Skip to content

Instantly share code, notes, and snippets.

@gamesbook
Created Mar 7, 2021
Embed
What would you like to do?
Example of dataclass with property
from dataclasses import dataclass
from typing import List, Tuple
@dataclass(frozen=True)
class Position:
name: str
dates: List[int]
items: Tuple
lon: float = 0.0
lat: float = 0.0
@property
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:
p.lat = 1.0 # simple type cannot be changed
print(p, p.lat)
except Exception as err:
print(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
print(p.sorted_items)
q = Position(name="NullIsle", items=['d','c'], dates=[0,1,2], lon=1.1, lat=2.2)
print(q.items) # type not enforced
print(q.sorted_items)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment