How to get the source code of python function being decorated?

Peter Otten __peter__ at web.de
Fri Sep 16 18:12:09 EDT 2016


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 Python 3 functools.wraps() records the wrapped function as __wrapped__:

$ cat tmp.py
import functools

def spam(func):
    @functools.wraps(func)
    def decorator(*args, **kwargs):
        return func(*args, **kwargs)
    return decorator

@spam
def ham(foo, bar):
    return 42

$ python3
...
>>> import inspect
>>> import tmp              
>>> print(inspect.getsource(tmp.ham))
    @functools.wraps(func)
    def decorator(*args, **kwargs):
        return func(*args, **kwargs)

>>> print(inspect.getsource(tmp.ham.__wrapped__))
@spam
def ham(foo, bar):
    return 42

In Python 2 when you look into the attributes of tmp.ham() using dir() 
you'll eventually find

>>> print inspect.getsource(tmp.ham.__closure__[0].cell_contents)
@spam
def ham(foo, bar):
    return 42

but I'm not sure this is general enough to spare you the look into the 
source code.




More information about the Python-list mailing list