When I call execfile without passing the globals or locals arguments, it creates objects in the current namespace, but if I call execfile and set the dict for globals (and / or locals), it creates objects in the __builtin__ namespace.
Take the following example:
# exec.py def myfunc(): print 'myfunc created in %s namespace' % __name__
exec.py is execfile'd from main.py as follows.
# main.py print 'execfile in global namespace:' execfile('exec.py') myfunc() print print 'execfile in custom namespace:' d = {} execfile('exec.py', d) d['myfunc']()
when I run main.py from the command line, I get the following output.
execfile in global namespace: myfunc created in __main__ namespace execfile in custom namespace: myfunc created in __builtin__ namespace
Why is it running in the __builtin__ namespace in the second case?
Also, if I try to run myfunc from __builtins__ , I get an AttributeError. (This is what I hope will happen, but then why is __name__ set to __builtin__ ?)
>>> __builtins__.myfunc() Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'module' object has no attribute 'myfunc'
Can anyone explain this behavior? Thanks
source share