Python: literally "printing" a function
Question: For reasons I won't get into, I need some way to literally print a function.

I know when you run print on a function object you get some complicated
<010101045 function> output. So to my understanding perhaps the only way to do
this is run some kind of python notepad module. Then I could devise an
algorithm to write a line of text to match each function line so as to get a
printed function.

If anyone knows some other way to achieve this, please do tell because I am
sure doing it this way is incredibly complicated. If however this is the only
way, if someone could walk me through the basic steps to doing so that would
also be greatly appreciated.

It occurred to me also that it would be interesting to be able to have the
syntax of the printed function be saved in python format so that I could
literally just import it directly into a program if I wanted. Yes, I realize
this is getting really complicated, but again, a general walk through would be
really cool if anyone knows how to do this.

If anyone has gotten as far as automating the aforementioned process to the
point where a program could modify an imported module from inside of the
program importing it, now that would really cool.

(In an ideal case of course the modified version would be saved under a
different name and be imported as well as the previous version and handled at
that point within the program doing the importing)

I guess at this point I'm just curious about the basic commands for importing,
saving, and modifying of files from within a python program.

All insight is appreciated,

Thanks,

PS: if you are wondering why I want to do all of this, it should be obvious,
if not it would take a while to explain.


Answer: Use
[`inspect.getsource`](http://docs.python.org/2/library/inspect.html?highlight=inspect#inspect.getsource):

    
    
    def a():
        pass
    
    import inspect
    print inspect.getsource(a)
    

Of course, this only works if you have access to the original source.

If you don't have the original source, the most you could get is the byte code
(see `dis.dis`).

EDIT: The Python interactive shell is one example where `inspect` does not
have access to the source.

