"""Copyright 2009 55 Minutes (http://www.55minutes.com)Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License."""importimp,sys,types__all__=('find_or_load_module',)def_brute_force_find_module(module_name,module_path,module_type):formin[mforn,minsys.modules.iteritems()iftype(m)==types.ModuleType]:m_path=[]try:ifmodule_typein(imp.PY_COMPILED,imp.PY_SOURCE):m_path=[m.__file__]elifmodule_type==imp.PKG_DIRECTORY:m_path=m.__path__exceptAttributeError:passforpinm_path:ifp.startswith(module_path):returnmreturnNonedef_load_module(module_name,fo,fp,desc):suffix,mode,mtype=descifmodule_nameinsys.modulesand \
sys.modules[module_name].__file__.startswith(fp):module=sys.modules[module_name]else:module=_brute_force_find_module(module_name,fp,mtype)ifnotmodule:try:module=imp.load_module(module_name,fo,fp,desc)except:raiseImportErrorreturnmoduledef_load_package(pkg_name,fp,desc):suffix,mode,mtype=descifpkg_nameinsys.modules:iffpinsys.modules[pkg_name].__path__:pkg=sys.modules[pkg_name]else:pkg=Noneelse:pkg=_brute_force_find_module(pkg_name,fp,mtype)ifnotpkg:pkg=imp.load_module(pkg_name,None,fp,desc)returnpkgdeffind_or_load_module(module_name,path=None):""" Attempts to lookup ``module_name`` in ``sys.modules``, else uses the facilities in the ``imp`` module to load the module. If module_name specified is not of type ``imp.PY_SOURCE`` or ``imp.PKG_DIRECTORY``, raise ``ImportError`` since we don't know what to do with those. """fo,fp,desc=imp.find_module(module_name.split('.')[-1],path)suffix,mode,mtype=descifmtypein(imp.PY_SOURCE,imp.PY_COMPILED):module=_load_module(module_name,fo,fp,desc)elifmtype==imp.PKG_DIRECTORY:module=_load_package(module_name,fp,desc)else:raiseImportError("Don't know how to handle this module type.")returnmodule