What you requested cannot be done (beautifully - there are ways to do this, but they are nasty hacks). BUT: you really don't want to do this. Think at a higher level: you need an easy way to change the function for registration with which it started. Changing the source code of a function is not a good way to do this - after all, a log has nothing to do with what the function does! Instead, you want to change the ex post facto function.
def startLog( func ): def loggedFunc( *args, **kwargs ): print( "starting {0} with {1}".format( func.__name__, args[ 0 ] ) ) return func( *args, **kwargs ) return loggedFunc @startLog def theFunc( ): print( "running theFunc" ) theFunc( )
This is an example of a Python decorator: it converts a function in time-time to another. This is syntactic sugar for:
def theFunc( ): print( "running theFunc" ) theFunc = startLog( theFunc )
In other words, you take the function object yourself (remember - functions are also objects, you can transfer them, change them, view their attributes, etc.!) And redefine it. After looking at the source code, we see that startLog defines a new function ( loggedFunc ), which first prints the trace of the log, and then runs the original function, passing through its arguments. Using the decorator replaces theFunc with loggedFunc , so the function associated with theFunc is now written itself!
It makes sense? I am pleased to explain this in more detail.
Edit
As already noted, this does not specifically answer your question; if you need more functionality than in this case, use the logging module, which will do everything you ever need, and then some. Walking on the glass is simply not good, but also fragile, although = p.