Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gauravvjn/3e652e2bdd4012de37fd864e6fa0857a to your computer and use it in GitHub Desktop.
Save gauravvjn/3e652e2bdd4012de37fd864e6fa0857a to your computer and use it in GitHub Desktop.
def import_all_items_from_all_modules_in_a_package():
"""
Put and call this function in the __init__.py file of the package.
This function dynamically loads all non-private classes, functions & variables from all modules
with in the current package. this is equivalent to below
```
from .abc import *
from .xyz import *
.
.
.
```
"""
path = pathlib.Path(__file__).parent.absolute()
names = [x.name[:-3] for x in path.iterdir() if x.is_file() and not x.name.endswith('__init__.py')]
for name in names:
mod = importlib.import_module(f".{name}", __name__)
for item in dir(mod):
if item.startswith('_') and item.endswith('_'):
continue
setattr(sys.modules[__name__], item, getattr(mod, item))
import_all_items_from_all_modules_in_a_package()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment