Skip to content

Instantly share code, notes, and snippets.

@Viicos
Created August 14, 2023 19:38
Show Gist options
  • Save Viicos/26d8cc7ade6fb8828448142e8bf0951b to your computer and use it in GitHub Desktop.
Save Viicos/26d8cc7ade6fb8828448142e8bf0951b to your computer and use it in GitHub Desktop.
dataclasses, InitVar and properties
from dataclasses import dataclass, field, InitVar
@dataclass
class A:
_x: int = field(init=False)
x: InitVar[int]
def __post_init__(self, x: int) -> None:
self.x = x
@property
def x(self) -> int:
return self._x
@x.setter
def x(self, value: int) -> None:
print(value)
print("dc Setter is called")
self._x = value
a = A()
#> <property object at 0x7fa7b2813f60>
#> dc Setter is called
# Weird, the property object is used if no value is provided for x
a = A(x=1)
#> 2
# > dc Setter is called
# Works as expected
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment