[Python] Type hinting optional properties in python 3.10+

Discussão em 'Python' iniciado por Stack, Junho 18, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose I have a Car class with the properties color and owner. Thinking from a seller's perspective, a new car doesn't have an owner yet. Therefore I'd like to make owner optional, as with the following code:

    from dataclasses import dataclass
    from enum import Enum

    class Color(Enum):
    RED = 0
    BLUE = 1

    @dataclass
    class Person():
    name: str
    license_id: int

    class Car():

    def __init__(self, color: Color, owner: Person|None = None) -> None:
    self.color: Color = color
    self.owner: Person|None = owner

    def sell_to(self, buyer: Person) -> None:
    self.owner = buyer


    Now when I try to sell this car to someone ...

    if __name__ == "__main__":
    new_car = Car(Color.RED)
    john_doe = Person("John Doe", 123)
    new_car.sell_to(john_doe)
    print(f"Car sold to {new_car.owner.name}")


    my language server (Pylance in VSCode) complains for new_car.owner.name that "name" is not a known attribute of "None", despite the code printing the correct output.

    When instead of using the type-hints Person|None I only use Person, Pylance complains in the init-definition that Expression of type "None" cannot be assigned to parameter of type "owner_type" and "None" is not assignable to "Person"

    How can I correctly type-hint the owner such that it is an optional property and I don't need to check if new_car.owner is not None every time I want to access that property?

    Continue reading...

Compartilhe esta Página