Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dataclasses howto (code for the carbon.now.sh images)
import json
from datetime import datetime
from datetime import date
from pydantic.dataclasses import dataclass
from dataclasses import asdict
@dataclass(frozen=True, order=True)
class Foo:
name: str
int_value: int
float_value: float
ts: datetime
dt: date
@dataclass(frozen=True, order=True)
class Bar:
name: str
value: Foo
datetime_to_str = lambda v: v.isoformat() if isinstance(v, (datetime, date)) else None
bar=Bar('bar', Foo('foo', 1, 1/3, datetime.now(), datetime.now().date()))
str_bar = json.dumps(asdict(bar), default=datetime_to_str)
bar_data = json.loads(str_bar)
print(Bar(**bar_data))
Bar(name='bar', value=Foo(name='foo', int_value=1, float_value=0.3333333333333333, ts=datetime.datetime(2022, 8, 13, 12, 38, 45, 46213), dt=datetime.date(2022, 8, 13)))
--------------
import json
from typing import Dict, List, Any, Tuple
from dataclasses import dataclass, asdict, field
@dataclass(frozen=True, order=True)
class Foo:
name: str
dict_value: Dict[int, Any] = field(hash=False)
lst_value: List[str] = field(hash=False)
tuple_value: Tuple[Any]
ignored_lst_value: List[str] = field(compare=False, hash=False)
foo = Foo('foo', {1: 'a', 2: []}, ['b', 3], ('c', 4), [1,2,3])
--------------
import json
from datetime import datetime
from datetime import date
from dataclasses import dataclass, asdict
@dataclass(frozen=True, order=True)
class Foo:
name: str
int_value: int
float_value: float
ts: datetime
dt: date
@classmethod
def from_data(cls, data):
return Foo(
name=data['name'],
int_value=data['int_value'],
float_value=data['float_value'],
ts=datetime.fromisoformat(data['ts']),
dt=datetime.fromisoformat(data['dt']).date()
)
@dataclass(frozen=True, order=True)
class Bar:
name: str
value: Foo
@classmethod
def from_data(cls, data):
return Bar(
name=data['name'],
value=Foo.from_data(data['value'])
)
datetime_to_str = lambda v: v.isoformat() if isinstance(v, (datetime, date)) else None
>>> bar = Bar('bar', Foo('foo', 1, 1/3, datetime.now(), datetime.now().date()))
>>> data = json.dumps(asdict(bar), default=datetime_to_str)
>>> Bar.from_data(json.loads(data))
Bar(name='bar', value=Foo(name='foo', int_value=1, float_value=0.3333333333333333, ts=datetime.datetime(2022, 8, 13, 12, 15, 44, 51572), dt=datetime.date(2022, 8, 13)))
>>> {bar: 1}
{Bar(name='bar', value=Foo(name='foo', int_value=1, float_value=0.3333333333333333, ts=datetime.datetime(2022, 8, 13, 12, 16, 45, 526179), dt=datetime.date(2022, 8, 13))): 1}
--------------
import gzip
import json
from dataclasses import dataclass, asdict
@dataclass(frozen=True, order=True)
class Foo:
name: str
int_value: int
float_value: float
foos = [Foo('foo', 2, 1/3), Foo('foo', 1, 1/3)]
with gzip.open('foo.jsonl.gz', 'wt') as outfile:
for foo in foos:
outfile.write(json.dumps(asdict(foo)) + '\n')
new_foos = [
Foo(**json.loads(row))
for row in gzip.open('foo.jsonl.gz', 'rt')
]
--------------
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Foo:
name: str
int_value: int
float_value: float
>>> sorted([Foo('foo', 2, 1/3), Foo('foo', 1, 1/3)])
[Foo(name='foo', int_value=1, float_value=0.3333333333333333),
Foo(name='foo', int_value=2, float_value=0.3333333333333333)]
--------------
from dataclasses import dataclass
@dataclass
class Foo:
name: str
int_value: int
float_value: float
>>> Foo('foo', 1, 1/3)
Foo(name='foo', int_value=1, float_value=0.3333333333333333)
--------------
from dataclasses import dataclass
@dataclass
class Foo:
name: str
int_value: int
float_value: float
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment