Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions patterns/structural/flyweight.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions tests/structural/test_flyweight.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Loading