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?
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
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__)
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With