1

I'm solving some text2code problem for question-answering system and in the process I had the following question: Is it possible to run strings of code as complete code by passing arguments from the original environment? For example,I have these piece of code in str:

import module model=module(data,*args) 

And from base environment I want to do:

#for example args=[**some args**] data=pd.DataFrame() exec(string)(data=data,*args) 

For obvious reasons, transferring the data object using string.format() will not work. Standard unpacking using * does not work either, although, perhaps, I am doing something wrong.

1

1 Answer 1

1

exec can take 3 args: the string, globals var and locals var.

So you can do something like:

exec(string, globals(), locals()) 

to pass all variable. It might be faster to only pass a subset of it:

exec(string, None, {k: locals()[k] for k in ('data', 'args')})` 

For single expression you can use eval:

>>> i = 50 >>> eval("print(i)") 50 >>> 

How do I execute a string containing Python code in Python?

Sign up to request clarification or add additional context in comments.

2 Comments

eval is only suitable for executing single expressions, it is not capable of executing a string as full source code:(
Yep,it works.It was only necessary to indicate the names of the arguments in the string itself, for some reason I did not think of this right away.Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.