Differences between __name__ and __qualname__

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

def fn(): 
    pass


class C(object):
    pass


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

What is the difference between __name__ and __qualname__ ?

    
asked by anonymous 28.10.2018 / 02:39

1 answer

3

It's exactly the same thing in basic usage. In the cited example it does not change. But when you have classes or functions nested there changes. Using a more complex example, see that only the higher-level class or function that is in the global namespace produces the same result, the others change and only __qualname__ produces a full pathname, called < in> fully qualified name . __name__ only gives the basic name without a "last name", which can be ambiguous when the element of the code 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__)

See running on ideone . And no Coding Ground . Also I put GitHub for future reference .

    
28.10.2018 / 12:02