Skip to content

Instantly share code, notes, and snippets.

@FurryHead
Created June 8, 2011 18:58
Show Gist options
  • Save FurryHead/1015084 to your computer and use it in GitHub Desktop.
Save FurryHead/1015084 to your computer and use it in GitHub Desktop.
Module loader, to replace (somewhat) python's import. Does not work on .pyc - it's mainly for user files.
import os, sys, new
modules = { }
def loadModule(moduleName, locals_dict={}):
"""
Imports a module without using the built-in import functions.
Parameters:
moduleName - The name of the module, same as if you were using __import__ or import
locals_dict - The dictionary of locals to use when loading the module.
globals_dict - The dictionary of globals to use when loading the module.
Returns the loaded module environment, similar to __import__ (but without using sys.modules, thus allowing re-loading)
"""
moduleFile = __find_file(moduleName)
fh = open(moduleFile, "rU")
exec fh in locals_dict
fh.close()
mod = new.module(moduleName)
setattr(mod, "__file__", moduleFile)
setattr(mod, "__name__", moduleName)
if moduleFile.endswith("__init__.py"):
setattr(mod, "__package__", moduleFile[:-12])
else:
setattr(mod, "__package__", None)
for k,v in locals_dict.items():
setattr(mod, k, v)
modules[moduleName] = mod
return mod
def __find_file(moduleName): #throws ImportError
moduleName = moduleName.replace(".", os.sep)
for path in sys.path:
if not path.endswith(".zip"):
if path == "":
if os.path.isfile(moduleName+".py"):
# if the module's location is in a package, call loadModule again to load the package first
if os.path.isfile(os.path.join(os.getcwd(), "__init__.py")):
loadModule(path)
return moduleName+".py"
elif os.path.isdir(moduleName):
if os.path.isfile(os.path.join(moduleName, "__init__.py")):
return os.path.join(moduleName, "__init__.py")
else:
raise ImportError("Invalid package. (missing __init__.py)")
else:
if os.path.isfile(os.path.join(path, moduleName+".py")):
# if the module's location is in a package, call loadModule again to load the package first
if os.path.isfile(os.path.join(path, "__init__.py")):
loadModule(path)
return os.path.join(path, moduleName+".py")
elif os.path.isdir(os.path.join(path, moduleName)):
if os.path.isfile(os.path.join(path, moduleName, "__init__.py")):
return os.path.join(path, moduleName, "__init__.py")
else:
raise ImportError("Invalid package. (missing __init__.py)")
#if we got here, we couldn't find the module or package
raise ImportError("No such module.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment