20241118
from [2024年の日記]20241118[20241117][20241119][iigau式リッピングパイプライン]
class CachedTuple(tuple):
_cache = {}
def __new__(cls, value):
if not isinstance(value, tuple):
raise TypeError("CachedTuple にはタプルのみ渡してください")
try:
h = hash(value)
except TypeError:
raise TypeError("キャッシュするにはハッシュ可能なオブジェクトが必要です")
if h in cls._cache:
return cls._cache[h]
instance = super().__new__(cls, value)
cls._cache[h] = instance
return instance
# 使用例
a = CachedTuple(("Taro", 22))
b = CachedTuple(("Taro", 22))
c = CachedTuple(("Hanako", 20))
print(a is b) # 出力: True
print(a is c) # 出力: False
# エラーチェック
try:
d = CachedTuple(["Taro", 22]) # リストはハッシュ不可能
except TypeError as e:
print(e) # 出力: キャッシュするにはハッシュ可能なオブジェクトが必要です