[issue37033] Dictionary defaults .get(), .pop(), .setdefault()

Rémi Lapeyre report at bugs.python.org
Fri May 24 05:45:20 EDT 2019


Rémi Lapeyre <remi.lapeyre at henki.fr> added the comment:

Hi @vykouk, Python evaluates arguments before calling functions so

>>> dicti.get(key, dflt(key))

is equivalent to:

>>> arg = dflt(key)
>>> dicti.get(key, arg)

Notive how dflt() is called before .get()

This is how all functions work in Python, not just dict methods.

You can change your code like so to make it work:

>>> if key in dicti:
>>>     x = dicti[key]
>>> else:
>>>     x = dflt(key)

or use defaultdict instead of setdefault which will take a callable to generate the default value.

I don't think there is a bug and we can close this issue.
Have a nice day.

----------
nosy: +remi.lapeyre

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


More information about the Python-bugs-list mailing list