Python: Displaying an object's implementation source
Question: I've been tasked with something a bit unusual and unexpectedly puzzling -
Display the source code of a particular class's implementation of a method.

    
    
    In [1]: class Demonstration:
       ...:     def cost():
       ...:         return 42
       ...:     
    
    In [2]: class OtherDemo:
       ...:     def cost():
       ...:         return 43
       ...:  
    

In this example, I'd want to find the text `def cost():` and the following
lines at the appropriate indent for either given class.

modules like `inspect` or `dis` are nearly what I'm looking for, but I want to
display the python code, such as is displayed during a traceback; not
bytecode.

I'm also not opposed to parsing the source files, either - is there a library
that text editors might use for autocompletion or indent calculations that
could find a specific method in a class?


Answer: It sounds like the `inspect` library is exactly what you need, in particular,
the function
[`getsourcelines`](https://docs.python.org/2/library/inspect.html#inspect.getsourcelines):

    
    
    In [1]: def foo(x):
       ...:     x += 3
       ...:     x += 4
       ...:     return x
       ...: 
    
    In [2]: import inspect
    
    In [3]: inspect.getsourcelines(foo)
    Out[3]: (['def foo(x):\n', '    x += 3\n', '    x += 4\n', '    return x\n'], 1)
    
    In [4]: source_code = _
    
    In [6]: print(''.join(source_code[0]))
    def foo(x):
        x += 3
        x += 4
        return x
    

From the docs:

> Return a list of source lines and starting line number for an object. The
> argument may be a module, class, method, function, traceback, frame, or code
> object. The source code is returned as a list of the lines corresponding to
> the object and the line number indicates where in the original source file
> the first line of code was found. An IOError is raised if the source code
> cannot be retrieved.

