Can I format dataclass attributes in python?
Question:
I am trying to creating a python dataclass where fields can have formatted values. If I have the following
@dataclass(kw_only=True)
class childtestProduct(testProduct):
t1:float
t2:str
how can I have for example t1 be like 99.90€ and t2 be like 10/8/2002 ?
Answers:
You could use an approach with @property
decorator, as mentioned, and turn all dataclass fields into field properties:
from dataclasses import dataclass
from datetime import datetime, date
@dataclass(kw_only=True)
class ChildTestProduct:
t1: float
t2: datetime | str
@property
def t1(self) -> str:
return f'{self._t1:.2f}€'
@t1.setter
def t1(self, value: float):
self._t1 = value
@property
def t2(self) -> str:
return self._t2.strftime('%m/%d/%Y')
@t2.setter
def t2(self, value: datetime | str):
if isinstance(value, str):
self._t2 = datetime.strptime(value, '%m/%d/%y').date()
else:
self._t2 = value
p = ChildTestProduct(t1=99.9, t2='10/8/22')
print(p) # ChildTestProduct(t1='99.90€', t2='10/08/2022')
assert isinstance(p._t1, float)
assert isinstance(p._t2, date)
I am trying to creating a python dataclass where fields can have formatted values. If I have the following
@dataclass(kw_only=True)
class childtestProduct(testProduct):
t1:float
t2:str
how can I have for example t1 be like 99.90€ and t2 be like 10/8/2002 ?
You could use an approach with @property
decorator, as mentioned, and turn all dataclass fields into field properties:
from dataclasses import dataclass
from datetime import datetime, date
@dataclass(kw_only=True)
class ChildTestProduct:
t1: float
t2: datetime | str
@property
def t1(self) -> str:
return f'{self._t1:.2f}€'
@t1.setter
def t1(self, value: float):
self._t1 = value
@property
def t2(self) -> str:
return self._t2.strftime('%m/%d/%Y')
@t2.setter
def t2(self, value: datetime | str):
if isinstance(value, str):
self._t2 = datetime.strptime(value, '%m/%d/%y').date()
else:
self._t2 = value
p = ChildTestProduct(t1=99.9, t2='10/8/22')
print(p) # ChildTestProduct(t1='99.90€', t2='10/08/2022')
assert isinstance(p._t1, float)
assert isinstance(p._t2, date)