我在哪里可以阅读Python中的import _ {module name}?

时间:2010-06-21 07:48:04

标签: python

我注意到了这一点。例如:

创建一个名为ast.py

的空文本文件
$ touch ast.py

运行Python

$ python
>>> from ast import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> from _ast import *
>>> dir()
['AST', 'Add', 'And', 'Assert', 'Assign', ...]

ast是一个python模块。那么......这里发生了什么?我尝试使用空的os.py并且无法正常工作。

2 个答案:

答案 0 :(得分:3)

_xxx模块没有什么特别之处,除非它们是私有(例如_abcoll)或低级(例如_thread )并不打算一般使用。

_ast模块很特殊,例如

$ touch _ast.py
$ python -c 'from _ast import *; print(dir())'
['AST', 'Add', 'And', 'Assert', 'Assign', 'Attribute ...

但由于领先_,这,但_ast是内置模块。类似的事情发生在sys模块中。

$ touch sys.py
$ python -c 'from sys import *; print(dir())'
['__builtins__', '__doc__', '__name__', '__package__', 'api_version', 'argv', ...

在Python中_astast两个单独的模块。有一行

from _ast import *
内置ast.py中的

,因此导入ast也会带来_ast模块中的所有内容。这会让您产生_ast和{{1具有相同的内容but actually _ast is a lower level module of ast

答案 1 :(得分:2)

这是因为_ast 也是模块。这里没有魔力。此外,_ast是一个内置模块(即一个模块不作为单独的文件存在,但在解释器本身中编译),因此它总是被加载并且创建相同的文件不会摆脱它。

_ast不会被文件重载的原因是,一旦加载了一个模块,python将不再查看文件。您可以在sys.modules中找到当前加载的所有模块的列表。如果您需要有关模块的完整文档,请查看python文档。所有内容都已指定,例如:http://docs.python.org/tutorial/modules.html或此处:http://docs.python.org/reference/simple_stmts.html#the-import-statement