14

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

I want this to work even for lambda functions defined inside other functions.

1

4 Answers 4

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yup, unfortunately getsource only works if it can open the file the source code exists in. One possible thing you can do to see what the lambda is doing is use dis to pull apart the bytecode.
8

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!

Comments

4

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).  
    while source[-1].startswith(' '):
        source.append(linecache.getline(source_file, first_line_num + i))
        i += 1

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

Comments

0

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.

1 Comment

The compiled bytecode of a function can be viewed with dis.dis.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.