A call to execfile () in the user namespace executes code in the __builtin__ namespace

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

+4
source share
3 answers

Firstly, __name__ not a namespace - it is a reference to the name of the module to which it belongs, that is: somemod.py → somemod.__name__ == 'somemod' exception to this is that if you run the module as an executable file from the command line, then __name__ is "__main __".

in your example there is a happy coincidence that your module, which starts as the main one, is also called the main one.

Execfile executes the contents of a module WITHOUT importing it as a module. Thus, __name__ not installed because its not a module - its just an executable code sequence.

+4
source

The execfile function is similar to the exec statement. If you look at the documentation for exec , you will see the following paragraph explaining the behavior.

As a side effect, an implementation may insert additional keys into dictionaries specified in addition to those that correspond to variable names specified by the executable code. For example, the current implementation may add a link to the dictionary of the __builtin__ built-in module under the __builtins__ (!) Key.

Edit: now I see that my answer relates to one possible interpretation of the name of the question. My answer does not apply to the question asked.

+1
source

As an aside, I prefer to use __import__() over execfile :

 module = __import__(module_name) value = module.__dict__[function_name](arguments) 

This also works well when added to PYTHONPATH, so modules in other directories can be imported:

 sys.path.insert(position, directory) 
+1
source

All Articles