The Any type
A value with the Any
type is dynamically typed. Mypy doesn’t knowanything about the possible runtime types of such value. Anyoperations are permitted on the value, and the operations are only checkedat runtime. You can use Any
as an “escape hatch” when you can’t usea more precise type for some reason.
Any
is compatible with every other type, and vice versa. You can freelyassign a value of type Any
to a variable with a more precise type:
- a: Any = None
- s: str = ''
- a = 2 # OK (assign "int" to "Any")
- s = a # OK (assign "Any" to "str")
Declared (and inferred) types are ignored (or erased) at runtime. They arebasically treated as comments, and thus the above code does notgenerate a runtime error, even though s
gets an int
value whenthe program is run, while the declared type of s
is actuallystr
! You need to be careful with Any
types, since they let youlie to mypy, and this could easily hide bugs.
If you do not define a function return value or argument types, thesedefault to Any
:
- def show_heading(s) -> None:
- print('=== ' + s + ' ===') # No static type checking, as s has type Any
- show_heading(1) # OK (runtime error only; mypy won't generate an error)
You should give a statically typed function an explicit None
return type even if it doesn’t return a value, as this lets mypy catchadditional type errors:
- def wait(t: float): # Implicit Any return value
- print('Waiting...')
- time.sleep(t)
- if wait(2) > 1: # Mypy doesn't catch this error!
- ...
If we had used an explicit None
return type, mypy would have caughtthe error:
- def wait(t: float) -> None:
- print('Waiting...')
- time.sleep(t)
- if wait(2) > 1: # Error: can't compare None and int
- ...
The Any
type is discussed in more detail in section Dynamically typed code.
Note
A function without any types in the signature is dynamicallytyped. The body of a dynamically typed function is not checkedstatically, and local variables have implicit Any
types.This makes it easier to migrate legacy Python code to mypy, asmypy won’t complain about dynamically typed functions.