Python导入细微差别

2024-06-26 01:53:33 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释一下Python解释器中的这种行为:

from os import path    # success
type(path)             # <class 'module'>
from path import *     # complains that no module called 'path' exists 

type(os.path)          # complains that the name 'os' is not defined, yet:
from os.path import *  # works just fine

作为一个附带的问题,我想知道是什么机制允许诸如“from os import path”这样的语句在操作系统尚未定义的情况下工作?操作系统不是在from…import时执行的,因此它应该被称为一个模块?我是否可以说,将操作系统排除在已知名称之外仅仅是一种约定,旨在防止未直接导入的符号(如“导入操作系统”)对名称空间的“污染”?在


Tags: pathnofromimport名称thatostype
1条回答
网友
1楼 · 发布于 2024-06-26 01:53:33

这并不是python3特有的,在python2中也会遇到同样的问题。导入名称会将其添加到名称空间,仅此而已。在

这条线:

from path import *

指:

"Try to find a module called path in any directory that is in PYTHONPATH, and attempt to import all names from it to the current namespace."

由于当前工作目录中没有这样的模块,更重要的是在PYTHONPATH中的任何目录中都没有这样的模块,因此导入失败。注意,搜索不会搜索PYTHONPATH中任何目录的子目录。在

^{pr2}$

此行失败,因为当前命名空间中没有名称os(因为它没有导入)。在

I wonder what is the mechanism that allows a statement such as 'from os import path' to work, while yet still os is undefined?

导入会导致搜索在PYTHONPATH中定义的路径以查找模块;有关导入如何工作的更多说明,请参见this article on effbot。在

“Undefined”只是表示名称空间中不存在该名称。在

Isn't os executed at the time of the from...import, and such it should be "known" as a module?

不,当您这样做时,from x import y只导入y,而不是{}。在

Am I right to say that keeping os out of the known names is simply a convention, intended to prevent the "polution" of the namespace with symbols that have not been imported directly (as in 'import os')?

不,这不是真的(我希望你明白为什么)。在

相关问题 更多 >