Modify function in decorator

后端 未结 2 1239
春和景丽
春和景丽 2021-02-19 13:07

I was thinking about making a decorator for the purpose of increasing performance. A decorator that modifies the source code of the function it decorates, and returns the modifi

2条回答
  •  不要未来只要你来
    2021-02-19 13:22

    This works:

    import inspect, itertools
    
    def decorate(f):
        source = itertools.dropwhile(lambda line: line.startswith('@'), inspect.getsource(f).splitlines())
        exec('\n'.join(source))
        return eval(f.__name__)
    
    @decorate
    def test():
        return 1
    

    I think the problem is the inclusion of the decorator in the function source.

    # foo.py
    import inspect
    
    def decorate(f):
        print inspect.getsource(f)
    
    @decorate
    def test():
        return 1
    

     

    >>> import foo
    @decorate
    def test():
        return 1
    >>> # Notice the decorator is included in the source.
    

    exec sees @decorate for a test defined in a string, so it calls decorate recursively, but this time inspect.getsource fails, because it can't find the source of a function defined in a string.

提交回复
热议问题