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:

  1. a: Any = None
  2. s: str = ''
  3. a = 2 # OK (assign "int" to "Any")
  4. 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:

  1. def show_heading(s) -> None:
  2. print('=== ' + s + ' ===') # No static type checking, as s has type Any
  3.  
  4. show_heading(1) # OK (runtime error only; mypy won't generate an error)

You should give a statically typed function an explicit Nonereturn type even if it doesn’t return a value, as this lets mypy catchadditional type errors:

  1. def wait(t: float): # Implicit Any return value
  2. print('Waiting...')
  3. time.sleep(t)
  4.  
  5. if wait(2) > 1: # Mypy doesn't catch this error!
  6. ...

If we had used an explicit None return type, mypy would have caughtthe error:

  1. def wait(t: float) -> None:
  2. print('Waiting...')
  3. time.sleep(t)
  4.  
  5. if wait(2) > 1: # Error: can't compare None and int
  6. ...

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.