Parámetros:
def foo(a: expression, b: expression = 5):
...
Valores de retorno:
def sum() -> expression:
...
Se pueden anotar los tipos esperados de las variables
def greeting(name: str) -> str:
return 'Hello ' + name
Annotations en Python 3
def foo(a: str, b: int) -> str:
return a + str(b)
foo.__annotations__
{'a': str, 'b': int, 'return': str}
Podríamos tipar sólo algunas variables
def foo(a: str, b) -> str:
# "b" puede ser cualquier cosa con un __str__
return a + str(b)
foo.__annotations__
{'a': str, 'return': str}
mypy
en Python 3pip install mypy-lang
Si tengo un script como este en foo_py3.py
:
def foo(a: str, b: int) -> str:
return a + str(b)
print(foo("arbol", "manzana"))
Lo puedo correr usando mypy para chequear tipos:
mypy foo_py3.py
foo_py3.py:5: error: Argument 2 to "foo" has incompatible type "str"; expected "int"
mypy
en Python 2Con una sintaxis diferente, si tengo un script como este en foo_py2.py
:
def foo(a, b): # type: (str, int) -> str
return a + " " + str(b)
print foo("arbol", "manzana")
También lo puedo correr usando mypy para chequear tipos:
mypy --py2 foo_py2.py
foo_py2.py:5: error: Argument 2 to "foo" has incompatible type "str"; expected "int"
typeguard
para hacer type checking en el intérpretepip install typeguard
Usando un decorador:
from typeguard import typechecked
@typechecked
def foo(a: str, b: int) -> str:
return a + str(b)
foo("arbol", "manzana")
...
TypeError: type of argument b must be int; got str instead
typing
typing
Tiene tipos más complejos
Iterable
from typing import Iterable
def greet_all(names: Iterable[str]) -> None:
for name in names:
print('Hello, {}'.format(name))
Tuple
from typing import Tuple
def f(t: Tuple[int, str]) -> None:
t = 1, 'foo' # OK
t = 'foo', 1 # Type check error
typing
Permite crear abstracciones convenientes
Un punto, un vector...
from typing import Tuple, List
Point = Tuple[float, float]
def distance(point: Point) -> float: ...
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector: ...
Una conexión a un servidor
from typing import Dict, Tuple, List
ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: List[Server]) -> None: ...
@agustinbenassi de @datosgobar
https://github.com/datosgobar/presentacion-type-checking-python