0

我知道可以有条件地导入模块。我的问题是;如果导入模块的条件为假,模块是否仍然被加载(并且只是在后台闲置),或者不。

我从资源的角度问这个问题。例如,使用 Raspberry Pi 进行编程确实有其局限性。这只是一个假设性问题......我还没有遇到任何问题。

4

1 回答 1

2

No, it is not imported, and it is not loaded.

This code verifies that the module is not added to the namespace:

>>> if False:
...     import time
... else:
...     time.clock()
...
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
NameError: name 'time' is not defined

And this code proves that the import statement is never run, as otherwise it would have generated an ImportError. This means that the module is never loaded in sys.modules, the cache (in the memory) of all modules that have been imported previously.

>>> if False:
...     import thismoduledoesnotexist
...
>>> import thismoduledoesnotexist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named thismoduledoesnotexist

This is mainly due to the fact that all that Python does prior to running the script is compile it to bytecode, and as such does not evaluate the statements before their occurence.

于 2013-08-29T09:22:24.293 回答