[Python-ideas] Standard way to get caller name and easy call stack access

Robert Kern robert.kern at gmail.com
Tue Mar 27 17:14:43 CEST 2012


On 3/27/12 2:33 PM, Steven D'Aprano wrote:
> anatoly techtonik wrote:
> [...]
>> Well, I proposed to have a caller_name() method. If it is not too
>> universal, then a sys.call_stack() could be a better try:
>>
>> sys.call_stack() - Get current call stack. Return the list with a
>> list of qualified names starting with the oldest.
>>
>> Rationale: make logging calls and module based filters zero cost.
>
> I don't have an opinion on whether this is a good idea or a bad idea, but if
> people are going to make radical changes with respect to inspecting the call
> stack, I think it would be much better to get a list of the actual calling
> functions, not their names.
>
> Reasons:
>
> * If you have the function, you can do anything with it, including getting the
> name, the docstring, any annotations it may have, etc., but if all you have is
> the name, it isn't so easy, and may not actually be possible to unambiguously
> find the function object given only it's name.
>
> * Not all functions have meaningful names (think lambdas); or their name may be
> ambiguous (think functions produced by factory functions).

One problem with this is that some of the intermediate frames (at the very 
least, the root frame) won't be functions but rather executed code in the form 
of module-level code or exec'ed strings. Furthermore, in CPython at least, it is 
difficult to go from the code object (which is what you have available) to its 
owning function object (if there is one). You can get the (well, a) name from 
the code object, though.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-ideas mailing list