Get the module itself and add members dynamically

Use

Variable names can be specified dynamically, files can be read dynamically to incorporate functions and classes, and so on.

Code example

Dynamic variable declaration

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

Dynamically declare a function from a list of files

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()
...

reference

Python: How to get current module object - python.todaysummary.com 31.5. importlib – The implementation of import — Python 3.4.2 documentation

Recommended Posts

Get the module itself and add members dynamically
Dynamically load the module.
Add lines and text on the image
Get the address from latitude and longitude
Get the title of yahoo news and analyze sentiment
How to get the variable name itself in python
[python] Get the list of classes defined in the module
Get comments and subscribers with the YouTube Data API
Django-Overview the tutorial app on Qiita and add features (1)
[Django 2.2] Sort and get the value of the relation destination