Skip to content

Instantly share code, notes, and snippets.

@poros
Created October 6, 2015 00:03
Show Gist options
  • Save poros/04a368f465e3c69d8d55 to your computer and use it in GitHub Desktop.
Save poros/04a368f465e3c69d8d55 to your computer and use it in GitHub Desktop.
Defaultdict with default custom class
from collection import defaultdict
class Number(object):
def __init__(self, N):
self.N = N
def __repr__(self):
return str(self.N)
d = defaultdict(Number)
d['foo']
# TypeError: __init__() takes exactly 2 arguments (1 given)
d = defaultdict(lambda: Number(10))
d['foo']
10
# OR
from functools.partial
d = defaultdict(partial(Number, 10))
d['foo']
10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment