Skip to content

Instantly share code, notes, and snippets.

@snnwolf
Forked from decatur/dataclass_sample.py
Created October 15, 2021 16:05
Show Gist options
  • Save snnwolf/50096c90047b2f2f500df9605ffa88ff to your computer and use it in GitHub Desktop.
Save snnwolf/50096c90047b2f2f500df9605ffa88ff to your computer and use it in GitHub Desktop.
Use Python dataclass to autogenerate timestamp and sequence id on an object.
from dataclasses import dataclass, field
from itertools import count
from datetime import datetime
counter = count()
@dataclass
class Event:
message: str
create_at: datetime = field(default_factory=datetime.now)
index: int = field(default_factory=lambda: next(counter))
Event('foo')
Event('bar')
# Event(message='foo', create_at=datetime.datetime(2018, 9, 21, 13, 5, 23, 781750), index=0)
# Event(message='bar', create_at=datetime.datetime(2018, 9, 21, 13, 5, 23, 781750), index=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment