Skip to content Skip to sidebar Skip to footer

Viewing The Code Of A Python Function

Let's say I'm working in the Python shell and I'm given a function f. How can I access the string containing its source code? (From the shell, not by manually opening the code file

Solution 1:

inspect.getsource It looks getsource can't get lambda's source code.

Solution 2:

Not necessarily what you're looking for, but in ipython you can do:

>>>function_name??

and you will get the code source of the function (only if it's in a file). So this won't work for lambda. But it's definitely useful!

Solution 3:

maybe this can help (can get also lambda but it's very simple),

import linecache

def get_source(f):

    source = []
    first_line_num = f.func_code.co_firstlineno
    source_file = f.func_code.co_filename
    source.append(linecache.getline(source_file, first_line_num))

    source.append(linecache.getline(source_file, first_line_num + 1))
    i = 2

    # Here i just look until i don't find any indentation (simple processing).  whilesource[-1].startswith(' '):
        source.append(linecache.getline(source_file, first_line_num + i))
        i += 1

    return"\n".join(source[:-1])

Solution 4:

A function object contains only compiled bytecode, the source text is not kept. The only way to retrieve source code is to read the script file it came from.

There's nothing special about lambdas though: they still have a f.func_code.co_firstline and co_filename property which you can use to retrieve the source file, as long as the lambda was defined in a file and not interactive input.

Post a Comment for "Viewing The Code Of A Python Function"