Function signatures and dynamic vs static typing

A function without type annotations is considered to be dynamically typed by mypy:

  1. def greeting(name):
  2. return 'Hello ' + name

By default, mypy will not type check dynamically typed functions. This meansthat with a few exceptions, mypy will not report any errors with regular unannotated Python.

This is the case even if you misuse the function: for example, mypy would currentlynot report any errors if you tried running greeting(3) or greeting(b"Alice")even though those function calls would result in errors at runtime.

You can teach mypy to detect these kinds of bugs by adding type annotations (alsoknown as type hints). For example, you can teach mypy that greeting both acceptsand returns a string like so:

  1. def greeting(name: str) -> str:
  2. return 'Hello ' + name

This function is now statically typed: mypy can use the provided type hints to detectincorrect usages of the greeting function. For example, it will reject the followingcalls since the arguments have invalid types:

  1. def greeting(name: str) -> str:
  2. return 'Hello ' + name
  3.  
  4. greeting(3) # Argument 1 to "greeting" has incompatible type "int"; expected "str"
  5. greeting(b'Alice') # Argument 1 to "greeting" has incompatible type "bytes"; expected "str"

Note that this is all still valid Python 3 code! The function annotation syntaxshown above was added to Python as a part of Python 3.0.

If you are trying to type check Python 2 code, you can add type hintsusing a comment-based syntax instead of the Python 3 annotation syntax.See our section on typing Python 2 code for more details.

Being able to pick whether you want a function to be dynamically or staticallytyped can be very helpful. For example, if you are migrating an existingPython codebase to use static types, it’s usually easier to migrate by incrementallyadding type hints to your code rather than adding them all at once. Similarly,when you are prototyping a new feature, it may be convenient to initially implementthe code using dynamic typing and only add type hints later once the code is more stable.

Once you are finished migrating or prototyping your code, you can make mypy warn youif you add a dynamic function by mistake by using the —disallow-untyped-defsflag. See The mypy command line for more information on configuring mypy.

Note

The earlier stages of analysis performed by mypy may report errorseven for dynamically typed functions. However, you should not relyon this, as this may change in the future.