Sub topic 7
Any, object, and gradual typing
This chapter assumes you can annotate parameters and returns, and that you have run mypy or pyright on a file. It covers what to do when a value's type is unclear.
Gradual typing
Python's type system is gradual. Code without annotations is not an error. A checker treats unannotated parameters as Any and skips most checks on them. You can add hints one function at a time, and the checker verifies only what you have described.
Any: opt out of checking
Any is a type that is compatible with every other type, in both directions. A checker lets you do anything with an Any value.
from typing import Any
def parse(raw: str) -> Any:
return raw.split(",")
result = parse("a,b")
print(result.upper()) # a checker accepts this, but it fails at runtimeThe checker raises no error on result.upper(). The call fails at runtime with an AttributeError, because result is a list. Any spreads: a value derived from an Any value is usually Any too, so one loose annotation can silence checks across many lines.
object: accept anything, promise nothing
object is the base class of every type, so any value is a valid object. The difference from Any is what you may do with it. A checker only allows operations that every object supports.
def describe(value: object) -> str:
if isinstance(value, int):
return f"int: {value + 1}"
if isinstance(value, str):
return f"str: {value.upper()}"
return "something else"
print(describe(41))
print(describe("hi"))
print(describe([1, 2]))Calling value.upper() before the isinstance check would be an error. You must narrow the type first, as covered in the previous chapter.
Choosing between them
| Type | Accepts any value | Allows any operation | Checker protection |
|---|---|---|---|
| `Any` | Yes | Yes | None |
| `object` | Yes | Only operations all objects have | Full |
| A precise type | Only matching values | Only that type's operations | Full |
Use this order of preference:
- Use a precise type when you know it.
- Use a union, a
Protocol, or aTypeVarwhen the type varies but has structure. - Use
objectwhen the function accepts anything and checks the type before using it. - Use
Anyonly when you cannot describe the type, such as with untyped third-party code or dynamic data like parsed JSON.
Common errors
- Annotating a parameter as
Anywhen you meantobject. Callers see no difference, but your function body loses all checking. - Returning
Anyfrom a function. Every caller then loses checking on the result. - Assuming an unannotated function is checked. By default mypy skips the bodies of functions that have no annotations.
- Forgetting that a bare
listordictmeanslist[Any]ordict[Any, Any].
Seeing where Any hides
Both major checkers can flag loose typing. Run mypy --strict, or mypy --disallow-any-explicit, to report explicit Any annotations. Pyright's strict mode reports unknown types. Turning these on for new code stops Any from spreading while older code is still being converted.
Exercise
A function log_value(value) prints any value it receives using print, and does nothing else with it. Should the parameter be annotated Any or object, and why?
Show answer
Use object. The function accepts every value and only uses an operation all objects support, so the checker can still verify the body. Any would accept the same arguments but turn off checking inside the function for no benefit.
Exercise
A function takes value: object and the body calls value.upper(). What does the checker do, and how do you fix it?
Show answer
The checker reports an error because object has no upper method. Narrow the type first with if isinstance(value, str):, then call value.upper() inside that block.