سؤال

Assume we have package named 'package', it has a module 'module'.

If we

from package import module

Since 'package' is loaded, will package's local namespace has a name 'module'?

We can see a phrase like this in reference of 'import':

The first form of import statement binds the module name in the local namespace to the module object, and then goes on to import the next identifier, if any. If the module name is followed by as, the name following as is used as the local name for the module.

The from form does not bind the module name: it goes through the list of identifiers, looks each one of them up in the module found in step (1), and binds the name in the local namespace to the object thus found. As with the first form of import, an alternate local name can be supplied by specifying “as localname”. If a name is not found, ImportError is raised. If the list of identifiers is replaced by a star ('*'), all public names defined in the module are bound in the local namespace of the import statement..

What does it mean by "The from form does not bind the module name" in the second paragraph?

هل كانت مفيدة؟

المحلول

Yes, the package.__init__ module will have access to the name module:

$ mkdir package
$ touch package/__init__.py
$ touch package/module.py
$ python
Python 2.7.5 (default, Oct 28 2013, 20:45:48) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from package import module
>>> import sys
>>> sys.modules['package']
<module 'package' from 'package/__init__.py'>
>>> dir(sys.modules['package'])
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'module']
>>> sys.modules['package'].module
<module 'package.module' from 'package/module.py'>

The second paragraph you refer to talks about what names are bound by a from foo import bar import statement. bar is bound, foo is not. Or, in terms of the above demonstration:

>>> module
<module 'package.module' from 'package/module.pyc'>
>>> package
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'package' is not defined

The from package import module statement added a module name to the namespace, but package was not bound.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top