I've been reading into how super()
works. I came across this recipe that demonstrates how to create an Ordered Counter:
from collections import Counter, OrderedDict
class OrderedCounter(Counter, OrderedDict):
'Counter that remembers the order elements are first seen'
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__,
OrderedDict(self))
def __reduce__(self):
return self.__class__, (OrderedDict(self),)
For example:
oc = OrderedCounter('adddddbracadabra')
print(oc)
OrderedCounter(OrderedDict([('a', 5), ('d', 6), ('b', 2), ('r', 2), ('c', 1)]))
Is someone able to explain how this magically works?
This also appears in the Python documentation.
dict
methodsCounter
actually overrides/customizes. I can't figure out exactly which those would be, but I suspectCounter
leaves__setitem__
and__iter__
untouched, so your new class gets those fromOrderedDict
and that's enough to give you the ordered behaviour. – Xantho__init__
method in the python docs, but no__init__
method in Raymond Hettinger's article. From my testing it works without the__init__
. – Delusion