98 lines
2.0 KiB
Python
98 lines
2.0 KiB
Python
"""
|
|
SMAVS Shared Kernel - Identifier
|
|
|
|
Defines the base Value Object used to uniquely identify every
|
|
domain element inside the framework.
|
|
|
|
All domain-specific identifiers inherit from this class.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from uuid import UUID, uuid4
|
|
|
|
__all__ = ["Identifier"]
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class Identifier:
|
|
"""
|
|
Base immutable identifier.
|
|
|
|
An Identifier represents the identity of a domain object.
|
|
|
|
Internally it stores a UUID while exposing a strongly typed
|
|
Value Object to the rest of the domain.
|
|
"""
|
|
|
|
value: UUID
|
|
|
|
@classmethod
|
|
def new(cls) -> Identifier:
|
|
"""
|
|
Create a new identifier.
|
|
|
|
Returns:
|
|
A newly generated identifier.
|
|
"""
|
|
return cls(uuid4())
|
|
|
|
@classmethod
|
|
def from_string(cls, value: str) -> Identifier:
|
|
"""
|
|
Create an identifier from its string representation.
|
|
|
|
Args:
|
|
value:
|
|
UUID string.
|
|
|
|
Returns:
|
|
The corresponding identifier.
|
|
|
|
Raises:
|
|
ValueError:
|
|
If the provided string is not a valid UUID.
|
|
"""
|
|
return cls(UUID(value))
|
|
|
|
@classmethod
|
|
def from_uuid(cls, value: UUID) -> Identifier:
|
|
"""
|
|
Create an identifier from an existing UUID.
|
|
|
|
Args:
|
|
value:
|
|
UUID instance.
|
|
|
|
Returns:
|
|
The corresponding identifier.
|
|
"""
|
|
return cls(value)
|
|
|
|
def __str__(self) -> str:
|
|
"""
|
|
Return the canonical string representation.
|
|
"""
|
|
return str(self.value)
|
|
|
|
def __repr__(self) -> str:
|
|
"""
|
|
Return the developer representation.
|
|
"""
|
|
return f"{self.__class__.__name__}('{self.value}')"
|
|
|
|
@property
|
|
def hex(self) -> str:
|
|
"""
|
|
Return the hexadecimal representation.
|
|
"""
|
|
return self.value.hex
|
|
|
|
@property
|
|
def urn(self) -> str:
|
|
"""
|
|
Return the UUID URN representation.
|
|
"""
|
|
return self.value.urn
|