PKc47SBEGG-INFO/namespace_packages.txtpeak peak.util PKc4EGG-INFO/not-zip-safePKc4EEGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: Importing Version: 1.9.1 Summary: Import objects dynamically, lazily, "weakly", and more. Home-page: http://peak.telecommunity.com/DevCenter/Importing Author: Phillip J. Eby Author-email: peak@eby-sarna.com License: PSF or ZPL Description: Need to import an object when all you've got is its name? Need to lazily import modules, such that they don't actually get loaded until you use them? Want to have some code in a module that only gets run *if* another module is imported? Then you need the "Importing" toolkit. Installing the toolkit (using ``"easy_install Importing"`` or ``"setup.py install"``) allows you to access the ``peak.util.imports`` module. This module was previously bundled for years inside of the general PEAK distribution, but is now available as a standalone module for your convenience. The "Importing" toolkit does not install or use any special import hooks, and is compatible with zipfile imports, ``py2exe``, etc. Lazy and weak imports should be compatible with almost any import hooks or hacks, as long as they have reasonable support for the ``reload()`` builtin. The dynamic import utilities, however, require only that ``__import__()`` work correctly, and so should work anywhere that normal Python imports work. Platform: UNKNOWN PKc40-e  EGG-INFO/SOURCES.txtREADME.txt setup.py Importing.egg-info/PKG-INFO Importing.egg-info/SOURCES.txt Importing.egg-info/namespace_packages.txt Importing.egg-info/top_level.txt ez_setup/README.txt ez_setup/__init__.py peak/__init__.py peak/util/__init__.py peak/util/imports.py PKc4EGG-INFO/top_level.txtpeak PK4k<99peak/__init__.py__import__('pkg_resources').declare_namespace(__name__) PKc4((peak/__init__.pyc; sDc@sediedS(s pkg_resourcesN(s __import__sdeclare_namespaces__name__(((s&build\bdist.win32\egg\peak\__init__.pys?sPKb4N G,G,peak/util/imports.py"""Tools for doing dynamic imports""" __all__ = [ 'importString', 'importObject', 'importSequence', 'importSuite', 'lazyModule', 'joinPath', 'whenImported', 'getModuleHooks', ] import __main__, sys defaultGlobalDict = __main__.__dict__ from types import StringTypes, ModuleType from sys import modules try: from peak.util.EigenData import AlreadyRead except ImportError: class AlreadyRead(Exception):pass def importSuite(specs, globalDict=defaultGlobalDict): """Create a test suite from import specs""" from unittest import TestSuite return TestSuite( [t() for t in importSequence(specs,globalDict)] ) def joinPath(modname, relativePath): """Adjust a module name by a '/'-separated, relative or absolute path""" module = modname.split('.') for p in relativePath.split('/'): if p=='..': module.pop() elif not p: module = [] elif p!='.': module.append(p) return '.'.join(module) def importString(name, globalDict=defaultGlobalDict): """Import an item specified by a string Example Usage:: attribute1 = importString('some.module:attribute1') attribute2 = importString('other.module:nested.attribute2') 'importString' imports an object from a module, according to an import specification string: a dot-delimited path to an object in the Python package namespace. For example, the string '"some.module.attribute"' is equivalent to the result of 'from some.module import attribute'. For readability of import strings, it's sometimes helpful to use a ':' to separate a module name from items it contains. It's optional, though, as 'importString' will convert the ':' to a '.' internally anyway.""" if ':' in name: name = name.replace(':','.') parts = filter(None,name.split('.')) item = __import__(parts.pop(0), globalDict, globalDict, ['__name__']) # Fast path for the common case, where everything is imported already for attr in parts: try: item = getattr(item, attr) except AttributeError: break # either there's an error, or something needs importing else: return item # We couldn't get there with just getattrs from the base import. So now # we loop *backwards* trying to import longer names, then shorter, until # we find the longest possible name that can be handled with __import__, # then loop forward again with getattr. This lets us give more meaningful # error messages than if we only went forwards. attrs = [] exc = None try: while True: try: # Exit as soon as we find a prefix of the original `name` # that's an importable *module* or package item = __import__(name, globalDict, globalDict, ['__name__']) break except ImportError: if not exc: # Save the first ImportError, as it's usually the most # informative, especially w/Python < 2.4 exc = sys.exc_info() if '.' not in name: # We've backed up all the way to the beginning, so reraise # the first ImportError we got raise exc[0],exc[1],exc[2] # Otherwise back up one position and try again parts = name.split('.') attrs.append(parts[-1]) name = '.'.join(parts[:-1]) finally: exc = None # Okay, the module object is now in 'item', so we can just loop forward # to retrieving the desired attribute. # while attrs: attr = attrs.pop() try: item = getattr(item,attr) except AttributeError: raise ImportError("%r has no %r attribute" % (item,attr)) return item def lazyModule(modname, relativePath=None): """Return module 'modname', but with its contents loaded "on demand" This function returns 'sys.modules[modname]', if present. Otherwise it creates a 'LazyModule' object for the specified module, caches it in 'sys.modules', and returns it. 'LazyModule' is a subclass of the standard Python module type, that remains empty until an attempt is made to access one of its attributes. At that moment, the module is loaded into memory, and any hooks that were defined via 'whenImported()' are invoked. Note that calling 'lazyModule' with the name of a non-existent or unimportable module will delay the 'ImportError' until the moment access is attempted. The 'ImportError' will occur every time an attribute access is attempted, until the problem is corrected. This function also takes an optional second parameter, 'relativePath', which will be interpreted as a '/'-separated path string relative to 'modname'. If a 'relativePath' is supplied, the module found by traversing the path will be loaded instead of 'modname'. In the path, '.' refers to the current module, and '..' to the current module's parent. For example:: fooBaz = lazyModule('foo.bar','../baz') will return the module 'foo.baz'. The main use of the 'relativePath' feature is to allow relative imports in modules that are intended for use with module inheritance. Where an absolute import would be carried over as-is into the inheriting module, an import relative to '__name__' will be relative to the inheriting module, e.g.:: something = lazyModule(__name__,'../path/to/something') The above code will have different results in each module that inherits it. (Note: 'relativePath' can also be an absolute path (starting with '/'); this is mainly useful for module '__bases__' lists.)""" def _loadModule(module): oldGA = LazyModule.__getattribute__ oldSA = LazyModule.__setattr__ modGA = ModuleType.__getattribute__ modSA = ModuleType.__setattr__ LazyModule.__getattribute__ = modGA LazyModule.__setattr__ = modSA try: # Get Python (or supplied 'reload') to do the real import! _loadAndRunHooks(module) except: # Reset our state so that we can retry later if '__file__' not in module.__dict__: LazyModule.__getattribute__ = oldGA.im_func LazyModule.__setattr__ = oldSA.im_func raise try: # Convert to a real module (if under 2.2) module.__class__ = ModuleType except TypeError: pass # 2.3 will fail, but no big deal class LazyModule(ModuleType): __slots__ = () def __init__(self, name): ModuleType.__setattr__(self,'__name__',name) #super(LazyModule,self).__init__(name) def __getattribute__(self,attr): _loadModule(self) return ModuleType.__getattribute__(self,attr) def __setattr__(self,attr,value): _loadModule(self) return ModuleType.__setattr__(self,attr,value) if relativePath: modname = joinPath(modname, relativePath) if modname not in modules: getModuleHooks(modname) # force an empty hook list into existence modules[modname] = LazyModule(modname) if '.' in modname: # ensure parent module/package is in sys.modules # and parent.modname=module, as soon as the parent is imported splitpos = modname.rindex('.') whenImported( modname[:splitpos], lambda m: setattr(m,modname[splitpos+1:],modules[modname]) ) return modules[modname] postLoadHooks = {} def _loadAndRunHooks(module): """Load an unactivated "lazy" module object""" # if this fails, we haven't called the hooks, so leave them in place # for possible retry of import if module.__dict__.keys()==['__name__']: # don't reload if already loaded! reload(module) try: for hook in getModuleHooks(module.__name__): hook(module) finally: # Ensure hooks are not called again, even if they fail postLoadHooks[module.__name__] = None def getModuleHooks(moduleName): """Get list of hooks for 'moduleName'; error if module already loaded""" hooks = postLoadHooks.setdefault(moduleName,[]) if hooks is None: raise AlreadyRead("Module already imported", moduleName) return hooks def _setModuleHook(moduleName, hook): if moduleName in modules and postLoadHooks.get(moduleName) is None: # Module is already imported/loaded, just call the hook module = modules[moduleName] hook(module) return module getModuleHooks(moduleName).append(hook) return lazyModule(moduleName) def whenImported(moduleName, hook): """Call 'hook(module)' when module named 'moduleName' is first used 'hook' must accept one argument: the module object named by 'moduleName', which must be a fully qualified (i.e. absolute) module name. The hook should not raise any exceptions, or it may prevent later hooks from running. If the module has already been imported normally, 'hook(module)' is called immediately, and the module object is returned from this function. If the module has not been imported, or has only been imported lazily, then the hook is called when the module is first used, and a lazy import of the module is returned from this function. If the module was imported lazily and used before calling this function, the hook is called immediately, and the loaded module is returned from this function. Note that using this function implies a possible lazy import of the specified module, and lazy importing means that any 'ImportError' will be deferred until the module is used. """ if '.' in moduleName: # If parent is not yet imported, delay hook installation until the # parent is imported. splitpos = moduleName.rindex('.') whenImported( moduleName[:splitpos], lambda m: _setModuleHook(moduleName,hook) ) else: return _setModuleHook(moduleName,hook) def importObject(spec, globalDict=defaultGlobalDict): """Convert a possible string specifier to an object If 'spec' is a string or unicode object, import it using 'importString()', otherwise return it as-is. """ if isinstance(spec,StringTypes): return importString(spec, globalDict) return spec def importSequence(specs, globalDict=defaultGlobalDict): """Convert a string or list specifier to a list of objects. If 'specs' is a string or unicode object, treat it as a comma-separated list of import specifications, and return a list of the imported objects. If the result is not a string but is iterable, return a list with any string/unicode items replaced with their corresponding imports. """ if isinstance(specs,StringTypes): return [importString(x.strip(),globalDict) for x in specs.split(',')] else: return [importObject(s,globalDict) for s in specs] PKc4&s1s1peak/util/imports.pyc; uDc@sdZddddddddgZd kZd kZeiZd klZlZd kl Z yd k l Z Wn)e j od e fdYZ nXedZdZedZedZhZdZdZdZdZedZedZd S(sTools for doing dynamic importss importStrings importObjectsimportSequences importSuites lazyModulesjoinPaths whenImportedsgetModuleHooksN(s StringTypess ModuleType(smodules(s AlreadyReads AlreadyReadcBstZRS(N(s__name__s __module__(((s*build\bdist.win32\egg\peak\util\imports.pys AlreadyReadscCsHdkl}|gi}t||D]}||q'~SdS(s%Create a test suite from import specs(s TestSuiteN(sunittests TestSuitesappends_[1]simportSequencesspecss globalDictst(sspecss globalDicts TestSuites_[1]st((s*build\bdist.win32\egg\peak\util\imports.pys importSuites cCs|id}xb|idD]Q}|djo|iq| o g}q|djo|i|qqWdi|SdS(sBAdjust a module name by a '/'-separated, relative or absolute paths.s/s..N(smodnamessplitsmodules relativePathspspopsappendsjoin(smodnames relativePathsmodulesp((s*build\bdist.win32\egg\peak\util\imports.pysjoinPaths   cCsd|jo|idd}ntt|id}t|id||dg}x<|D]0}yt ||}Wqct j oPqcXqcW|Sg}t}zxtoyt|||dg}PWqtj o{| oti}nd|jo|d|d|dn|id}|i|ddi|d }qXqWWdt}XxW|oO|i}yt ||}Wqnt j otd ||fqnXqnW|SdS( sImport an item specified by a string Example Usage:: attribute1 = importString('some.module:attribute1') attribute2 = importString('other.module:nested.attribute2') 'importString' imports an object from a module, according to an import specification string: a dot-delimited path to an object in the Python package namespace. For example, the string '"some.module.attribute"' is equivalent to the result of 'from some.module import attribute'. For readability of import strings, it's sometimes helpful to use a ':' to separate a module name from items it contains. It's optional, though, as 'importString' will convert the ':' to a '.' internally anyway.s:s.is__name__iiiNs%r has no %r attribute(snamesreplacesfiltersNonessplitspartss __import__spops globalDictsitemsattrsgetattrsAttributeErrorsattrssexcsTrues ImportErrorssyssexc_infosappendsjoin(snames globalDictsitemspartssattrssexcsattr((s*build\bdist.win32\egg\peak\util\imports.pys importString*sL !  !  csddtfdY|ot|ntjoXttsN( s _loadModules ModuleTypes LazyModules relativePathsjoinPathsmodnamesmodulessgetModuleHookssrindexssplitposs whenImported(smodnames relativePaths LazyModulessplitposs _loadModule((smodnames LazyModules _loadModulessplitposs*build\bdist.win32\egg\peak\util\imports.pys lazyModule|s'     cCsd|iidgjot|nz(x!t|iD]}||q:WWdtt|i;sN(s moduleNamesrindexssplitposs whenImporteds_setModuleHookshook(s moduleNameshookssplitpos((s moduleNameshooks*build\bdist.win32\egg\peak\util\imports.pys whenImported s  cCs)t|tot||Sn|SdS(sConvert a possible string specifier to an object If 'spec' is a string or unicode object, import it using 'importString()', otherwise return it as-is. N(s isinstancesspecs StringTypess importStrings globalDict(sspecs globalDict((s*build\bdist.win32\egg\peak\util\imports.pys importObjectIscCst|toAgi}|idD]}|t|i|q'~Sn/gi}|D]}|t ||q_~SdS(soConvert a string or list specifier to a list of objects. If 'specs' is a string or unicode object, treat it as a comma-separated list of import specifications, and return a list of the imported objects. If the result is not a string but is iterable, return a list with any string/unicode items replaced with their corresponding imports. s,N( s isinstancesspecss StringTypessappends_[1]ssplitsxs importStringsstrips globalDictsss importObject(sspecss globalDicts_[1]sssx((s*build\bdist.win32\egg\peak\util\imports.pysimportSequenceWs A(s__doc__s__all__s__main__ssyss__dict__sdefaultGlobalDictstypess StringTypess ModuleTypesmodulesspeak.util.EigenDatas AlreadyReads ImportErrors Exceptions importSuitesjoinPaths importStringsNones lazyModules postLoadHookss_loadAndRunHookssgetModuleHookss_setModuleHooks whenImporteds importObjectsimportSequence(simportSequences__main__s importObjects AlreadyReads lazyModules postLoadHookss__all__s whenImporteds StringTypess ModuleTypessyss_setModuleHooks importStrings_loadAndRunHookssmodulessgetModuleHookssdefaultGlobalDicts importSuitesjoinPath((s*build\bdist.win32\egg\peak\util\imports.pys?s(    R e   ) PK4(88peak/util/__init__.py__import__('pkg_resources').declare_namespace(__name__) PKc4%peak/util/__init__.pyc; sDc@sediedS(s pkg_resourcesN(s __import__sdeclare_namespaces__name__(((s+build\bdist.win32\egg\peak\util\__init__.pys?sPKc47SBEGG-INFO/namespace_packages.txtPKc4LEGG-INFO/not-zip-safePKc4EEGG-INFO/PKG-INFOPKc40-e  bEGG-INFO/SOURCES.txtPKc4EGG-INFO/top_level.txtPK4k<99peak/__init__.pyPKc4((>peak/__init__.pycPKb4N G,G,: peak/util/imports.pyPKc4&s1s15peak/util/imports.pycPK4(88Ygpeak/util/__init__.pyPKc4%gpeak/util/__init__.pycPK h