Created
August 30, 2017 22:05
-
-
Save kageurufu/4a39f1821b9ec5e8e02fa3d9982b97d4 to your computer and use it in GitHub Desktop.
Auto-import all files in a module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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