[issue44524] __name__ attribute in typing module

Lars report at bugs.python.org
Wed Jun 30 10:35:26 EDT 2021


Lars <gemerden at gmail.com> added the comment:

I have been doing some research, but note that I don't have much experience with the typing module. That said, there seem to be 2 main cases:

 - '_SpecialForm': with instances Any, Union, etc.
 - '_BaseGenericAlias'/'_SpecialGenericAlias': base classes collections classes.

I think '_SpecialForm' can be enhanced to have '__name__' by replacing the '_name' attribute with '__name__'. Maybe add '__qualname__' as well. I cannot say whether there are many more attributes that could be implemented to have the same meaning as in 'type'. The meaning of attributes like '__mro__' seem difficult to define.
Alternatively '__getattr__' could be added (but that might be too much):

def __getattr__(self, attr):
    return getattr(self._getitem, attr)

'_BaseGenericAlias''_SpecialGenericAlias' the '__getattr__' method could perhaps be adapted (or overridden in '_SpecialGenericAlias') as follows, from:

def __getattr__(self, attr):
    # We are careful for copy and pickle.
    # Also for simplicity we just don't relay all dunder names
    if '__origin__' in self.__dict__ and not _is_dunder(attr):
        return getattr(self.__origin__, attr)
    raise AttributeError(attr)

to:

def __getattr__(self, attr):
    if '__origin__' in self.__dict__:
        return getattr(self.__origin__, attr)
    raise AttributeError(attr)

or perhaps:

def __getattr__(self, attr):
    if '__origin__' in self.__dict__ and hasattr(type, attr):
        return getattr(self.__origin__, attr)
    raise AttributeError(attr)

to forward unresolved attribute names to the original class.

I have written some tools and tested some with the above solutions and this seems to solve the missing '__name__' issue and make the typing abc's much more in line with the collection abc's. However I did not do any unit/regression testing (pull the repo, etc.)

tools are attached.

----------
Added file: https://bugs.python.org/file50135/typing_attributes.py

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


More information about the Python-bugs-list mailing list