Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

TODO: mypy

  • Complex data structures?
  • My types/classes?
  • Allow None (or not) for a variable.
from typing import Generator

def numbers(n: int) -> Generator[int, None, None]:
    return ( x for x in range(n))

print(list(numbers(10)))
from typing import List

def numbers(n: int) -> List[int]:

    return list(range(n))

print(numbers(10))
from typing import IO
import typing

fh1: IO = open("data.txt")

fh2: typing.IO = open("data.txt")

def f() -> int:
    file: Op[str] = None
    return 42

def func(param: int | str) -> int:
    if isinstance(param, int):
        return param
    elif isinstance(param, str):
        return len(param)

# In this case mypy understands that the if and elif cover all the valid options and does not complain about missing `return`
# If we remove the `elif` part we can see the mypy complaint.
# In another similar case in real code I saw it comlaining even when all the possibilities were handled.


class A:
    pass
class B:
    pass

def func2(param: A | B) -> int:
    if isinstance(param, A):
        return 1
    elif isinstance(param, B):
        return 2