views:

628

answers:

4

Suppose, I have simple python function named foo as shown below,

def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a

I get name of the function using

>> foo.func_name

how can I get

>> foo.somemethod ?

#do something with args
a = arg1 + arg2
return a

What is best way to do this? Thanks in advance.

+4  A: 

The inspect module has methods for retreiving source code from python objects. Seemingly it only works if the source is located in a file though. If you had that I guess you wouldn't need to get the source from the object.

runeh
Yes, it seems to work only for objects defined in a file. Not for those defined in interpreter.
jetxee
A: 

I believe that variable names aren't stored in pyc/pyd/pyo files, so you can not retrieve the exact code lines if you don't have source files.

Abgan
+9  A: 

If the function is from a source file available on the filesystem, then inspect.getsourcelines(foo) might be of help.

I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.

Rafał Dowgird
+3  A: 

Thanks!!! Thank you very much .... You guys are amazing.... My BIG problem is solved.. here is the code

somefile.py

def funn(arg1,arg2):
    '''doc string'''
    #implementation details
    #etc...
if __name__=='__main__':
    import inspect
    L = inspect.getsourcelines(funn)
PLEASE mark runeh's correct answer as solution and edit your comments into your question.
furtelwart