20250409

TIL

PEP 484 - Type Hints

def concat_strings(s1: str, s2: str) -> str:
    return s1 + s2


print(concat_strings.__annotations__)
# {'s1': <class 'str'>, 's2': <class 'str'>, 'return': <class 'str'>}
# [Type aliases](https://peps.python.org/pep-0484/#type-aliases)
Url = str

def retry(url: Url, retry_count: int) -> None: ...
from typing import TypeVar, Iterable, Tuple

T = TypeVar('T', int, float, complex)
Vector = Iterable[Tuple[T, T]]

def inproduct(v: Vector[T]) -> T:
    return sum(x*y for x, y in v)

I have never seen type aliases. Isn’t it confusing to assign a different name? It might be not widely-used as we have int | float | str kind type annotations.

Frameworks expecting callback functions of specific signatures might be type hinted using Callable[[Arg1Type, Arg2Type], ReturnType]

I don’t have experience with Callable, TypeVar, too.

# PEP 484 — User-defined generic types
from typing import TypeVar, Generic
from logging import Logger

T = TypeVar('T')

class LoggedVar(Generic[T]):
    def __init__(self, value: T, name: str, logger: Logger) -> None:
        self.name = name
        self.logger = logger
        self.value = value

    def set(self, new: T) -> None:
        self.log('Set ' + repr(self.value))
        self.value = new

    def get(self) -> T:
        self.log('Get ' + repr(self.value))
        return self.value

    def log(self, message: str) -> None:
        self.logger.info('{}: {}'.format(self.name, message))

I was not aware of this use case. It might be useful in the future, perhaps.

Consider a class Employee with a subclass Manager. Now suppose we have a function with an argument annotated with List[Employee]. Should we be allowed to call this function with a variable of type List[Manager] as its argument? Many people would answer “yes, of course” without even considering the consequences. But unless we know more about the function, a type checker should reject such a call: the function might append an Employee instance to the list, which would violate the variable’s type in the caller.

Hmm… I think people around me are good with meaning subsclasses.. but I think I should do some research on this controversy.

The PEP continues to describe how type checkers should behave, but I think they are too much information for my current self. I’ll skip for now.


PEP8: The style guide for Python code

PEP 20: The Zen of Python

PEP 572: Introduction of the walrus operator


TODO:


index 20250408 20250410