Differences between __name__ and __qualname__

Asked

Viewed 170 times

3

In Python functions/methods and classes have two attributes that in their most "basic" use seem to do exactly the same thing, are they: __name__ and __qualname__, see:

def fn(): 
    pass


class C(object):
    pass


>>> fn.__name__
"fn"
>>> fn.__qualname__
"fn"
>>> C.__name__
"C"
>>> C.__qualname__
"C"

What’s the difference between __name__ and __qualname__?

  • Useful: https://www.python.org/dev/peps/pep-3155/

1 answer

3


It is exactly the same in the basic use. In the example quoted it does not change. But when you have nested classes or functions it changes. Using a more complex example see that only the higher level class or function is in namespace global produces the same result, others change and only __qualname__ produces a full path of the name, the call Fully Qualified name. __name__ only gives the basic name without "surname", which can be ambiguous when the code element is nested.

class C:
   def f(): pass
   class D:
     def g(): pass
 
print(C.__qualname__)
print(C.f.__qualname__)
print(C.D.__qualname__)
print(C.D.g.__qualname__)
 
def f():
   def g(): pass
   return g
 
print(f.__qualname__)
print(f().__qualname__)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thank you for the reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.