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

Sven Marnach sven at marnach.net
Thu Mar 22 01:17:25 CET 2012

anatoly techtonik schrieb am Do, 22. Mär 2012, um 00:03:47 +0300:
> 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.

Using introspection in production code is not recommended in general,
with some exceptions, since the main purpose of introspection is
debugging.  *If* you want to do this at all, the recommended way is to
use the inspect module.  (And there is another way -- at least in
CPython you can use 'sys._getframe().f_back.f_code.co_name'.)

> 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

The missing link here seems to be that code objects don't allow access
to PEP 3155 qualified names -- if they did, this would be rather easy
to do.  How about adding a `co_qualname` attribute to code objects?
It could point to the same string the function object points to, so
the overhead would be minimal.

> So, I'd propose to include caller_name() function somewhere and name
> it somehow. 

I don't think this would be necessary if the qualified name could be
accessed from the frame object in some way.

> But there is more to that. Maybe too late for Python 3,
> but still an idea - make call stack a normal Python feature

Not sure what you are talking about here.


More information about the Python-ideas mailing list