10

I'd like to generate a defaultdict that contains a deque. For example:

d = defaultdict(deque)

The above work fine, but I'd like to make the deque a fixed length by passing in an argument:

d = defaultdict(deque(maxlen=10))

How can I pass arguments such as this to defaultdict?

turtle
  • 7,533
  • 18
  • 68
  • 97

1 Answers1

21

Use a partially applied function:

from functools import partial
defaultdict(partial(deque, maxlen=10))

Demo:

>>> deque10 = partial(deque, maxlen=10)
>>> deque10()
deque([], maxlen=10)
>>> deque10(range(20))
deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19], maxlen=10)

See functools.partial docs for details.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 4
    Great thanks. I see `defaultdict(lambda: deque(maxlen=10))` also would work. – turtle Oct 09 '13 at 17:36
  • @turtle: yes, but it's not as pretty, IMHO. `partial` is considered more Pythonic than `lambda`. – Fred Foo Oct 09 '13 at 17:36
  • 1
    `lambda` is certainly worth mentioning; but see this question and the answer by [Alex Martelli](http://stackoverflow.com/questions/3252228/python-why-is-functools-partial-necessary) for a wonderful explanation of the benefits of `partial` over `lambda`. – senderle Oct 09 '13 at 17:37
  • thanks, this is exactly the use case I was looking for. `partial` can be useful in many cases where you need pass uncalled function along with some arguments for it. – Nikita Tonkoskur Dec 24 '20 at 01:01