Is there any way I can make a collections.defaultdict return a default constructed object when I set it…
foo = defaultdict(list)
foo[3].append('dsafdasf')
… but not when I try to access it?
try:
for word in foo[None]:
print(word)
except KeyError:
pass
I think that what you’re looking for is something like this:
That is, instead of using
collections.defaultdict, you could use a regular dictionary and usesetdefaultmethod when you need to assign a default and item access when you need an exception to be raised for missing keys.