[issue43589] Using defaultdict as kwarg to function reuses same dictionary every function call

Steven D'Aprano report at bugs.python.org
Mon Mar 22 05:56:12 EDT 2021


Steven D'Aprano <steve+python at pearwood.info> added the comment:

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)
        ...

----------
nosy: +steven.daprano
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43589>
_______________________________________


More information about the Python-bugs-list mailing list