Created
April 5, 2012 21:49
-
-
Save Xion/2314456 to your computer and use it in GitHub Desktop.
dict with "missing" values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import collections | |
missing = object() | |
class MissingDict(dict): | |
"""Dictionary that supports a special 'missing' value. | |
Assigning a missing value to key will remove the key from dictionary. | |
Initializing a key with missing value will result in key not being | |
added to dictionary at all. | |
Rationale is to eliminate 'ifs' which are sometimes needed when creating | |
dictionaries e.g. when sometimes we want default value for keyword argument. | |
Example: | |
>>> MissingDict({ | |
'zero': 0 or missing, | |
'one': 1, | |
}) | |
{'one': 1} | |
""" | |
def __init__(self, arg=None, **kwargs): | |
if arg is None: | |
kwargs = dict((k, v) for k, v in kwargs.iteritems() | |
if v is not missing) | |
dict.__init__(self, **kwargs) | |
else: | |
items = (((k, arg[k]) for k in arg) | |
if isinstance(arg, collections.Mapping) else arg) | |
filtered_items = ((k, v) for k, v in items | |
if v is not missing) | |
dict.__init__(self, filtered_items) | |
def __setitem__(self, key, obj): | |
if obj is missing: | |
del self[key] | |
else: | |
dict.__setitem__(self, key, obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment