Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you obtain the body of a function?

Tags:

python

I would need to separate the signature from the body of a function in Python, i.e. :

def mult(a, b):
    "Multiplication"
    if a or b is None:
       # border case
       return None
    else:
       return a * b

(the function is there for demonstration only).

I know that inspect.getsourcelines(mult) will get me the full code, but I would like to have only the body, i.e. less the signature and the docstring:

if a or b is None:
   # border case
   return None
else:
   return a * b

Is there an elegant way to obtain that, ideally using Python3 built-in parsing tools, rather than string manipulation?

like image 264
fralau Avatar asked Nov 17 '25 23:11

fralau


1 Answers

As I don't know any function that does this, here is a homemade function that should work. I don't have time for more in-depth use-cases. So i'll leave my incomplete answer here.

def get_body(func):
    """ Using the magic method __doc__, we KNOW the size of the docstring.
        We then, just substract this from the total length of the function
    """
    try:
        lines_to_skip = len(func.__doc__.split('\n'))
    except AttributeError:
        lines_to_skip = 0

    lines = getsourcelines(func)[0]

    return ''.join( lines[lines_to_skip+1:] )

def ex_0(a, b):
    """ Please !
        Don't

    Show
This
    """
    if a or b is None:
       # border case
       return None
    else:
       return a * b

def ex_1(a, b):
    ''' Please !Don'tShowThis'''
    if a or b is None:
       # border case
       return None
    else:
       return a * b

def ex_2(a, b):
    if a or b is None:
       # border case
       return None
    else:
       return a * b

def ex_3(bullshit, hello):
    pass

get_body(ex_0)
    # if a or b is None:
    #    # border case
    #    return None
    # else:
    #    return a * b

get_body(ex_1)
    # if a or b is None:
    #    # border case
    #    return None
    # else:
    #    return a * b

get_body(ex_2)
    # if a or b is None:
    #    # border case
    #    return None
    # else:
    #    return a * b

get_body(ex_3)
    # pass
like image 113
IMCoins Avatar answered Nov 20 '25 13:11

IMCoins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!