Sub topic 7
Any, unannotated code, and gradual typing
This chapter assumes you can annotate functions and variables, run mypy or Pyright from the command line, and read their error messages. It covers what happens where annotations are missing or deliberately vague, and how that affects what a checker can promise you.
Gradual typing in one idea
Python's type system is gradual. You can annotate some parts of a program and leave others alone, and the checker still works on the whole program. The special type Any makes this possible. Any is compatible with every other type in both directions. A value of type Any can be passed where an int is expected, and an int can be passed where Any is expected. In practice, Any tells the checker to stop checking that value.
import json
from typing import Any
def parse(raw: str) -> Any:
return json.loads(raw)
data = parse('{"n": 1}')
data.anything_goes() # no checker error; AttributeError at runtime
count: int = data # accepted, even if data holds a dictNeither line below data = ... is reported. The checker has no information to contradict them. At runtime the first one fails and the second one silently stores the wrong type.
Any spreads
Operations on an Any value produce Any. Attribute access, calls, indexing and arithmetic all return Any, so one loose value can switch off checking for everything computed from it.
from typing import Any
def load() -> Any: ...
row = load()
name = row["user"]["name"] # Any
size = len(name) # int, because len always returns int
label = name.title() # Any
reveal_type(label) # AnyA good habit is to put a precise annotation at the boundary where the Any enters, such as the result of json.loads, a untyped library call, or an Any-returning function. That stops the spread:
from typing import Any
def get_name(payload: Any) -> str:
name: str = payload["user"]["name"]
return name.title()The checker accepts the assignment to str because Any is compatible with it. From that line on, name is a real str. Nothing verifies this at runtime, so it is still a promise from you to the checker.
Any versus object
object is also a type that accepts every value, but it behaves differently. A value typed object allows only operations that every object supports.
def show(value: object) -> str:
return value.upper() # error: "object" has no attribute "upper"Use object when you really mean "anything, and I will not assume more". You must narrow it with isinstance before you use it. Use Any only when you want checking turned off. The practical rule is to prefer object for "unknown input" and keep Any for places you cannot describe yet.
Unannotated code
A function with no annotations is untyped. Its parameters are treated as Any, and its return type is not declared. The two checkers handle this very differently.
mypy, by default, does not check the body of an untyped function at all. Pyright checks every body and infers what it can.
def add(a, b):
return a + b
def broken():
return 1 + "a"
result = add(1, 2)
reveal_type(result)With default settings:
- mypy reports nothing for
broken, because its body is skipped. It revealsresultasAny. - Pyright reports the unsupported
+betweenintandstrinbroken. It infers a return type from the arguments at the call site and revealsresultasint.
Pyright also infers a parameter's type from its default value. A parameter written as retries=3 is treated as int, while a bare a has an unknown type.
Partially annotated functions
In mypy, a single annotation makes a function typed, so its body is checked. Parameters you left out are still implicitly Any.
def scale(value: float, factor) -> float:
return value * factor # checked, but factor is Any
scale(2.0, "ten") # accepted: factor is AnyA common trap is def __init__(self):. With no annotations this is untyped, so mypy skips the body. Writing def __init__(self) -> None: makes it typed and checked. The -> None is worth adding for that reason alone.
Implicit Any in generics
A bare generic such as list or dict means list[Any] or dict[Any, Any]. These are easy to miss because they look like precise types.
def total(values: list) -> int:
return sum(values) # values is list[Any]; the element type is unchecked
def total_safe(values: list[int]) -> int:
return sum(values)Tightening the checks
Both tools have options that report or limit Any. The table lists the common ones.
| Goal | mypy option | Pyright setting |
|---|---|---|
| Check bodies of unannotated functions | `check_untyped_defs` | Always on |
| Require annotations on every function | `disallow_untyped_defs` | `reportMissingParameterType` and `reportUnknownParameterType` |
| Reject half-annotated functions | `disallow_incomplete_defs` | `reportMissingParameterType` |
| Reject bare `list`, `dict` | `disallow_any_generics` | `reportMissingTypeArgument` |
| Warn when an `Any` value is returned from a typed function | `warn_return_any` | `reportUnknownVariableType` and related rules |
| Forbid writing `Any` | `disallow_any_explicit` | No single equivalent |
Pyright separates two ideas that mypy merges. An explicit Any is a type you wrote. An unknown type is one the checker could not work out, such as an unannotated parameter. Both are displayed as Any in hover text, but the reportUnknown... rules in strict mode report only the unknown kind.
A moderate configuration for mypy that catches most hidden problems without demanding full annotations looks like this:
[tool.mypy]
python_version = "3.12"
check_untyped_defs = true
warn_return_any = true
disallow_any_generics = trueCommon mistakes
- Treating
Anyas a safe placeholder. Any code that touches the value is unchecked, and the errors appear only at runtime. - Assuming that no errors means correct. A checker that skips untyped bodies can report a clean run on code full of bugs.
- Comparing the two checkers on unannotated code. The same file can pass in mypy and fail in Pyright because of the body-checking difference, not because one tool is stricter in general.
- Converting
Anyto a real type with an annotation and then trusting it without validation. Useisinstancechecks or a validation library when the data comes from outside your program.
Summary
Any is the escape hatch that lets typed and untyped code live together. It disables checking for any value it touches, and that effect spreads through later operations. mypy and Pyright differ in how they treat unannotated functions: mypy skips their bodies by default, while Pyright checks and infers. Stricter options exist in both tools, and later chapters on strict mode and incremental adoption build on them.
Exercise
Consider this file. What does mypy report with default settings, and what does Pyright report? Name the single change that makes mypy report the error, and name a second change, not involving mypy options, that does the same. def price(item): return item.cost + "USD"
Show answer
Neither the function nor its callers are annotated, so mypy by default skips the body and reports nothing. Pyright checks the body, but since item is unknown, item.cost is unknown too, so it likely reports nothing either unless item has a known type. Setting checkuntypeddefs = true makes mypy check the body, but the same limitation applies: item is Any, so item.cost + "USD" is also Any and still passes. To make the checker find the bug, give the parameter a real type, for example a class with cost: int. Both tools then report that int and str cannot be added. The lesson is that checking a body is not enough. The parameter types must be declared for the checker to find errors.