2012-11-07 14 views
5

Ho un modulo che importazioni multa (i stamparlo nella parte superiore del modulo che lo utilizza)Python è Nessuno

from authorize import cim 
print cim 

che produce:

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

Tuttavia più tardi in un metodo di chiamata, è misteriosamente trasformato in None

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

che quando eseguito mostrano che cim è None. Il modulo non è mai assegnato direttamente a None in questo modulo.

Qualche idea su come può accadere?

+3

Non credo sia possibile a meno che non v'è più il codice di te postato ... – wroniasty

+0

Chiaramente manca qualcosa, inviare più codice per favore. –

+5

In un punto intermedio, 'cim' deve essere stato usato come nome di variabile globale. –

risposta

4

Come commentate voi stessi - è probabile che un codice attribuisca Nessuno al nome "cim" sul vostro stesso modulo - il modo per verificarlo è se il vostro modulo di grandi dimensioni sarebbe "in sola lettura" per altri moduli - credo che Python permette per questo - (20 min. hacking)

-

qui - basta mettere questo frammento in un file "protect_module.py", importarlo, e chiamo "ProtectdedModule() "alla fine del modulo in cui il nome" cim "sta scomparendo - dovrebbe darti il ​​colpevole:

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