我有一个导入良好的模块(我将它打印在使用它的模块的顶部)
from authorize import cim
print cim
产生:
<module 'authorize.cim' from '.../dist-packages/authorize/cim.pyc'>
然而后来在方法调用中,它神秘地变成了None
class MyClass(object):
def download(self):
print cim
运行时显示 cim
为 None
。该模块从未直接分配给此模块中任何位置的 None
。
知道这是怎么发生的吗?
最佳答案
正如您自己评论的那样 - 很可能某些代码将 None 归因于模块本身的“cim”名称 - 检查这一点的方法是如果你的大模块将被其他模块设置为“只读” - - 我认为 Python 允许这样做 -
(20 分钟黑客攻击)--
这里 -- 只需将此代码段放入“protect_module.py”文件中,导入它,然后调用 模块末尾的“ProtectdedModule()”,名称“cim”正在消失 - 它应该给你罪魁祸首:
"""
Protects a Module against naive monkey patching -
may be usefull for debugging large projects where global
variables change without notice.
Just call the "ProtectedModule" class, with no parameters from the end of
the module definition you want to protect, and subsequent assignments to it
should fail.
"""
from types import ModuleType
from inspect import currentframe, getmodule
import sys
class ProtectedModule(ModuleType):
def __init__(self, module=None):
if module is None:
module = getmodule(currentframe(1))
ModuleType.__init__(self, module.__name__, module.__doc__)
self.__dict__.update(module.__dict__)
sys.modules[self.__name__] = self
def __setattr__(self, attr, value):
frame = currentframe(1)
raise ValueError("Attempt to monkey patch module %s from %s, line %d" %
(self.__name__, frame.f_code.co_filename, frame.f_lineno))
if __name__ == "__main__":
from xml.etree import ElementTree as ET
ET = ProtectedModule(ET)
print dir(ET)
ET.bla = 10
print ET.bla
关于Python 导入模块为 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13274916/