design-patterns-python icon indicating copy to clipboard operation
design-patterns-python copied to clipboard

Fix unexpected behavior with mutable object as default param in Iterator Pattern

Open matheusfelipeog opened this issue 3 years ago • 0 comments

There is unexpected behavior for the iterator pattern when using some mutable object (list, dict...) as a default parameter, where the same mutable object is referenced in all the instantiated concrete objects.

Before:

>>> collection = WordsCollection()
>>> other_collection = WordsCollection()
>>>
>>> collection.add_item('First')
>>> collection.add_item('Second')
>>> collection.add_item('Third')
>>>
>>> other_collection._collection
['First', 'Second', 'Third']

Now:

>>> collection = WordsCollection()
>>> other_collection = WordsCollection()
>>>
>>> collection.add_item('First')
>>> collection.add_item('Second')
>>> collection.add_item('Third')
>>>
>>> other_collection._collection
[]

In this way, there is no interference with other objects, as all created collections have their own data structure.


more info:

  • https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments
  • https://web.archive.org/web/20200221224620id_/http://effbot.org/zone/default-values.htm

matheusfelipeog avatar Sep 03 '22 21:09 matheusfelipeog