12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

import typesdef status(module):print 'reloading', module._ _name_ _def transitive_reload(module, visited):if not visited.has_key(module):# Trap cycles, dupsstatus(module) # Reload this modulereload(module)# And visit childrenvisited[module] = Nonefor attrobj in module._ _dict_ _.values( ): # For all attrsif type(attrobj) == types.ModuleType: # Recur if moduletransitive_reload(attrobj, visited)def reload_all(*args):visited = { }for arg in args:if type(arg) == types.ModuleType:transitive_reload(arg, visited)if __name__ == '_ _main_ _':import reloadallreload_all(reloadall)# Test code: reload myself# Should reload this, typesRecursive from Imports May Not WorkI saved the most bizarre (and, thankfully, obscure) gotcha for last. Because importsexecute a file’s statements from top to bottom, you need to be careful when usingmodules that import each other (known as recursive imports). Because the statementsin a module may not all have been run when it imports another module, someof its names may not yet exist.If you use import to fetch the module as a whole, this may or may not matter; themodule’s names won’t be accessed until you later use qualification to fetch their values.But, if you use from to fetch specific names, you must bear in mind that you willonly have access to names in that module that have already been assigned.For instance, take the following modules, recur1 and recur2. recur1 assigns a nameX, and then imports recur2 before assigning the name Y. At this point, recur2 canfetch recur1 as a whole with an import (it already exists in <strong>Python</strong>’s internal modulestable), but if it uses from, it will be able to see only the name X; the name Y, which isassigned below the import in recur1, doesn’t yet exist, so you get an error:# File: recur1.pyX = 1import recur2Y = 2# Run recur2 now if it doesn't exist# File: recur2.pyfrom recur1 import Xfrom recur1 import Y# OK: "X" already assigned# Error: "Y" not yet assignedModule Gotchas | 443

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!