Skip to content

Instantly share code, notes, and snippets.

@lstrgiang
Created November 11, 2018 02:53
Show Gist options
  • Save lstrgiang/5eec399a37983d5e8596cd8be6ca7675 to your computer and use it in GitHub Desktop.
Save lstrgiang/5eec399a37983d5e8596cd8be6ca7675 to your computer and use it in GitHub Desktop.
Automatically import all all classes or defined attribute within a module
## IMPORTING PROBLEM:
## - When you want to import a class or any object, attribute from a submodule, you need to specify
## the filename within the module path
## Example: you want to import class UserAuthentication declared in the file user_authentication.py
## within the module app.controllers.auth, then:
## > import UserAuthentication from app.controllers.auth.user_authentication
## INSTEAD, WHY NOT: > import UserAuthentication from app.controllers.auth
## Here is the solution:
import pkgutil
import sys
__all__ = []
for loader, name, is_pkg in pkgutil.walk_packages(__path__):
if name.startswith('__'):
continue
## 1. replace 'app.controllers.{name}' by your module path
## 2. replace 'api' by your class or attribute you need to import
## > tips: for attribute you need to import, you can create a function to
## > convert the file name from snake case into camel case, which is the importing classname
module_ = __import__(f'app.controllers.{name}', fromlist=['api'])
## The following step store imported attribute into an array, which can be used dynamically
__all__.append(getattr(module_, 'api'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment