2

I am trying to use defaultdict to store several lambdas that take one param, but to respond with a default lambda with the key is missing. I get an error when trying to use the default:

d = defaultdict(lambda str: str)
d['a'] = lambda str: f"aaa{str}"

d['a']('hello')
>>> 'aaahello'
d['b']('hello')
>>> <lambda>() missing 1 required positional argument: 'str'
Josh Diehl
  • 2,913
  • 2
  • 31
  • 43
  • 7
    The parameter to `defaultdict()` isn't the default value, it's a callable object (that will receive no parameters) that must return the default value. (If it didn't work this way, you couldn't create a defaultdict with a mutable default value such as a list.) Try `defaultdict(lambda: (lambda str: str))` - except that you shouldn't be using the built-in name `str` here, that's just going to cause confusion. – jasonharper Aug 30 '19 at 03:44
  • Possibly a helpful thread for your request: https://stackoverflow.com/questions/8419401/python-defaultdict-and-lambda – DocDriven Aug 30 '19 at 09:42
  • @jasonharper that makes sense and fixed it. You should submit as an answer. BTW not sure what you mean by str, are you referring to the str() function? – Josh Diehl Aug 30 '19 at 23:18

1 Answers1

1

It seems that your default lamba is intended to just bounce the called string back to the callee. As jasonharper mentioned, defaultdict only takes a callable function with no parameters, but using str as the name of the argument to lambda shadows the built-in str() function.

I suggest using defaultdict(lambda : str) because this lambda doesn't need any arguments. This is what it would look like:

d = defaultdict(lambda : str)
d['b']('hello')
>>> 'hello'

Zenul_Abidin
  • 573
  • 8
  • 23