2021年6月10日 星期四

[ 常見問題 ] List submodules and import them

 Source from here1 and here2

Question
How to import submodules of a given module and import them dynamically? Said I have a package A with modules as below:
  1. [23:54:22 tmp]$ tree A/  
  2. A/  
  3. ├── submodule1.py  
  4. └── submodule2.py  
Let's say I have imported A as below and how to list submodule1 and submodule2 and then imported them?
  1. import A  
  2.   
  3. # TBD  
  4. # List all submodules under package A and import them  
HowTo
We can leverage pkgutil & importlib. Check sample code below:
test.py
  1. import A  
  2. import importlib  
  3. import pkgutil  
  4.   
  5.   
  6. for sm_info in pkgutil.iter_modules(A.__path__):  
  7.     print(f"Found submodule: {sm_info}")  
  8.     submodule_name = f"A.{sm_info.name}"  
  9.     print(f"Importing {submodule_name}")  
  10.     modu = my_module = importlib.import_module(submodule_name)  
  11.     print(f"Done: {modu.name()}")  
Execution result:
$ ./test.py
Found submodule: ModuleInfo(module_finder=FileFinder('/tmp/A'), name='submodule1', ispkg=False)
Importing A.submodule1
Done: Hello submodule1
Found submodule: ModuleInfo(module_finder=FileFinder('/tmp/A'), name='submodule2', ispkg=False)
Importing A.submodule2
Done: Hi, submodule2


1 則留言:

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...