Skip to content

18th November 2021

Coding

Python

Type Hints

  • New: Define a TypeVar with restrictions.

    from typing import TypeVar
    
    AnyStr = TypeVar('AnyStr', str, bytes)
    
  • New: Use a constrained TypeVar in the definition of a class attributes.

    If you try to use a TypeVar in the definition of a class attribute:

    class File:
        """Model a computer file."""
    
        path: str
        content: Optional[AnyStr] = None # mypy error!
    

    mypy will complain with Type variable AnyStr is unbound [valid-type], to solve it, you need to make the class inherit from the Generic[AnyStr].

    class File(Generic[AnyStr]):
        """Model a computer file."""
    
        path: str
        content: Optional[AnyStr] = None
    

Properties

  • New: Give an overview on Python's @property decorator.

Pydantic

Operative Systems

Linux

Vim