[Python-ideas] Standard way to get caller name and easy call stack access
anatoly techtonik
techtonik at gmail.com
Wed Mar 21 22:03:47 CET 2012
Seems like the only way to get caller name in Python is to use inspect
module [1]
It seems that this way is not recommended (I wonder why?) and there is no other.
The stackoverflow question about how to get callers method namd [1]
got 3k views over 1 year, so the recipe seems to be useful. I've
developed a similar snippet [2] that also extracts a module and class
name in addition to method. To me this snippet is very handy to insert
in print statements to see who uses a certain function at run-time.
The output from this function is:
spyderlib.widgets.externalshell.introspection.NotificationThread.run
Which no function of `inspect` and `traceback` modules can provide
(correct me if I wrong, but I am pretty confident). The stuff they
propose will look like:
File "/mount/sdb5/projects/spyderlib/spyderlib/widgets/externalshell/introspection.py",
line 183, in run
write_packet(self.notify_socket, output)
As a 'software engineer' I am more interested to get logical structure
of call stack rather than physical location of code text pieces (which
is important too, but secondary). Neither `traceback` nor `inspect`
seems to be designed with this use case, and if you'll look closely -
the traceback above misses class info completely. To get the name of
the class from this traceback you need to know its location withing
the lines of the file.
So, I'd propose to include caller_name() function somewhere and name
it somehow. But there is more to that. Maybe too late for Python 3,
but still an idea - make call stack a normal Python feature (optional
for stackless, but still a feature) and describe a standard for call
stack names, to provide everybody a simple and safe way to see what's
going on with execution stack (and an easy way to get caller names).
Making it a feature means that there will be almost no overhead when
looking up the name (id) of the caller callers. This will also be
handy for logging.
I wish I could shorten this proposal. The picture in my head is something like:
__main__
spyderlib.widgets.externalshell.introspection.NotificationThread.run
spyderlib.utils.bsdsocket.write_packet
Every indented string is an unique id of function or other closure
that makes up Python code. Would it rock?
This will probably require describing all possible ways to run Python
code to see where a call to caller_name() can appear to cover all
possible situations. Is there already a list of these ways?
1. http://stackoverflow.com/questions/2654113/python-how-to-get-the-callers-method-name-in-the-called-method
2. https://gist.github.com/2151727
--
anatoly t.
More information about the Python-ideas
mailing list