With the python module inspect, one can inspect (no kidding) the run-time python stack. Among other things, this makes it possible to get the name of the current function or callers. Handy for logging or debugging purposes. A simple script to illustrate:
import inspect # functions def whoami(): return inspect.stack()[1][3] def whosdaddy(): return inspect.stack()[2][3] def foo(): print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy()) bar() def bar(): print "hello, I'm %s, daddy is %s" % (whoami(), whosdaddy()) johny = bar # call them! foo() bar() johny()
output:
hello, I'm foo, daddy is ? hello, I'm bar, daddy is foo hello, I'm bar, daddy is ? hello, I'm bar, daddy is ?
How does it work?
inspect.stack()returns a list with frame records.- In function
whoami():inspect.stack()[1]is the frame record of the function that callswhoami, likefoo()andbar(). - The fourth element of the frame record (
inspect.stack()[1][3]) is the function name.
The rest should be obvious (check the python docs on inspect for more information), except that johny() thinks he's function bar(). That's because johny actually just points to the code of bar() and the function name bar is associated with the code and not with the variables.
Inspiration:
Index for function name
I could be doing something completely wrong, but inspect.stack()[1][3] doesn't get me the function name, it has the value of ''.
(This is with Python 2.5) To get the name of the function, I used inspect.stack()[0][3].
If you use inspect.stack()
If you use
inspect.stack()inside the function you want to investigate, you should indeed use index 0. In my example I used a functionwhoami(), which adds another function call layer, and I have to look at index 1.Thanks so much!!!
Dude, this totally injected awesome into my debugging. To say thanks here is this:
To call it you just import debug into any script then in your classes or functions run debug(). If you add something to the call, it will print out the the object you add. You can even add objects in parenthesis. Using log=False you can focus in on what you need debugged. This should help remove the puzzle box that can occur when you don't know where objects are changing.
You have to format it yourself.
There goes Stefaan... still
There goes Stefaan... still helpin' a brother out over a year and a half later.
Thanks, man.
Very cool
Nice tutorial man :) Thanks for your contribution to the community!
That's exactly what I was
That's exactly what I was looking for. Thank you :)
Post new comment