Skip to content

Instantly share code, notes, and snippets.

Created Mar 7, 2021
What would you like to do?
Example of dataclass with property
from dataclasses import dataclass
from typing import List, Tuple
class Position:
name: str
dates: List[int]
items: Tuple
lon: float = 0.0
lat: float = 0.0
def sorted_items(self):
if self.items:
return tuple(sorted(list(self.items)))
return ()
p = Position(name="NullIsle", items=('d','c'), dates=[0,1,2], lon=1.1, lat=2.2)
print(p, p.lon)
try: = 1.0 # simple type cannot be changed
except Exception as err:
p.dates[0] = 10 # list values are NOT immutable in frozen dataclass
print(p, p.dates)
p.dates.append(20) # list is NOT immutable in frozen dataclass
print(p, p.dates)
p.dates.append('x') # list "type" not enforced in frozen dataclass
print(p, p.dates)
# p.items = ('c', 'd') # tuple is an immutable type in Python
q = Position(name="NullIsle", items=['d','c'], dates=[0,1,2], lon=1.1, lat=2.2)
print(q.items) # type not enforced
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment