Fix flyweight_with_metaclass sharing instances for different arguments - #495
Open
Darkslayer3324j wants to merge 1 commit into
Open
Darkslayer3324j wants to merge 1 commit into
Darkslayer3324j wants to merge 1 commit into
Conversation
The pool key concatenated str(arg) with no separator, so Card2('1', '0') and
Card2('10') (or Card2(1) and Card2('1')) got the same key and the second call
returned the first call's instance. Use repr of the class name, args and
sorted kwargs instead, which also makes the key independent of kwarg order.
Add tests, since the module had none.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
FlyweightMeta._serialize_paramsbuilds the pool key with"".join(map(str, args)) + str(kwargs) + cls.__name__. There is no separator and the type of each argument is lost, so different calls collide and the second one silently gets the first one's instance:The reverse also happens:
Card2(a=1, b=2)andCard2(b=2, a=1)are not shared, becausestr(kwargs)depends on insertion order.Fix
Use
repr((cls.__name__, args, sorted(kwargs.items())))as the key. It keeps argument boundaries and types, and is independent of keyword order. The key is still a string, so nothing else about the pool changes (the__main__demo still passes).Tests
patterns/structural/flyweight_with_metaclass.pyhad no tests (42% covered). I addedtests/structural/test_flyweight_with_metaclass.pywith cases for sharing, non-sharing, argument boundaries, argument types and kwarg order. Three of the five fail onmasterand all pass with the change. The repo's lint steps (flake8,isort,black --check,mypy,codespell) are clean andpytest tests patternspasses (136 passed).Written with AI assistance (Claude Code); I reproduced the collisions above and ran the checks.