我想导入模块,但导入的行为可能会有所不同,具体取决于我要施加的某些外部条件。有什么策略可以实现这个结果?导入模块并在导入时更改模块行为
示例。我想要一个模块foo.py.如果我import foo
根据某些与模块无关的外部条件,我会得到“你好”或“再见”的打印,而取决于外部因素。一个微不足道的可能是一个全局变量,但我不认为python范围规则允许我从模块foo之外获取全局变量。
例子:
fop.py
import __main__
try:
__main__.bar
present = True
except:
present = False
if present:
print "present"
else:
print "not present"
现在,当我输入的模块,我可以得到不同的结果
Python 2.7.1 (r271:86832, Feb 27 2011, 20:04:04)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
not present
>>>
Python 2.7.1 (r271:86832, Feb 27 2011, 20:04:04)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> bar = 5
>>> import foo
present
我知道这很奇怪,但我有一个非常,这是非常非常好的理由。
听起来像没有人会明白的代码... – 2011-04-27 16:06:16
塞巴斯蒂安:这是_exactly_我想要达到的效果 – 2011-04-27 16:06:42
您可以举一个用例的例子吗?如外部条件的一个例子,什么构成“行为不同”? – samplebias 2011-04-27 16:10:51