Skip to content
Advertisement

Optional[Type[Foo]] raises TypeError in Python 3.5.2

This code:

JavaScript

will raise TypeError on 3.5.2:

JavaScript

whereas it runs fine on 3.6. Same problem if I spell out Optional as Union[None, Type[Foo]].

Is there any workaround for 3.5.2, while still accurately annotating the return type?

Advertisement

Answer

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

JavaScript

will eventually call

JavaScript

… 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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement