Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with generating a defaultdict with a deque

Tags:

python

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?

like image 934
turtle Avatar asked Oct 09 '13 17:10

turtle


1 Answers

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.

like image 184
Fred Foo Avatar answered Oct 29 '22 15:10

Fred Foo