0

If I first do

from collections import defaultdict

then doing

defaultdict(lambda: "Default value")[7]

yields 'Default value'. However, instead doing

defaultdict(default_factory=lambda: "Default value")[7]

results in

KeyError                                  Traceback (most recent call last)
Cell In [28], line 1
----> 1 defaultdict(default_factory=lambda: "Default value")[7]

but according to the defaultdict documentation, the first argument is default_factory, so the two statements should be equivalent. So why do they behave differently?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
HelloGoodbye
  • 3,624
  • 8
  • 42
  • 57
  • See also https://stackoverflow.com/questions/24735311/what-does-the-slash-mean-in-help-output – mkrieger1 Jan 22 '23 at 01:28
  • It's not entirely obvious from the documentation, but the `/` following the parameter indicates that all the preceding parameters are positional-only, disallowing keyword arguments from setting them. – chepner Jan 22 '23 at 01:33
  • 1
    The reason it doesn't accept it as a keyword argument is because it wishes to allow *arbitrary* keyword arguments to describe members of the dictionary. If you write `dict(default_factory=1)`, that creates `{'default_factory': 1}`. `defaultdict` does the same, but if it allowed passing the default factory by keyword, and you did `defaultdict(lambda: "default", default_factory=1)` to specifically create it with that key, it would see it as the same argument being passed twice. – ShadowRanger Jan 22 '23 at 01:39

0 Answers0