Skip to content

Commit d00a9ee

Browse files
committed
adding immutabledict
1 parent 9d76768 commit d00a9ee

2 files changed

Lines changed: 46 additions & 1 deletion

File tree

wolframclient/deserializers/wxf/wxfconsumer.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from wolframclient.serializers.wxfencoder import constants
99
from wolframclient.serializers.wxfencoder.utils import array_to_list
1010
from wolframclient.utils.api import numpy
11+
from wolframclient.utils.datastructures import immutabledict
1112

1213
__all__ = ["WXFConsumer", "WXFConsumerNumpy"]
1314

@@ -112,7 +113,7 @@ def build_function(self, head, arg_list, **kwargs):
112113
"""
113114
return WLFunction(head, *arg_list)
114115

115-
def consume_association(self, current_token, tokens, dict_class=dict, **kwargs):
116+
def consume_association(self, current_token, tokens, dict_class=immutabledict, **kwargs):
116117
"""Consume a :class:`~wolframclient.deserializers.wxf.wxfparser.WXFToken` of type *association*.
117118
118119
By default, return a :class:`dict` made from the rules.

wolframclient/utils/datastructures.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,50 @@ def __repr__(self):
1010
return dict.__repr__(self)
1111

1212

13+
def _fail(self, *args, **opts):
14+
raise TypeError("{0} does not support item assignment".format(self.__class__.__name__))
15+
16+
17+
class immutabledict(dict):
18+
"""
19+
hashable dict implementation, suitable for use as a key into
20+
other dicts.
21+
22+
>>> h1 = immutabledict({"apples": 1, "bananas":2})
23+
>>> h2 = immutabledict({"bananas": 3, "mangoes": 5})
24+
>>> h1+h2
25+
immutabledict(apples=1, bananas=3, mangoes=5)
26+
>>> d1 = {}
27+
>>> d1[h1] = "salad"
28+
>>> d1[h1]
29+
'salad'
30+
>>> d1[h2]
31+
Traceback (most recent call last):
32+
...
33+
KeyError: immutabledict(bananas=3, mangoes=5)
34+
35+
based on answers from
36+
http://stackoverflow.com/questions/1151658/python-hashable-dicts
37+
38+
"""
39+
40+
def __hash__(self):
41+
return hash(tuple(self.items()))
42+
43+
__setitem__ = _fail
44+
__delitem__ = _fail
45+
clear = _fail
46+
pop = _fail
47+
popitem = _fail
48+
setdefault = _fail
49+
update = _fail
50+
51+
def __add__(self, right):
52+
result = hashdict(self)
53+
dict.update(result, right)
54+
return result
55+
56+
1357
class Settings(dict):
1458
"""
1559
Dictionary subclass enabling attribute lookup/assignment of keys/values.

0 commit comments

Comments
 (0)