2

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?

Duncan
  • 92,073
  • 11
  • 122
  • 156
meawoppl
  • 2,714
  • 1
  • 23
  • 30
  • You could get it for objects nested inside classes by exhaustively searching the tree of attributes, starting with objects in the global namespace. I don't believe there would be a way to duplicate the `` indicator for functions defined inside other functions. – BrenBarn Oct 24 '14 at 08:25
  • I am not quite clear on what you are suggesting, spider up globals() until you find locals() and your own identifier? – meawoppl Oct 24 '14 at 08:34
  • You can't get `locals()` without actually calling a function. But you can spider through the `__dict__` of every object in `globals()`, then the `__dict__` of all those objects, etc. – BrenBarn Oct 24 '14 at 17:32

3 Answers3

7

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

wouter bolsterlee
  • 3,879
  • 22
  • 30
2

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__.

greschd
  • 606
  • 8
  • 19
1

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

wouter bolsterlee
  • 3,879
  • 22
  • 30