如何确定通过`from m import *`导入什么? [英] How to determine what is imported via `from m import *`?
问题描述
我正在对导入语句进行一些修补,我需要确切地知道从m import *
中导入了哪些成员.该文档似乎表明缺少 __ all __
时,将导入所有不以下划线开头的成员.在所有情况下这都是正确的吗?我知道 inspect.getmembers()
, dir()
和 m .__ dict __
的逻辑都略有不同,所以我并不完全确保哪个(如果有)将提供与 import *
相同的列表.
让我们看一下做什么:
>>>dis.dis(compile('from m import *','< module>','single'))1 0 LOAD_CONST 0(0)2 LOAD_CONST 1(('*',))4 IMPORT_NAME 0(m)6 IMPORT_STAR8 LOAD_CONST 2(无)10 RETURN_VALUE
此处的关键是它实际上会调用专用的操作码 IMPORT_STAR
,这是特定于将执行此代码的解释器的实现.该运算符最初是在 PEP-0221 中指定的,但是指定的实现详细信息在此特定提交引入的注释中.
在CPython中,可以在 /Python/ceval.c
(Python 3.7.2),然后依次调用 /pypy/interpreter/pyopcode.py
,再次类似于C实现它会调用 解决方案
Let's take a look at what that from m import *
statement does:
>>> dis.dis(compile('from m import *', '<module>', 'single'))
1 0 LOAD_CONST 0 (0)
2 LOAD_CONST 1 (('*',))
4 IMPORT_NAME 0 (m)
6 IMPORT_STAR
8 LOAD_CONST 2 (None)
10 RETURN_VALUE
The key here is that it actually invokes a dedicated opcode IMPORT_STAR
, and this is implementation specific to the interpreter that will execute this code. This operator was originally specified in PEP-0221 but the implementation details specified is in the comments introduced by this specific commit.
In CPython, this is found in /Python/ceval.c
(Python 3.7.2) and it in turns call import_all_from
which shows the general logic on what that actually does inside the bytecode interpreter.
In PyPy, this is found in /pypy/interpreter/pyopcode.py
, and again much like the C implementation it invokes the import_all_from
function defined in RPython, which again has a similar logic but in a more familiar syntax for Python programmers.
In both the CPython and pypy implementation, if __all__
is presented as a list of names inside the imported module, all matching assignments will be added to the current local scope, including those names that are prefixed with an underscore (_
). Otherwise, every assignment inside the module that do not start with an underscore will be added to the current local scope.
这篇关于如何确定通过`from m import *`导入什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!