DEV Community

andi
andi

Posted on

Typed python + typed NamedTuple <3

be aware of limitations:

Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.

https://stackoverflow.com/a/43977962/953553

way to use:

  • defining a class with typed fields
  • specify types of args the functions receive

how it is checked?

  • e.g good IDE like pycharm will do it
  • install pep8 and mypy-lang to be warned

EXAMPLES

basic types

(run with pep8 and mypy-lang installed):

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

then calling:

greeting(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in greeting
TypeError: Can't convert 'int' object to str implicitly
greeting('3')
#'Hello 3'

support for classes and inheritance

more complex types:

List

from typing import List

Tuple

from typing import Tuple

NamedTuple

from typing import NamedTuple

Dict

from typing import Dict

Union

is the way to allow more than one type for varaible.

Optional

more nice examples of typed stuff here:

https://blog.daftcode.pl/first-steps-with-python-type-system-30e4296722af

typed tuple in python3 is typed version of collections.namedtuple

from typing import NamedTuple


class Employee(NamedTuple):
    name: str
    id: int = 3

employee = Employee('Guido')
assert employee.id == 3

Top comments (0)