Skip to content

Instantly share code, notes, and snippets.

@radix
Last active January 4, 2016 07:09
Show Gist options
  • Save radix/8586616 to your computer and use it in GitHub Desktop.
Save radix/8586616 to your computer and use it in GitHub Desktop.
Stupid Immutable Dict
def imdict(dct):
"""Construct an immutable dict, based on a normal one.
"""
# Warning: It's possible for others to get at these closed-over variables
# by inspecting frames, and then modifying them. Suggestions welcome (other
# than implementing a new hash table with tuples from scratch)
items = dct.items()
lookup = dict([(item[0], index) for index, item in enumerate(items)])
class ImmutableDict(tuple):
def __new__(klass, dct):
values = [x[1] for x in items]
return super(ImmutableDict, klass).__new__(klass, values)
def __getitem__(self, key):
field = lookup[key]
return super(ImmutableDict, self).__getitem__(field)
return ImmutableDict(dct)
if __name__ == '__main__':
d = imdict({"a": 1, "b": 2})
assert d['a'] == 1
assert d['b'] == 2
try:
d['b'] = 3
except TypeError:
print "good: can't set attributes"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment