I'd like to retrieve qualified name like function or class property __qualname__
for the current function. inspect.stack()
provides only simple unqualified name.
So I'm looking for a trick to calculate qualified name from available introspection info. I recoursed to trial-and-error in absence of python's internal representation knowledge and still could not figure the method. Python naturally calculates qualified names, so all required information are already available but I don't know where to find it.
I searched on the stackoverflow site and had found few solutions each incurring a drawback.
Check frame's locals
The method was proposed by @Aran-Fey in #42322828. Just scan stack locals for the first occurred __qualname__
def retrieveQualifiedName():
f = inspect.currentframe()
while f:
if '__qualname__' in f.f_locals:
return f.f_locals['__qualname__']
f = f.f_back
return None
It works good for classes nested in other classes directly but fails when there is a function in between.
good for
class A:
class B: pass
bad for
class A:
def a(self):
class B: pass
return B()
Offload all work to the 'executing' library
@Alex Hall suggested in #12190238 to use third-party introspection library executing
import executing
def retrieveQualifiedName():
f = inspect.currentframe().f_back.f_back
return executing.Source.executing(f).code_qualname()
The library calculates qualified name pretty reliably, but two things make me search for another solution.
First using third-party dependency complicates support. I could not just write a simple python script, I need to use full project definition and build artefacts. I would like to avoid it if possible.
Second the executing library parses source code to infer qualified name causing excess processing. I would like to extract qualified name from information already available to the interpreter.