Python导入的模块为None。

6

我有一个模块,成功地导入了(我在使用该模块的模块顶部打印了它)。

from authorize import cim
print cim

这将产生:

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

然而,在方法调用之后,它神奇地变成了None
class MyClass(object):
    def download(self):
        print cim

当运行时显示是。在此模块中,该模块从未直接分配给。任何想法如何发生这种情况?

3
除非你贴出更多的代码,否则我认为这是不可能的。 - wroniasty
5
在某个地方,cim 一定被用作全局变量名。 - Fred Foo
1
我会简单地添加打印语句和二分查找来找到代码的变化点。@MartijnPieters:错过的赋值仍然是最有可能的问题,但我认为曾经由于名称冲突和星号导入而出现了神秘的None模块。(现在我大多数情况下都学习得更好了。) - DSM
@DSM: 我非常同意; 我只是展示了另一个模块搞乱名称空间的可能性是多么的不可能。 :-) - Martijn Pieters
1
我在模块底部有一个测试,用于演示问题。在解决问题之前,我已对其余代码进行了注释。现在我知道它绝对是导入引起的 None。我没想到导入可能会影响它,这让我想到它与Django中的模型加载有关(因为这是一个models.py文件)。 - leech
显示剩余6条评论
2个回答

5

正如您所评论的一样 - 可能有些代码将None分配给您模块本身的 "cim"名称 - 检查方法是,如果其他模块将使您的大型模块成为“只读” - 我认为Python允许这样做 -

(20分钟黑客) -

在此处 - 只需将此片段放入“protect_module.py”文件中,导入它,并在名称“cim”消失的模块末尾调用“ProtectdedModule()”,它应该给你罪犯:

"""
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

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接