繁体   English   中英

使用装饰器修补模块中的所有功能

[英]Patch all functions in module with decorator

我有一个包含许多函数的python模块,我想为它们应用一个装饰器。 有没有办法通过猴子修补来修补所有这些,以便为每个函数应用这个装饰器,而无需在应用装饰器的行上进行复制粘贴?

换句话说,我想替换这个:

@logging_decorator(args)
func_1():
  pass

@logging_decorator(args)
func_2():
  pass

@logging_decorator(args)
func_3():
  pass


@logging_decorator(args)
func_n():
  pass

有了这个:

patch_func():
  # get all functions of this module
  # apply @logging_decorator to all (or not all) of them

func_1():
  pass

func_2():
  pass

func_3():
  pass

func_n():
  pass

我真的不确定这是个好主意。 毕竟, 明确比隐含更好

有了这样说,这样的东西应该工作,使用inspect来查找模块的哪些成员可以被装饰,并使用__dict__来操作模块的内容。

import inspect

def decorate_module(module, decorator):
    for name, member in inspect.getmembers(module):
        if inspect.getmodule(member) == module and callable(member):
            if member == decorate_module or member == decorator:
                continue
            module.__dict__[name] = decorator(member)

样品用法:

def simple_logger(f):
    def wrapper(*args, **kwargs):
        print("calling " + f.__name__)
        f(*args, **kwargs)
    return wrapper

def do_something():
    pass

decorate_module(sys.modules[__name__], simple_logger)
do_something()

我不会很漂亮......但你可以在定义后使用dir()列出所有函数。 然后我想不出一种在没有包装函数的情况下修补它们的方法。

def patched(func):
    @logging_decorator
    def newfunc(*args, **kwargs):
        return func(*args, **kwargs)
    return newfunc

funcs=[f in dir() if not '__' in f]
for f in funcs:
    exec(f+'=patched(f)')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM