Skip to content

Instantly share code, notes, and snippets.

@lucaswiman
Last active June 25, 2017 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucaswiman/21373bea33ccd2c5e868ec52b6eff412 to your computer and use it in GitHub Desktop.
Save lucaswiman/21373bea33ccd2c5e868ec52b6eff412 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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