You stated:
To add a hash method, you need to make them immutable by setting unsafe_hash to True
The logic doesn't seem to fit the naming, and from how I interpret the docs you might do it this way but it is frowned on:
Although not recommended, you can force dataclass() to create a hash() method with unsafe_hash=True. This might be the case if your class is logically immutable but can nonetheless be mutated. This is a specialized use case and should be considered carefully.
It might be better to look at the settings of the eq and frozen parameters when unsafe_hash=False, (the default): Setting eq=True, frozen=True would then get a hash method generated.
Gosh, it takes my concentration to work this out :-)
Note that field ordering of dicts is only maintained in newer python versions (officially since 3.7, but also in CPython 3.6).
>>> c = {"r": 50, "g": 205, "b": 50, "alpha": alpha}
>>> Color = namedtuple("Color", c)
>>> Color(**c)
Color(r=50, g=205, b=50, alpha=0)
Hi, could you tell me why I got error for optional attribute?
>>> from dataclasses import dataclass >>> from typing import Optional >>> @dataclass ... class Color: ... r: float ... g: float ... b: float ... alpha: Optional[float] ... >>> blue = Color(r=0, g=0, b=255) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __init__() missing 1 required positional argument: 'alpha'Thansk in advance!