Python Type Hints - Use object instead of Any2021-05-07
When starting out with Python type hints, it’s common to overuse
This is dangerous, since
Any entirely disables type checking for a variable, allowing any operation.
If you’re using
Any to mean “this object could be any type, and I don’t care what”, you probably want to use
Every object in Python inherits from
object, which makes it an “opaque” type that only allows operations common to everything.
Therefore we could pass, print, or store such variables in a container, but we couldn’t do anything more specific.
Take these few lines of code:
We assign an
x, which we marked explicitly as having type
The next line has an operation that will fail, since
ints do not have a
But, due to the
Any type, mypy does not detect the failure:
If we didn’t care what type
x contained, we would be better off typing it as
Mypy can then correctly detect the bug:
Another example where
Any can be overused is when passing through
Since we are only passing on
kwargs, the use of
Any doesn’t really have an effect.
But if the code ever evolves to look inside
kwargs, for example to log them, then such operations will not be type checked.
We should instead use
object to declare that we don’t know or care about the types of the values in
object is also less work since we don’t have to import it!
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 - *args and **kwargs
- Python Type Hints - How to Use TypedDict
- Python Type Hints - How to Fix Circular Imports
Tags: mypy, python
© 2021 All rights reserved.