Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What you've asked for can't be done (nicely -- there are ways of doing it but they are nasty hacks). BUT: you don't really want to do that. Think at a higher level: you want an easy way to modify a function to log that it has started. Changing the <em>source code</em> of the function isn't a good way do to that -- after all, the logging has nothing to do with what the function is doing! Instead, you want to modify the function <em>ex post facto</em>.</p> <pre><code>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( ) # starting theFunc # running theFunc </code></pre> <p>This is an example of a Python <em>decorator</em>: it transforms a function at define-time into another one. It's syntactic sugar for:</p> <pre><code>def theFunc( ): print( "running theFunc" ) theFunc = startLog( theFunc ) </code></pre> <p>In other words, you are taking the function object itself (remember -- functions are objects too, you can pass them around, modify them, look at their attributes, etc!) and redefining it. Looking at the source code, we see that <code>startLog</code> defines a new function (<code>loggedFunc</code>), which first prints a log trace and then runs the original function, passing through its arguments. Applying the decorator replaces <code>theFunc</code> with <code>loggedFunc</code>, so that the function bound to the name <code>theFunc</code> now logs itself!</p> <p>Does that make sense? I'm happy to explain it in more detail.</p> <h3>Edit</h3> <p>As has been pointed out, this doesn't specifically answer your question; if you need any more functionality than this then use the <code>logging</code> module which does everything you'll ever need and then some. Walking the stack is just icky, as well as fragile, though =p.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload