Last active
July 11, 2025 15:11
-
-
Save Tishka17/b01a060831ba7d8408124c64f04cbdf3 to your computer and use it in GitHub Desktop.
ID Type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import field, dataclass | |
class ID: | |
def __init__(self, value: int | None = None): | |
self.value = value | |
def set(self, value: int): | |
if self.value is not None: | |
raise ValueError("Value already exists") | |
self.value = value | |
def __eq__(self, other): | |
if self.value is None: | |
return self is other | |
else: | |
return type(self) == type(other) and self.value == other.value | |
def __repr__(self): | |
if self.value is None: | |
return f"ID(tmp@{id(self)})" | |
return f"{self.__class__.__qualname__}({self.value})" | |
@dataclass | |
class Parent: | |
id: ID = field(default_factory=ID) | |
@dataclass | |
class Child: | |
parent_id: ID | |
parent = Parent() | |
child = Child(parent_id=parent.id) | |
print(child, parent) | |
parent.id.set(100) | |
print(child, parent) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment