Skip to content

Instantly share code, notes, and snippets.

@decatur
Created September 21, 2018 11:09
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save decatur/899691f2bd9e42cdb617c81cadc10f62 to your computer and use it in GitHub Desktop.
Save decatur/899691f2bd9e42cdb617c81cadc10f62 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