Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are `globals` and `locals` parameters in Python __import__ function for?

Tags:

python

import

There's a part of __import__ in Python documentation, which I don't understand:

__import__(name[, globals[, locals[, fromlist[, level]]]])

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.

What is there to "interpret" about the module name? What is package context?

An example call using those parameters looks like this:

spam = __import__('spam', globals(), locals(), [], -1)

Why does the example provide globals() and locals() to the function? What happens when I only provide globals()? Or neither?

I am probably missing some part of the namespace logic with relation to importing modules. Could you point me to an article that explains this/has examples with __import__ function?

like image 462
Martin Tóth Avatar asked Feb 02 '11 09:02

Martin Tóth


2 Answers

The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.

(from docs.python.org)

I still have no idea how globals are used; what global variable can ever affect the way import statement works?

EDIT: After looking at import.c in Python 2.5 source I found that __import__ expects to find either __name__ or __path__ in globals in order to augment import search path relative to path(s) found in one of these variables, in that order.

like image 145
9000 Avatar answered Oct 06 '22 00:10

9000


globals is used to determine the current context on where the import is being called. For example:

"""
/myproject/a/b.py
/myproject/a/foo.py
/myproject/c/d.py
/myproject/c/foo.py
"""

# Which foo gets imported?

import foo #1
foo = __import__('foo') #2

They are not the same, since there is no (easy) way on #2 to know from which module the import is being called from. The __import__ function needs to know which is the current module to actually import the correct foo.

Internally on __import__(), globals is used to get the reference on the current module invoking the import. From the __import__ source code:

Return the package that an import is being performed in. If globals comes from the module foo.bar.bat (not itself a package), this returns the sys.modules entry for foo.bar. If globals is from a package's init.py, the package's entry in sys.modules is returned, as a borrowed reference.

like image 42
vz0 Avatar answered Oct 05 '22 23:10

vz0