views:

110

answers:

4

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.

+2  A: 

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

sunqiang
A: 

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.

bobince
The compiled bytecode of a function can be viewed with `dis.dis`.
adw
+1  A: 

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!

Etienne
A: 

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])
singularity