[Python-ideas] Standard way to get caller name and easy call stack access
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
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 
got 3k views over 1 year, so the recipe seems to be useful. I've
developed a similar snippet  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:
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:
line 183, in run
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:
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?
More information about the Python-ideas