March 6th, 2004, 12:53 PM
Could someone explain what this is used for in contrast to import?
March 6th, 2004, 12:57 PM
This function is invoked by the import statement. It mainly exists so that you can replace it with another function that has a compatible interface, in order to change the semantics of the import statement. For examples of why and how you would do this, see the standard library modules ihooksand rexec. See also the built-in module imp, which defines some useful operations out of which you can build your own __import__() function.
For example, the statement "import spam" results in the following call: __import__('spam', globals(), locals(), ); the statement "from spam.ham import eggs" results in "__import__('spam.ham', globals(), locals(), ['eggs'])". Note that even though locals() and ['eggs'] are passed in as arguments, the __import__() function does not set the local variable named eggs; this is done by subsequent code that is generated for the import statement. (In fact, 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.)
When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned. This is done for compatibility with the bytecode generated for the different kinds of import statement; when using "import spam.ham.eggs", the top-level package spam must be placed in the importing namespace, but when using "from spam.ham import eggs", the spam.ham subpackage must be used to find the eggs variable. As a workaround for this behavior, use getattr() to extract the desired components. For example, you could define the following helper:
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
March 6th, 2004, 01:35 PM
Ahh thanks, I've been looking for the documentation for the built-ins but I guess I've missed it every time