Python 导入模块为 None

标签 python

我有一个导入良好的模块(我将它打印在使用它的模块的顶部)

from authorize import cim
print cim

产生:

<module 'authorize.cim' from '.../dist-packages/authorize/cim.pyc'>

然而后来在方法调用中,它神秘地变成了None

class MyClass(object):
    def download(self):
        print cim

运行时显示 cimNone。该模块从未直接分配给此模块中任何位置的 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/

相关文章:

python - __slots__ 在 Python 中是如何实现的?

python - 如何在考虑到每个点的位置和方向的情况下连接点

python - 查找包含子字符串的列并替换它 - Pandas

python - 基于条件的 Pandas DataFrame 重复值

python - 如何扩展 `psycopg2.extras.DictCursor`?

python - 扭曲的http客户端

python - 使用托管身份在 python 中被 azure 函数应用程序卡住

python - 使用包含单引号的 json 更新 PostgreSQL 中的 jsonb 字段

python - Flask - 在 Ajax/JQuery 中无需重定向即可更新页面内容

python - 在多个模式之前查找数字序列的正则表达式,放入新列(Python、Pandas)