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
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.