2013-08-29 29 views
0

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

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

回答

2

不,它不会被导入,也不会被加载。

此代码验证模块未添加到命名空间:

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

而这种代码证明import语句永远不会运行,否则它会产生一个ImportError。这意味着模块永远不会加载到以前导入的所有模块的sys.modules,cache (in the memory)中。

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

这主要是由于这样的事实,所有之前运行脚本,Python做是把它编译成字节码,因此不评估他们的occurence之前的语句。

+0

如果模块已加载,您还可以检查sys.modules。 –

+0

@GabrielSamfira你在评论我编辑我的答案时:) – edsioufi