5

Python 3.3 introduced the __qualname__ attribute for function objects and class objects.

It's easy to get the (unqualified) name and a code object for the currently executing function.

But how to get the qualified name for the currently executing function?

4
  • Inspection. I can get frame objects and code objects. But I can't get a function object which would yield __qualname__. Commented Aug 30, 2012 at 19:47
  • When you say (unqualified) name do you mean __name__? Commented Aug 30, 2012 at 21:38
  • for e.g. the frame object the unqualified name is inspect.stack()[0][0].f_code.co_name. Commented Aug 31, 2012 at 6:20
  • For e.g. function f2 nested in function f1, being a method of class c2 nested in class c1 the qualified name would be: c1.c2.f1.<locals>.f2. For me even better would be: c1.c2.f1.f2. Commented Aug 31, 2012 at 6:28

3 Answers 3

2

You can use executing:

executing.Source.for_frame(frame).code_qualname(frame.f_code) 
Sign up to request clarification or add additional context in comments.

Comments

2

As of Python 3.11 this is now possible via:

inspect.currentframe().f_code.co_qualname 

(with optional .f_backs inserted before the .f_code as desired)

https://docs.python.org/3.11/reference/datamodel.html#codeobject.co_qualname

Comments

1

I don't think you can, currently; see this thread.

Issue 13672 requests adding co_qualname to code objects, and issue 12857 requests making the called function available through the frame object. Both have patches attached.

3 Comments

Thanks. Python inspection is a patchwork and more clumsy than useful IMHO. But perhaps the underlying architecture is the clumsy patchwork?
@carpetemporem Part of the problem is that inspection has to work on top of multiple implementations which differ quite severely: CPython, Jython, IronPython, PyPy and even Stackless.
Yep, legacy code. But IMHO Python 3 could have been a chance for a fundamental redesign of a language which was simple and not bad for a starter but becomes more and more of a mess. Chance lost.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.