Skip to content

Instantly share code, notes, and snippets.

@internetimagery
Last active October 6, 2015 16:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save internetimagery/4be797eae970652385e6 to your computer and use it in GitHub Desktop.
Save internetimagery/4be797eae970652385e6 to your computer and use it in GitHub Desktop.
Auto load submodules in a package as they're used
# Stick the following in the bottom of your __init__.py, then simply import the base package. Use submodules as you need them and they'll be imported as you go.
import sys as _sys
class Package(object):
def __init__(s, local):
import os.path
s.cache = {}
s.local = dict((k, local[k]) for k in local)
s.root = os.path.realpath(os.path.dirname(s.local["__file__"]))
def __getattr__(s, k):
if k in s.local: return s.local[k]
if k in s.cache: return s.cache[k]
path = list(s.local["_sys"].path)
# s.local["_sys"].path.insert(0, s.root)
s.local["_sys"].path = [s.root]
try: s.cache[k] = __import__(k)
finally: s.local["_sys"].path[:] = path
return s.cache[k]
_sys.modules[__name__] = Package(locals())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment