Skip to content

Instantly share code, notes, and snippets.

@bplaxco
Created September 25, 2015 15:17
Show Gist options
  • Save bplaxco/bc8511b90903efcfefb5 to your computer and use it in GitHub Desktop.
Save bplaxco/bc8511b90903efcfefb5 to your computer and use it in GitHub Desktop.
An __init__.py to break classes up into single files without changing the import path.
# Import classes from files in the sub directory
# so files in models/ClassName.py with ClassName in it
# can be imported as models.ClassName
import pkgutil
__all__ = []
for _, name, ispkg in pkgutil.walk_packages(__path__):
if not name.startswith('__') and not ispkg:
# Ex: apps.assessment.models.<name>
full_name = '.'.join([__name__, name])
# Get the module that is holding the class
module = __import__(full_name, fromlist=[name])
# Get the class from the module and bring it into the global name space
globals()[name] = getattr(module, name)
# Add it to the __all__ array for * imports
__all__.append(name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment