Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
It is hard to use Union in runtime type checks
>>> type(Union[int, str])
typing.Union
>>> type(Union[int, str]) == Union
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/lucaswiman/.pyenv/versions/3.6/lib/python3.6/typing.py", line 760, in __eq__
return self._subs_tree() == other
File "/Users/lucaswiman/.pyenv/versions/3.6/lib/python3.6/typing.py", line 760, in __eq__
return self._subs_tree() == other
File "/Users/lucaswiman/.pyenv/versions/3.6/lib/python3.6/typing.py", line 760, in __eq__
return self._subs_tree() == other
[Previous line repeated 245 more times]
RecursionError: maximum recursion depth exceeded
>>> issubclass(Union[int, str], Union)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/lucaswiman/.pyenv/versions/3.6/lib/python3.6/typing.py", line 770, in __subclasscheck__
raise TypeError("Unions cannot be used with issubclass().")
TypeError: Unions cannot be used with issubclass().
>>> from typing import _FinalTypingBase
>>> _FinalTypingBase in Union.mro()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: '_Union' object has no attribute 'mro'
>>> type(Union[int, str]).mro()
[typing.Union, typing._FinalTypingBase, typing._TypingBase, <class 'object'>]
@lucaswiman

This comment has been minimized.

Copy link
Owner Author

commented Jun 25, 2017

To clarify, this code is indicating that even special casing typing.Union in a runtime typechecker decorator is somewhat difficult. Is there a simpler way than Union in type(cls).mro()?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.