Skip to content

Type checking

lachmanfrantisek edited this page Feb 20, 2019 · 1 revision

Types in Python

  • You can add type hints/annotations to Python code. (Can be done incrementally, not necessarily everywhere.)
  • The are tools to check the type consistency:

Examples:

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

If you have problems with cyclic imports, use a string with the name instead of the type:

def greeting(person: "Person") -> str:
    return 'Hello ' + person.name

The types are usefull for finding bugs before the runtime:

types_example.py

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

# Wrong usage:
greeting(5)
$ mypy types_example.py
types_example.py:5: error: Argument 1 to "greeting" has incompatible type "int"; expected "str"
Clone this wiki locally