VJasdf
VJasdf

Reputation: 1378

Why there is a difference in "import" vs. "import *"?

"""module a.py"""
test = "I am test"
_test = "I am _test"
__test = "I am __test"

=============

~ $ python
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) 
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from a import *
>>> test
'I am test'
>>> _test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_test' is not defined
>>> __test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__test' is not defined
>>> import a
>>> a.test
'I am test'
>>> a._test
'I am _test'
>>> a.__test
'I am __test'
>>> 

Upvotes: 6

Views: 706

Answers (1)

monkut
monkut

Reputation: 43830

Variables with a leading "_" (underbar) are not public names and will not be imported when from x import * is used.

Here, _test and __test are not public names.

From the import statement description:

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..

The public names defined by a module are determined by checking the module’s namespace for a variable named __all__; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in __all__ are all considered public and are required to exist. If __all__ is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_'). __all__ should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).

Upvotes: 21

Related Questions