How can I decorate all functions imported from a file?

泪湿孤枕 提交于 2019-11-29 11:31:01

A little bit of introspection (dir()) and dynamic look-up with getattr() and setattr().

First we iterate over all names found in module and check for objects that look like functions. After that we simply reassign old function with decorated one.

main.py:

import types
import functools

def decorate_all_in_module(module, decorator):
    for name in dir(module):
        obj = getattr(module, name)
        if isinstance(obj, types.FunctionType):
            setattr(module, name, decorator(obj))

def my_decorator(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        print(f)
        return f(*args, **kwargs)
    return wrapper

import mymod1
decorate_all_in_module(mymod1, decorator)

mymod1.py:

def f(x):
    print(x)


def g(x, y):
    print(x + y)

Output:

<function f at 0x101e309d8>
2
<function g at 0x101e30a60>
7

Process does not goes that smooth if you use star imports (from mymod import *). Reason is simple - because all names are in one huge bag and there no differentiation on where they come from, you need a lot of additional tricks to find what exactly you want to patch. But, well, that's why we use namespaces - because they are one honking great idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!