[New-bugs-announce] [issue44524] __name__ attribute in typing module

Lars report at bugs.python.org
Mon Jun 28 10:15:33 EDT 2021


New submission from Lars <gemerden at gmail.com>:

I noticed some (perhaps intentional) oddities with the __name__ attribute:

 - typing classes like Any (subclass of _SpecialForm) do not have a __name__ attribute,
 - abstract base classes in typing, like MutableSet do not have a __name__ attribute,
 - 'ChainMap', 'Counter', 'OrderedDict' do not have a __name__ attribute when imported from typing, but do when imported from collections.

I have written a function to show presence/absence if the name __name__ attribute:

def split_module_names(module):
    unnamed, named = set(), set()
    for name in dir(module):
        if not name.startswith('_'):
            attr = getattr(module, name)
            try:
                if hasattr(attr, '__name__'):
                    named.add(name)
                else:
                    unnamed.add(name)
            except TypeError:
                pass
    return named, unnamed

import typing
import collections

typing_named, typing_unnamed = split_module_names(typing)
collec_named, collec_unnamed = split_module_names(collections)

print("typing_unnamed:", typing_unnamed)
print("collec_named & typing_unnamed:", collec_named & typing_unnamed)

Is this intentional? It seems a little inconsistent.

I also found something that sometimes the __name__ attribute does resolve:

class S(typing.Sized):
        def __len__(self):
            return 0

print("'Sized' in typing_unnamed:", 'Sized' in typing_unnamed)
print("[t.__name__ for t in S.__mro__]:", [t.__name__ for t in S.__mro__])  # here __name__ is resolved!
print("getattr(typing.Sized, '__name__', None):", getattr(typing.Sized, '__name__', None))

printing:

'Sized' in typing_unnamed: True
[t.__name__ for t in S.__mro__]: ['S', 'Sized', 'Generic', 'object']
getattr(typing.Sized, '__name__', None): None

----------
messages: 396638
nosy: farcat
priority: normal
severity: normal
status: open
title: __name__ attribute in typing module
type: behavior
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44524>
_______________________________________


More information about the New-bugs-announce mailing list