Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given module m and code object c, what does "exec c in m.__dict__" do?

Tags:

python

exec

I'm writing Python 3 code and for some reason I want to run everything just in memory and save no files on disk. I managed to solve almost all of my problems so far by reading answers here, but I'm stuck on these lines:

>>> code = compile(source, filename, 'exec')
>>> exec code in module.__dict__

I don't really understand what the second line does, since I have "in" connected with loops and testing whether something is in some set or not which is not this case.

So, what does the second line do? And what is its Python 3 equivalent since in py3 is exec function, not keyword?

like image 695
user1687327 Avatar asked Sep 20 '12 22:09

user1687327


3 Answers

exec code in module.__dict__ 

means execute the commands in the file or string called 'code', taking global and local variables referred to in 'code' from module.__dict__ and storing local and global variables created in 'code' into the dictionary module.__dict__

See http://docs.python.org/reference/simple_stmts.html#exec

Eg:

In [51]: mydict={}

In [52]: exec "val1=100" in mydict

In [53]: mydict['val1']
Out[53]: 100

Eg2:

In [54]: mydict={}

In [55]: mydict['val2']=200

In [56]: exec "val1=val2" in mydict

In [57]: mydict.keys()
Out[57]: ['__builtins__', 'val2', 'val1']

In [58]: mydict['val2']
Out[58]: 200

In [59]: mydict['val1']
Out[59]: 200
like image 60
Riaz Rizvi Avatar answered Nov 05 '22 23:11

Riaz Rizvi


The in keyword specifies a dictionary to use for the global and local namespaces. From the python 2 documentation for exec:

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only the first expression after in is specified, it should be a dictionary, which will be used for both the global and the local variables.

The python 3 equivalent is thus exec(code, module.__dict__).

like image 45
Martijn Pieters Avatar answered Nov 05 '22 23:11

Martijn Pieters


In Python 3 that exec line would translate to:

exec(code, module.__dict__)

Excerpts from the Python 3 help files:

exec(object[, globals[, locals]]) 

In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables. If globals and locals are given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object.

like image 2
John Gaines Jr. Avatar answered Nov 05 '22 23:11

John Gaines Jr.