Passing a parameter to objects created by defaultdict

defaultdict, python

Solution

`defaultdict` takes any callable, so you can create a new function that doesn't take a parameter and returns an object instantiated with the parameter you want.

d = defaultdict(lambda: myobj(param1))

Another option is to use functools.partial, which creates a function with one (or more) of the parameters predefined:

import functools
d = defaultdict(functools.partial(myobj, param1))

Problem

I want to have a default dict that includes a parameter when it constructs a new object. Is this possible, is there a better way to do it? ``` defaultdict(myobj, param1) ``` then myobj: ``` class myobj(object): def __init__(self, param1): self.param1 = param1 ```

Original source