Why is there a difference in "import" and "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' >>> 
+6
python import
source share
1 answer

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

Here _test and __test are not publicly available.

From the import description:

If the identifier list is replaced with a star ('*'), all public names defined in the module are linked to the local namespace of the import expression ..

The public names defined by the module are determined by checking the variable namespace for the variable named __all__; if defined, it should be a sequence of strings that are names defined or imported by this module. The names indicated in __all__ are all considered publicly available and must exist. If __all__ is not defined, the set of public names includes all the names found in the module namespace, which do not start with the underscore character ('_'). __all__ should contain the entire open API. this is to avoid accidentally exporting items that are not part of the API (for example, library modules that were imported and used as part of a module).

+21
source share

All Articles