How to get the source code of python function being decorated?
Ned Batchelder
ned at nedbatchelder.com
Fri Sep 16 17:49:30 EDT 2016
On Friday, September 16, 2016 at 3:20:15 PM UTC-4, Peng Yu wrote:
> Hi, See the following example, I am not able to get the source code of
> the actual function that does the calculation of partial_ratio. Does
> anybody know what is the correct way of getting the source?
>
> /tmp$ ./main.py
> @functools.wraps(func)
> def decorator(*args, **kwargs):
> if args[0] is None or args[1] is None:
> return 0
> return func(*args, **kwargs)
>
> /tmp$ cat ./main.py
> #!/usr/bin/env python
> # vim: set noexpandtab tabstop=2 shiftwidth=2 softtabstop=-1 fileencoding=utf-8:
>
> import fuzzywuzzy.fuzz
> import inspect
> print inspect.getsource(fuzzywuzzy.fuzz.partial_ratio)
>
In general, you can't get at the decorated function. Decorators can
do anything they want with the function they decorate, including
completely ignore it, or store it in a closure, assign it to a global,
add it to a data structure, etc.
Can you tell us more about the problem you are trying to solve? Why
do you want a program that access the source of decorated functions?
Maybe there's another way to get at what you need.
--Ned.
More information about the Python-list
mailing list