Catch “before/after function call” events for all functions in class

非 Y 不嫁゛ 提交于 2019-12-03 19:17:19

问题


Is there any possibility to catch "before/after function call" events for all functions in class, without decorating each of these functions? May be some class decorator? In other words, for such code, I would like to get following output:

class Foo:
    def func1():
        print('1')

    def func2():
        print('2')

c = Foo()
c.func1()
c.func2()

# Output I would like to get:
# func1 called
# 1
# func1 finished
# func2 called
# 2
# func2 finished

I need it not for tracing. In class working with asynchronous functions, I need to know if some function were called before other function were finished.


回答1:


Yes, you can write a class decorator; the following will allow you to decorate each of the functions in the class:

def decorate_all_functions(function_decorator):
    def decorator(cls):
        for name, obj in vars(cls).items():
            if callable(obj):
                try:
                    obj = obj.__func__  # unwrap Python 2 unbound method
                except AttributeError:
                    pass  # not needed in Python 3
                setattr(cls, name, function_decorator(obj))
        return cls
    return decorator

The above class decorator applies a given function decorator to all callables on a class.

Say you have a decorator that prints the name of the function being called before and after:

from functools import wraps

def print_on_call(func):
    @wraps(func)
    def wrapper(*args, **kw):
        print('{} called'.format(func.__name__))
        try:
            res = func(*args, **kw)
        finally:
            print('{} finished'.format(func.__name__))
        return res
    return wrapper

then the class decorator could be applied with:

@decorate_all_functions(print_on_call)
class Foo:
    def func1(self):
        print('1')

    def func2(self):
        print('2')

Demo:

>>> @decorate_all_functions(print_on_call)
... class Foo:
...     def func1(self):
...         print('1')
...     def func2(self):
...         print('2')
... 
>>> c = Foo()
>>> c.func1()
func1 called
1
func1 finished
>>> c.func2()
func2 called
2
func2 finished



回答2:


If you don't want to decorate all the classes that you want to have this functionality, you can try metaprogramming to alter the methods during creation to run a pre/post operation, the details are in the answer to this question How to run a method before/after all class function calls with arguments passed?



来源:https://stackoverflow.com/questions/25828864/catch-before-after-function-call-events-for-all-functions-in-class

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