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.

E6aa95ad57706cd0f08ab4f0325816f1?s=128

Tom Phillips

April 02, 2019
Tweet

More Decks by Tom Phillips

Other Decks in Programming

Transcript

  1. What are type hints? Tom Phillips Senior Data Scientist fluidly.com

    tomwphillips.co.uk
  2. Type hints are expressions that annotate functions. def greeting(name: str)

    -> str: return 'Hello ' + name argument annotation return value annotation
  3. >>> 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.
  4. 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
  5. 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
  6. • machine-checked documentation • code is easier to understand •

    code is easier to modify Benefits
  7. 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
  8. Getting started • mypy-lang.org – especially the cheat sheets •

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