我想導入模塊,但導入的行爲可能會有所不同,具體取決於我要施加的某些外部條件。有什麼策略可以實現這個結果?導入模塊並在導入時更改模塊行爲
示例。我想要一個模塊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