Skip to content

Commit

Permalink
util: Add DefaultDict class
Browse files Browse the repository at this point in the history
This is a subclass of defaultdict which passes the missing key to the
factory function.
  • Loading branch information
MurphyMc committed Sep 15, 2013
1 parent dbd7c23 commit 22dd49c
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion pox/lib/util.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2011,2012 James McCauley
# Copyright 2011,2012,2013 James McCauley
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -148,6 +148,21 @@ def __delitem__ (self, k):
dict.__delitem__(self, k)


class DefaultDict (collections.defaultdict):
"""
A dictionary that can create missing values
This is similar to (and a subclass of) collections.defaultdict. However, it
calls the default factory passing it the missing key.
"""
#TODO: Make key-passing a constructor option so that this can serve as a
# complete defaultdict replacement.
def __missing__ (self, key):
v = self.default_factory(key)
self[key] = v
return v


def set_extend (l, index, item, emptyValue = None):
"""
Sets l[index] = item, padding l if needed
Expand Down

0 comments on commit 22dd49c

Please sign in to comment.