Question
How to import submodules of a given module and import them dynamically? Said I have a package A with modules as below:
Let's say I have imported A as below and how to list submodule1 and submodule2 and then imported them?
HowTo
We can leverage pkgutil & importlib. Check sample code below:
- test.py
Execution result:
How to import submodules of a given module and import them dynamically? Said I have a package A with modules as below:
- [23:54:22 tmp]$ tree A/
- A/
- ├── submodule1.py
- └── submodule2.py
- import A
- # TBD
- # List all submodules under package A and import them
We can leverage pkgutil & importlib. Check sample code below:
- test.py
- import A
- import importlib
- import pkgutil
- for sm_info in pkgutil.iter_modules(A.__path__):
- print(f"Found submodule: {sm_info}")
- submodule_name = f"A.{sm_info.name}"
- print(f"Importing {submodule_name}")
- modu = my_module = importlib.import_module(submodule_name)
- print(f"Done: {modu.name()}")
Python alive progress bar
回覆刪除Python split string by comma
Fizzbuzz program in Python
Reverse pyramid pattern in Python
Python ordereddict
How to find average of n numbers in Python
Python calculate total marks percentage and grade of a student
Swapping of two numbers in Python