pythonpython-dataclasses

How to declare multiple similar member variables of a dataclass in a single line?


Can this dataclass declaration:

@dataclass
class Point:
  x: float
  y: float
  z: float

be rewritten in order to reduce boilerplate and resemble something like this:

@dataclass
class Point:
  x, y, z: float

Solution

  • This is not really possible. The @dataclass decorator uses annotations to find the fields, and you can't have one annotation for multiple variables, see How to declare multiple variables with type annotation syntax in Python?.

    An alternative would be to use the make_dataclass function, but I suppose it will not work well with static type checkers and other tooling:

    from dataclasses import make_dataclass
    
    Point = make_dataclass(
        "Point",
        [(n, float) for n in "xyz"]
    )