This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Using defaultdict as kwarg to function reuses same dictionary every function call
Type: behavior Stage: resolved
Components: Versions: Python 3.9
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: TenzinCHW, steven.daprano
Priority: normal Keywords:

Created on 2021-03-22 09:15 by TenzinCHW, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg389289 - (view) Author: Tenzin (TenzinCHW) Date: 2021-03-22 09:15
When using a `defaultdict` as a kwarg to a function that requires another argument, every call to the function uses the same dictionary instance instead of creating a new one.

```>>> from collections import defaultdict
>>> def meow(a, b=defaultdict(list)):
...     b[a].append('moo')
...     return b
... 
>>> c = meow('hi')
>>> c
defaultdict(<class 'list'>, {'hi': ['moo']})
>>> c = meow('bye')
>>> c
defaultdict(<class 'list'>, {'hi': ['moo'], 'bye': ['moo']})
>>> d = meow('hello')
>>> d
defaultdict(<class 'list'>, {'hi': ['moo'], 'bye': ['moo'], 'hello': ['moo']})```

Is this the correct behaviour? Occurred in 3.6.12, 3.7.9, 3.8.5, 3.8.6 and 3.9.0.
msg389291 - (view) Author: Steven D'Aprano (steven.daprano) * (Python committer) Date: 2021-03-22 09:56
This is normal, expected behaviour and has nothing to do with defaultdicts specifically. Any mutable object would behave the same way.

Function default parameters are evaluated only once, when the function is defined. They are not re-evaluated on each call.

The standard pattern used for re-evaluating the default is:

    def function(arg=None):
        if arg is None:
            arg = defaultdict(list)
        ...
History
Date User Action Args
2022-04-11 14:59:43adminsetgithub: 87755
2021-03-22 09:56:11steven.dapranosetstatus: open -> closed

nosy: + steven.daprano
messages: + msg389291

resolution: not a bug
stage: resolved
2021-03-22 09:15:29TenzinCHWcreate