Optional[Type[Foo]] raises TypeError in Python 3.5.2
This is a bug in Python 3.5.2.
Optional[cls]
is a wrapper for Union[cls, type(None)]
, which uses __subclasses__()
to establish whether one class is a subclass of another.
However, Type
is a subclass of type
in Python 3.5.2, which means that
Union[Type[anything], anything_else]
will eventually call
type.__subclasses__()
… which is a problem, because type
is a metaclass, and so expects to be called with the class whose subclasses are being sought, in exactly the same way that calling an instance method on a regular class requires you to supply an instance of itself, e.g. str.upper('foo')
.
The problem is fixed in Python 3.5.3 (and, as you've noticed, 3.6) by making Type
no longer a subclass of type
.