Skip to content

Instantly share code, notes, and snippets.

@Geson-anko
Created March 25, 2024 04:54
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 Geson-anko/98099bdfc5a2c203e27138b5137fa34b to your computer and use it in GitHub Desktop.
Save Geson-anko/98099bdfc5a2c203e27138b5137fa34b to your computer and use it in GitHub Desktop.
新しいインスタンスを生成可能なクラス。MixInとして使っても良い。
import copy
from typing import Any, Self
class Reconstructable:
_init_args: tuple[Any, ...]
_init_kwds: dict[str, Any]
@classmethod
def reconstructable_init(cls, *args: Any, **kwds: Any) -> Self:
instance = cls(*copy.deepcopy(args), **copy.deepcopy(kwds))
instance._init_args = args
instance._init_kwds = kwds
return instance
@property
def is_reconstructable(self) -> bool:
return hasattr(self, "_init_args") and hasattr(self, "_init_kwds")
def new(self) -> Self:
if self.is_reconstructable:
return self.__class__.reconstructable_init(*self._init_args, **self._init_kwds)
else:
raise RuntimeError(
"Can not create new instance! Did you forget to use `reconstructable_init`"
"instead of `__init___` when creating a instance?"
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment