-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Reconciling Dataclasses And Properties In Python - Florimond Manca #387
Comments
Appreciate your effort to bring this detailed analysis, It really help us to take deep dive. |
Great article! |
@ruslaniv It seems you can set from dataclasses import dataclass, field
@dataclass
class Vehicle:
wheels: int
_wheels: int = field(init=False, repr=False, default=4)
@property
def wheels(self) -> int:
print("getting wheels")
return self._wheels
@wheels.setter
def wheels(self, wheels: int) -> None:
print("setting wheels to", wheels)
self._wheels = wheels But this wouldn't work: the >>> Vehicle()
setting wheels to <property object at 0x1045ff100>
getting wheels
Vehicle(wheels=<property object at 0x1045ff100>) After some digging into the source code of the # dataclasses.py, L730:732
# If the default value isn't derived from Field, then it's only a
# normal default value. Convert it to a Field().
default = getattr(cls, a_name, MISSING) When processing the class, We can't set a default using One solution that would work is ignoring that initial @wheels.setter
def wheels(self, wheels: int) -> None:
if isinstance(wheels, property):
return
print("setting wheels to", wheels)
self._wheels = wheels Output: >>> Vehicle()
getting wheels
Vehicle(wheels=4) This could be moved to a minimal class dataclass_property(property):
def __set__(self, obj, value):
if isinstance(value, property):
# dataclasses tries to set a default and uses the
# getattr(cls, name). But the real default will come
# from: `_attr = field(..., default=...)`.
return
super().__set__(obj, value) Usage would be to replace I won't comment on the level of hackiness, but any usage of the approach described in this blog post was already in the "NO WARRANTY PROVIDED" zone. :-) |
Thanks for this walk through and the short and sweet "recipe" at the end |
Reconciling Dataclasses And Properties In Python - Florimond Manca
I love Python dataclasses, but combining them with properties is not obvious. This is a problem solving report — and a practical introduction to dataclasses!
https://florimond.dev/en/posts/2018/10/reconciling-dataclasses-and-properties-in-python/
The text was updated successfully, but these errors were encountered: