Skip to content

Instantly share code, notes, and snippets.

@merwok
Created April 24, 2014 20:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save merwok/11268759 to your computer and use it in GitHub Desktop.
Save merwok/11268759 to your computer and use it in GitHub Desktop.
import collections
class OrderedDefaultDict(collections.OrderedDict, collections.defaultdict):
pass
odd = OrderedDefaultDict()
odd.default_factory = list
odd['a'].append(True)
odd['b'].append(False)
odd['c'].append(False)
print(odd.items())
print(odd['d'])
@merwok
Copy link
Author

merwok commented Apr 24, 2014

If I make defaultdict the first base, then the setitems will fail because the dict has no __root (Python 2) or __map (3) attribute. This is certainly due to defaultdict not calling super(...).__init__. This can be worked around by defining OrderedDefaultDict.__init__(default_factory, items) and calling the superclasses’ __init__ methods explicitly.

If OrderedDict is the first base, then the signature of __init__ has no argument for default_factory, so I had to set it manually after creating my instance.

@merwok
Copy link
Author

merwok commented Apr 24, 2014

You could also only subclass OrderedDict and define a __missing__ method to to the same thing as default_factory in defaultdict.

FTR collections.Counter can also help depending on your need, and it combines well with collections.OrderedDict: http://rhettinger.wordpress.com/2011/05/26/super-considered-super/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment