From 465ffcbd4775458c7ed94bb173fab6eea12ee5e4 Mon Sep 17 00:00:00 2001 From: adityajai119 Date: Mon, 30 Nov 2026 19:59:06 +0530 Subject: [PATCH] Fix flyweight key collisions between distinct cards --- patterns/structural/flyweight.py | 6 +++--- tests/structural/test_flyweight.py | 8 ++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/patterns/structural/flyweight.py b/patterns/structural/flyweight.py index 148a5bc05..844117341 100644 --- a/patterns/structural/flyweight.py +++ b/patterns/structural/flyweight.py @@ -37,15 +37,15 @@ class Card: # Could be a simple dict. # With WeakValueDictionary garbage collection can reclaim the object # when there are no other references to it. - _pool: weakref.WeakValueDictionary[str, "Card"] = weakref.WeakValueDictionary() + _pool: weakref.WeakValueDictionary[tuple[str, str], "Card"] = weakref.WeakValueDictionary() def __new__(cls, value: str, suit: str) -> "Card": # If the object exists in the pool - just return it - obj = cls._pool.get(value + suit) + obj = cls._pool.get((value, suit)) # otherwise - create new one (and add it to the pool) if obj is None: obj = object.__new__(Card) - cls._pool[value + suit] = obj + cls._pool[(value, suit)] = obj # This row does the part we usually see in `__init__` obj.value, obj.suit = value, suit return obj diff --git a/tests/structural/test_flyweight.py b/tests/structural/test_flyweight.py index a200203f9..8a1e56a07 100644 --- a/tests/structural/test_flyweight.py +++ b/tests/structural/test_flyweight.py @@ -18,3 +18,11 @@ def test_card_attribute_persistence_and_pool_clear(): Card._pool.clear() c3 = Card("A", "s") assert not hasattr(c3, "temp") + + +def test_distinct_cards_with_concatenated_equal_keys(): + Card._pool.clear() + first = Card("1", "23") + second = Card("12", "3") + assert first is not second + assert (second.value, second.suit) == ("12", "3")