Dynamic Function and Method Invocation in Python

# module.py

class A:

    def foo(self):
        print('this is foo.')

    @staticmethod
    def static_method():
        print('this is static.')


def bar():
    print('bar……')


def baz():
    print('==baz==')


This approach is an extension of the import() method. The Python documentation recommends using import_module() for programmatic module imports instead of import(). We will continue to use the module.py module defined above. ```

main.py

import importlib

module_name = 'module'

module_obj = importlib.import_module(module_name) class_of_module_obj = module_obj.A() class_of_module_obj.foo() class_of_module_obj.static_method() module_obj.bar()


Documentation: importlib — import implementation — Python 3.9.0 documentation The importlib package has two purposes. The first is to provide an implementation of the import statement in Python source code (and therefore extend the **import**() function). This provides a portable import implementation that works on any Python interpreter. Compared to implementations in other programming languages, this one is easier to understand. The second purpose is to expose parts of the import mechanism in this package, making it easier for users to create their own custom objects (often called importers) that can participate in the import process. Use Cases
---------

When working with redis, sometimes you need to add a proxy class, as shown below: ```
class RedisClient:
    def init_con(self, *args, **kwargs):
        # do init things
        # like connect redis
        pass


Then, you want to directly execute redis-related operations through this RedisClient, such as set, get, hget, etc. ``` rc = RedisClient() rc.set(...) rc.get(...) ...


If you call it this way, you would have to write all functions from pyredis again in RedisClient, which is not efficient. What we actually want is dynamic invocation, mapping the operations in RedisClient directly to the actual pyredis operations based on the operation name. So, in RedisClient: ```
class RedisClient:
    

    def __getattr__(self, func_name):
        def func(*args, **kwargs):
            # this getattr is equivalent to redis_con.<func_name>
            return getattr(self.redis_conn, func_name)(*args, **kwargs)

if __name__ == '__main__':
    redis_client = RedisClient()
    redis_client.init_con(...)
    redis_client.set('key_name', 'key_value')

</func_name>

This achieves the goal of dynamically calling pyredis operasions. Reference: https://masantu.com/blog/2020-10-15/python-call-method-dynamically/

Tags: python importlib dynamic-method-calling Redis Python-classes

Posted on Thu, 15 Oct 2026 16:33:07 +0000 by whistler