meawoppl
meawoppl

Reputation: 2802

Reproduce effects of Python 3.3 __qualname__ in earlier Pythons

Python 3.3 added the __qualname__ attribute which allows people to get the qualified name of a function (think module.submodule.class.function) or similar.

Is there a way to reproduce this attribute in Python 2.6 and 2.7?

Upvotes: 2

Views: 2058

Answers (3)

wouter bolsterlee
wouter bolsterlee

Reputation: 4037

I've written a library that provides a __qualname__ equivalent for older Python versions: https://github.com/wbolster/qualname

Upvotes: 6

wouter bolsterlee
wouter bolsterlee

Reputation: 4037

I've cooked up a hack that gets the qualified name for a (nested) class by using the inspect (for the class) and AST (for the source file) modules, and combining the results based on the line numbers. You can find it here:

https://gist.github.com/wbolster/d8ff5fe5ddca13391225

Upvotes: 1

greschd
greschd

Reputation: 636

Judging by the arguments given in the PEP where __qualname__ was proposed (here), this seems to be impossible. There's im_class, which gives you the defining class of a module, but that's it.

Of course it's possible to just go through all the things from globals() until you find something that matches your __name__, but that can become arbitrarily complex, and is just plain horrible. If you indeed decide to do that, please also check if the two have the same identity (a is b), because any two things can have the same __name__.

Upvotes: 2

Related Questions