[Python] Data class with argument optional only in init

Discussão em 'Python' iniciado por Stack, Julho 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following simple class in Python:

    class Point:
    def __init__(x: int, y: int | None = None):
    self.x = x
    self.y = y if y is not None else x


    How can the same thing be implemented using a @dataclass? The obvious would be to do the following:

    from dataclasses import dataclass

    @dataclass
    class Point:
    x: int
    y: int | None

    def __post_init__(self):
    if self.y is None:
    self.y = self.x


    This appears to work, but changes type of y to an optional, resulting in false positive warning issued by e.g. Point(1, 2).y + 0.

    How can I make y optional only in __init__? The only thing that comes to mind is to split it in half:

    @dataclass
    class Point:
    x: int
    y: int = field(init=False)
    _y: InitVar[int | None]

    def __post_init__(self, _y: int | None):
    self.y = _y if _y is not None else self.x


    but it seems overly verbose

    Continue reading...

Compartilhe esta Página