Created
August 14, 2023 19:38
-
-
Save Viicos/26d8cc7ade6fb8828448142e8bf0951b to your computer and use it in GitHub Desktop.
dataclasses, InitVar and properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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