Sub topic 7
Any, object, and gradual typing
This chapter assumes you can annotate parameters and return values, know that the interpreter ignores hints at runtime, and have run mypy or pyright on a file. It covers what happens when you can't, or don't want to, say precisely what a type is.
Gradual typing in one model
Python's type system is gradual. A checker verifies the parts of a program that are annotated and trusts the parts that are not. The special type Any is the bridge between the two. A value of type Any is compatible with every other type, in both directions.
That two-way compatibility is what separates Any from every other type:
- You can assign an
Anyvalue to a variable of any type. - You can assign any value to a variable of type
Any. - You can access any attribute on an
Anyvalue or call it with any arguments, and the checker reports nothing.
from typing import Any
def total(values: Any) -> int:
return values.sum() # no error: the checker assumes this is fine
x: Any = "text"
n: int = x # accepted: Any is assignable to int
print(n + 1) # the checker is silent, but this raises TypeError when runThe last line fails at runtime with TypeError: can only concatenate str (not "int") to str. The checker had no basis to warn you, because Any switched checking off for x and for everything derived from it.
object: the top of the type hierarchy
Every value is an instance of object, so object accepts anything, as Any does. The difference is what you may do next. A checker allows only operations that every object supports, such as str(), ==, and isinstance(). Anything more specific is an error until you narrow the type.
def describe(value: object) -> str:
if isinstance(value, int):
return f"int {value + 1}"
if isinstance(value, str):
return f"str {value.upper()}"
return f"other {type(value).__name__}"
print(describe(41))
print(describe("a"))
print(describe(3.5))This prints int 42, str A, and other float. Inside each isinstance branch the checker knows the narrower type, so value + 1 and value.upper() are accepted. Outside the branches, value.upper() would be reported as an error.
In short, Any means "stop checking this" and object means "I accept anything, and I will check before I use it."
| Annotation | What can be passed in | What you may do with the value | Checker protection |
|---|---|---|---|
| `Any` | Anything | Anything | None for this value |
| `object` | Anything | Only operations all objects support, until narrowed | Full |
| A precise type such as `int` | Only compatible values | Operations of that type | Full |
Where Any comes from without you writing it
Most Any values in a codebase are implicit. Know the common sources, because they spread silently.
- Unannotated parameters and returns. A function with no annotations has parameters of type
Anyand returnsAny. Any call to it produces anAnyresult that flows into your typed code. - Untyped libraries. Imports from a package with no type information are
Any. mypy reportsimport-untypedfor this. pyright reports unresolved stubs. - Standard library functions that cannot know the shape.
json.loadsreturnsAny. - Bare generics. An annotation like
listordictmeanslist[Any]ordict[Any, Any].
Also note that by default mypy does not check the body of a function that has no annotations at all. A bug inside such a function is never reported. The --check-untyped-defs flag turns that checking on, and it is often the best first step when adopting hints.
Containing Any at the boundary
The practical technique is to let Any enter at one place, then convert it to a precise type immediately. Treat the untrusted value as object, check it, and return a typed result.
import json
def read_port(raw: str) -> int:
data: object = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("expected a JSON object")
port = data.get("port")
if not isinstance(port, int):
raise ValueError("port must be an integer")
return port
print(read_port('{"port": 8080}'))This prints 8080. The annotation data: object discards the Any that json.loads returned, so every later use must be justified by a check. Callers of read_port get a real int, and the checks run at runtime too, so bad input fails with a clear message.
Compare the unchecked version, port: int = json.loads(raw)["port"]. It type-checks cleanly, and a string in the JSON would flow onward as if it were an int.
cast and type: ignore
Two other tools override the checker. Use each deliberately.
typing.cast(int, value)tells the checker to treatvalueasint. It does nothing at runtime, so no check happens. If you are wrong, the program fails later and further from the cause.# type: ignore[code]suppresses one error on one line. Include the error code so you suppress only what you intended.
from typing import cast
raw: object = 5
number = cast(int, raw)
print(number + 1)This prints 6 only because the cast happens to be true. Prefer an isinstance check, which verifies the claim, over a cast, which only asserts it.
Choosing between Any, object, and a precise type
A few guidelines follow from the flow:
- Prefer a union such as
int | stroverAnywhen the set of possibilities is small and known. - Prefer a
Protocolwhen you only need certain methods, as in the earlier chapter on structural typing. - Use
Anywhen the type truly cannot be expressed, for example a dynamic attribute system or a legacy function that you will annotate later. - Use
objectfor parameters that accept any value and for values you are about to validate.
Finding Any that you did not intend
Strict settings make hidden Any visible. These are the commonly used ones:
| Goal | mypy flag | pyright setting |
|---|---|---|
| Check bodies of unannotated functions | `--check-untyped-defs` | Enabled by default |
| Require annotations on all functions | `--disallow-untyped-defs` | `reportMissingParameterType` |
| Forbid bare generics such as `list` | `--disallow-any-generics` | `reportMissingTypeArgument` |
| Forbid writing `Any` explicitly | `--disallow-any-explicit` | `reportAny` in strict mode |
| Warn on needless casts | `--warn-redundant-casts` | `reportUnnecessaryCast` |
The setting --strict in mypy turns on most of these together. Enabling them one at a time on an existing codebase keeps the number of new errors manageable.
Common errors
- Using Any as a quick fix. The error disappears, and so does checking for every value derived from it. Prefer
objectplus narrowing. - Assuming
objectallows attribute access.value.nameon anobjectis an error. That error is correct, and it is the reason to preferobject. - Bare
dictorlist. These accept anything and returnAnyelements. Writedict[str, int]. - Trusting a cast.
castnever validates. A wrong cast hides a bug instead of fixing it. - Forgetting the return annotation. A function with annotated parameters but no return annotation is treated as returning
Anyin many checkers' default modes, so results from it are unchecked.
Exercise
A function def load(raw: str) -> Any: return json.loads(raw) is called as age: int = load(text)["age"]. The checker reports nothing, yet the program later fails when age is a string. Rewrite load so the checker catches the problem, and explain why object helps where Any does not.
Show answer
Change the return annotation to object (or better, validate and return a specific type such as dict[str, object]). With -> object, the expression load(text)["age"] is an error because object does not support indexing, so the caller must narrow with isinstance(result, dict) and check that the age is an int before using it. Any is compatible with int in both directions, so the original code passed silently.