[issue34568] Types in `typing` not anymore instances of `type` or subclasses of "real" types

Pekka Klärck report at bugs.python.org
Wed Sep 5 10:58:12 EDT 2018


Pekka Klärck <pekka.klarck at gmail.com> added the comment:

While studying the types in the typing module more, I noticed they have a special `__origin__` attribute which seems to contain the "real" type they represent. I was able to make my type conversion code to work by adding these lines:

    if hasattr(type_, '__origin__'):
        type_ = type_.__origin__

All our tests pass with this simple fix, but I'm slightly worried using it because `__origin__` doesn't seem to be documented. This means I'm not sure is my usage OK and, more importantly, makes me worried that another change in typing changes the behavior or removes the attribute altogether. Hopefully someone with more insight on this can comment my worries. Perhaps the attribute should also be documented as discussed earlier: https://github.com/python/typing/issues/335

I'd also be a little bit happier with the above fix if I could write it like

    if isinstance(type_, typing.SomeBaseType):
        type_ = type_.__origin__

but apparently types in the typing module don't have any public base class. I guess odds that some unrelated class would have `__origin__` defined is small enough that using `hasattr(type_, '__origin__')` is safe.

----------

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


More information about the Python-bugs-list mailing list