Skip to content

Instantly share code, notes, and snippets.

@kageurufu
Created August 30, 2017 22:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kageurufu/4a39f1821b9ec5e8e02fa3d9982b97d4 to your computer and use it in GitHub Desktop.
Save kageurufu/4a39f1821b9ec5e8e02fa3d9982b97d4 to your computer and use it in GitHub Desktop.
Auto-import all files in a module
"""
Import all files and packages under a module into the calling file's
locals, and set __all__ to all imported modules
May be cpython only, due to abuse of ``inspect``
"""
import importlib
import inspect
import os
def get_module_name(module):
return module.__name__.split('.')[-1]
def import_module_files():
caller = inspect.stack()[1]
caller__package__ = caller.frame.f_locals['__package__']
caller__file__ = caller.frame.f_locals['__file__']
module_dir = os.path.dirname(caller__file__)
modules = [
importlib.import_module('.{}'.format(filename.split('.')[0]), caller__package__)
for filename in filter(lambda s: not s.startswith('_'), os.listdir(module_dir))
if filename.endswith('.py')
or (os.path.isdir(os.path.join(module_dir, filename))
and os.path.exists(os.path.join(module_dir, filename, "__init__.py")))
]
caller.frame.f_locals['__all__'] = [get_module_name(m) for m in modules]
caller.frame.f_locals.update({get_module_name(m): m
for m in modules})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment