Upgrade to Pro — share decks privately, control downloads, hide ads and more …

What are type hints?

What are type hints?

Lightning talk at 55th Pydata London Meetup.

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Tom Phillips

April 02, 2019
Tweet

More Decks by Tom Phillips

Other Decks in Programming

Transcript

  1. Type hints are expressions that annotate functions. def greeting(name: str)

    -> str: return 'Hello ' + name argument annotation return value annotation
  2. >>> def greeting(name: str) -> str: ... return 'Hello '

    + name ... >>> greeting.__annotations__ {'name': <class 'str'>, 'return': <class 'str'>} Almost nothing happens at runtime. Use mypy to analyse type hints.
  3. Example program.py def greeting(name: str) -> str: return 'Hello '

    + name greeting(3) greeting(b'Bob') $ python3 -m pip install mypy $ mypy program.py program.py:4: error: Argument 1 to "greeting" has incompatible type "int"; expected "str" program.py:5: error: Argument 1 to "greeting" has incompatible type "bytes"; expected "str" 1 2 3 4 5
  4. A more complex example from typing import Iterable, TypeVar T

    = TypeVar('T', int, float, complex) # type variable Vector = Iterable[T] # type alias def dot_product(a: Vector[T], b: Vector[T]) -> T: return sum(x * y for x, y in zip(a, b)) dot_product([1, 2], [3, 4]) # OK dot_product(['1', '2'], ['3', '4']) # incompatible type
  5. Gradual typing: annotate part of the program “Python will remain

    a dynamically typed language, and [we] have no desired to ever make type hints mandatory, even by convention.” Authors of PEP 484
  6. Getting started • mypy-lang.org – especially the cheat sheets •

    PEP 484 – very accessible We’re hiring! fluidly.com/careers