Python Type Hints - How to Specify a Class Rather Than an Instance Thereof2021-05-16
In a type hint, if we specify a type (class), then we mark the variable as containing an instance of that type.
To specify that a variable instead contains a type, we need to use
type[Cls] (or the old syntax
For example, take this code:
We need to add type hints for
How can we specify that its
animal_class argument should contain a subclass of
We could try using
The type of
animal_class looks the same as the return type though, even though we know the first is a class and the second an instance.
And indeed, Mypy flags some errors:
What we should use instead is
This means “
animal_class takes the class
Animal or any subclass”.
Running Mypy on this produces no errors.
type syntax was only added in Python 3.9, thanks to PEP 585.
Mypy 0.800+ supports this new syntax on older Python versions if you use
from __future__ import annotations.
The previous syntax is
If your code uses
typing.Type and you add
__future__.annotations or upgrade to Python 3.9+, you can update your old syntax with
Dogs clearly beat cats,
Want better tests? Check out my book Speed Up Your Django Tests which teaches you to write faster, more accurate tests.
One summary email a week, no spam, I pinky promise.
- Python Type Hints - Duck typing with Protocol
- Python Type Hints - How to Fix Circular Imports
- Python Type Hints - Use object instead of Any
Tags: mypy, python
© 2021 All rights reserved.