Variable names can be specified dynamically, files can be read dynamically to incorporate functions and classes, and so on.
ham1.py
import sys
#Own module
myself = sys.modules[__name__]
#Addition of member ham (equivalent to declaration of ham variable)
myself.__dict__['ham'] = 'Ham'
#Output ham
print(ham)
#>>> Ham
ham2.py
import sys
import glob
import os.path
import importlib
#Import the directory (namespace package) that contains the dynamically loaded module in advance.
import dynamic_hams
#Get your own module
myself = sys.modules[__name__]
seq = 0
for mods_dir in dynamic_hams.__path__:
# dynamic_Get the list of py files in hams (pyc is omitted this time)
mod_paths = glob.glob(os.path.join(mods_dir, '*.py'))
for mod_path in mod_paths:
#File name without extension
mod_name = os.path.basename(mod_path).split('.')[0]
#Import module
# 'import dynamic_hams.ham'Equivalent to
mod = importlib.import_module('dynamic_hams.' + mod_name)
#Assign module members to themselves
myself.__dict__['incubate'+str(seq)] = mod.incubate
seq += 1
#Since the incubate function is assigned to itself, it can be called from other modules.
incubate0()
incubate1()
...
Python: How to get current module object - python.todaysummary.com 31.5. importlib – The implementation of import — Python 3.4.2 documentation
Recommended Posts