Skip to content

Instantly share code, notes, and snippets.

@acbart
Last active February 22, 2023 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acbart/6a169e0e301d6634c8b512edec4a6859 to your computer and use it in GitHub Desktop.
Save acbart/6a169e0e301d6634c8b512edec4a6859 to your computer and use it in GitHub Desktop.
Dataclass examples of common data structures
from dataclasses import dataclass
@dataclass
class Teacher:
name: str
years_teaching: int
has_corgi: bool
courses: list[str]
me = Teacher("Dr. Bart", 6, True, ["CISC108", "CISC320"])
print(me.name)
# Implementing a basic Linked List with dataclasses and strong static typing
@dataclass
class LinkedList:
pass
# Dummy node at end represents end of list
# Also called a Sentinel
TERMINAL_NODE = LinkedList()
# The actual data nodes
@dataclass
class LinkedNode(LinkedList):
data: int
next: LinkedList
# Equivalent to [5, 7, 3]
root = LinkedNode(5, LinkedNode(7, LinkedNode(3, TERMINAL_NODE)))
print(root.data, root.next.data, root.next.next.data)
from dataclasses import dataclass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment