Guest User

Nanotable Demo

a guest
Jun 4th, 2026
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | Source Code | 0 0
  1. from nanotable import Table, UniqueIndex, SortedMultiIndex
  2. from datetime import datetime
  3. from dataclasses import dataclass
  4. from typing import Any, Protocol
  5.  
  6.  
  7. @dataclass  # Doesn't have to be a dataclass. Any objects and mappings are supported
  8. class Contact:
  9.     name: str
  10.     phone: str
  11.     date_added: datetime
  12.  
  13.  
  14. # Completely optional, but results in full IDE support
  15. class Indexes(Protocol):
  16.     name: UniqueIndex[Contact, str]
  17.     phone: UniqueIndex[Contact, str]
  18.     date_added: SortedMultiIndex[Contact, datetime]
  19.  
  20.  
  21. table = Table[Contact, Indexes, UniqueIndex[Contact, str]](of_objects=True).primary_index_on("name")\
  22.     .index_on("phone", kind=UniqueIndex, required=False)\
  23.     .index_on("date_added", kind=SortedMultiIndex, required=True)
  24.  
  25. table.add(Contact("John Doe", "0123456789", datetime.now()))
  26. table.add(Contact("John Smith", "9876543210", datetime.now()))
  27.  
  28. table.at["John Doe"]
  29. table.by.name["John Doe"]
  30.  
  31. # Range queries on sorted indexes
  32. table.by.date_added[datetime(2026, 6, 4):datetime.now()]
  33.  
  34. guy = table.by.phone["9876543210"]
  35. with table.rekey(guy):
  36.     guy.name += " (owes me money!)"
  37.     # Indexes are automatically updated
  38.  
Advertisement
Add Comment
Please, Sign In to add comment