This commit is contained in:
2026-01-10 09:57:52 -06:00
parent 38b6807e70
commit 377e481803
18 changed files with 332 additions and 184 deletions

View File

@@ -0,0 +1,87 @@
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import ClassVar, Self, override, final
#
# class String(Protocol):
# @override
# def __str__(self) -> str: ...
# def replace(self, string: str) -> str:
# return string.replace(str(self), str(self))
# @dataclass(frozen=True, slots=True)
# class RecordCls[T_New: str | Callable[[None],str]]:
# old: ClassVar[str]
# new: T_New
#
# def __call__(self, string: str) -> str:
# return string.replace(str(self.old), self.new if isinstance(self.new, str) else self.new())
@final
@dataclass(frozen=True, slots=True)
class ReplaceStatic:
val: 'str| ReplaceStatic'
fmt: str = field(init=False)
def __post_init__(self):
setter = super(ReplaceStatic, self).__setattr__
setter('fmt', f"${{_{self.val.upper()}}}")
def __call__(self, string: str) -> str:
return string.replace(
self.fmt,
str(self)
)
def __str__(self) -> str:
return self.val if isinstance(self.val, str) else self.val.fmt
@dataclass(frozen=True, slots=True)
class ReplaceDynamic:
src: ReplaceStatic
dest: str | Callable[[], str]
def __call__(self, string: str) -> str:
return string.replace(
self.src,
str(self),
)
@override
def __str__(self) -> str:
return self.dest if isinstance(self.dest, str) else self.dest()
#
# @staticmethod
# def get_format(val: str) -> str:
# return f"${{_{val.upper()}}}"
@classmethod
def auto_format(cls, src: str, dest: str | Callable[[], str]) -> Self:
return cls(ReplaceStatic(src), dest)
@classmethod
def from_str(cls, string: str) -> Self:
return cls.auto_format(string, string)
# @property
# def stage_two(self) -> 'Record':
# return Record.from_str(self.dest if isinstance(self.dest, str) else self.dest())
@dataclass(frozen=True, slots=True)
class RecordCls(ReplaceDynamic):
# val: ClassVar[str]# = 'org'
rep: ClassVar[ReplaceStatic] # = Record.get_format(val)
@override
@classmethod
def from_str(cls, string: str) -> Self:
return cls(cls.rep, string)
@classmethod
def two_stage(cls, dest: str) -> tuple[Self, Self]:
dest_var = ReplaceStatic(dest)
return cls(cls.rep, dest_var.fmt), cls(dest_var, dest)