Dynamic import in Python (Reflection in Python)

In order to use functions from other files in Python, you need to import. However, like Java's reflection, Python allows you to call functions dynamically without using import keyword.

import

__import__ is a builtin function in Python. (It can be used without importing.)

You can read a specific module by passing only the module name (file name) as a parameter. It seems like Java's reflection.

mod_name = "bbb"
mod = __import__('%s' %(mod_name), fromlist=[mod_name])
print(mod)

we got the 'bbb' module.

<module 'bbb' from '/home/js/testcode/python/bbb.py'>

inspect & getattr

You can use inspect by declaring it with import inspect. inspect tells you what class or function the object has.

getattr () can create class or function objects with information from inspect.

The example below will show you how to use these functions.

If you create two files(aaa.py, bbb.py) below and run python aaa.py, you will get something like the log below. (the example is written in Python 3.5.)

aaa.py

import inspect
from bbb import BBB

# get module from module name
mod_name = "bbb"
mod = __import__('%s' %(mod_name), fromlist=[mod_name])

# get classes from module
class_list =  inspect.getmembers(mod, inspect.isclass)
for key, data in class_list:
    print('{} : {!r}'.format(key, data))


# get functions from a class
if class_list:
    cls_name = class_list[0][0]
    cls = getattr(mod, cls_name)
    func_list = inspect.getmembers(cls, inspect.isfunction)
    for key, data in func_list:
        print('{} : {!r}'.format(key, data))
        func_name = key
        func = getattr(cls, func_name)
        func()

bbb.py

class BBB:
    def setup():
        print("setup!")

    def teardown():
        print("teardown!")

    def testModule1():
        print("testModule1!")

    def testModule2():
        print("testModule2!")

    def testModule3():
        print("testModule3!")

We got the BBB class and it's functions. and we called it's functions.

log

BBB : <class 'bbb.BBB'>
setup : <function BBB.setup at 0x7f111ea54268>
setup!
teardown : <function BBB.teardown at 0x7f111ea542f0>
teardown!
testModule1 : <function BBB.testModule1 at 0x7f111ea54378>
testModule1!
testModule2 : <function BBB.testModule2 at 0x7f111ea54400>
testModule2!
testModule3 : <function BBB.testModule3 at 0x7f111ea54488>
testModule3!
codechachaCopyright ©2019 codechacha