2012-11-07 27 views
5

है मैं है एक मॉड्यूल है कि ठीक आयातअजगर आयातित मॉड्यूल कोई नहीं

from authorize import cim 
print cim 

कौन सा पैदा करता है (मैं यह मॉड्यूल यह का उपयोग करता है के शीर्ष पर मुद्रित):

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

हालांकि बाद में एक में विधि कॉल, यह रहस्यमय तरीके से None

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

जो जब किशो चलाने के लिए बदल गया हैNone है। मॉड्यूल को इस मॉड्यूल में कहीं भी सीधे None पर असाइन नहीं किया गया है।

कोई विचार यह कैसे हो सकता है?

+3

मैं यह संभव है जब तक कि वहाँ अधिक कोड से तुम्हें तैनात है नहीं लगता है ... – wroniasty

+0

जाहिर है कुछ याद आ रही है, पोस्ट अधिक कोड कृपया। –

+5

कहीं बीच में, 'cim' को वैश्विक चर नाम के रूप में उपयोग किया जाना चाहिए। –

उत्तर

4

जैसा कि आप इसे स्वयं टिप्पणी करते हैं - ऐसा लगता है कि कुछ कोड आपके मॉड्यूल पर "सीम" नाम से कोई भी जिम्मेदार नहीं है - इसके लिए जांच करने का तरीका यह है कि यदि आपका बड़ा मॉड्यूल अन्य मॉड्यूल के लिए "केवल पढ़ने" के लिए बनाया जाएगा - मैं अजगर इस के लिए अनुमति देता है लगता है - (। 20 मिनट हैकिंग)

-

यहाँ - बस एक "protect_module.py" फ़ाइल में इस स्निपेट यहीं है, यह आयात करते हैं और कहते हैं "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 
संबंधित मुद्दे