Skip to content

Commit

Permalink
Convert lists to tuples to make dict keys hashable, fixes #24
Browse files Browse the repository at this point in the history
  • Loading branch information
yuvadm committed Apr 28, 2021
1 parent d71ef41 commit 39ffaef
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions tests/samples/unhashablelist.sample

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from viewstate.utils import list_to_tuple

def test_list_to_tuple():
assert list_to_tuple([1,2,3]) == (1,2,3)
assert list_to_tuple((9,8,7)) == (9,8,7)
assert list_to_tuple((None,[2,3,None])) == (None,(2,3, None))
assert list_to_tuple(("abc",[2,[3],(9,8,True,False)])) == ("abc",(2,(3,),(9,8,True,False)))
assert list_to_tuple("abc") == "abc"
7 changes: 6 additions & 1 deletion viewstate/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from .colors import COLORS
from .exceptions import ViewStateException
from .utils import list_to_tuple


class ParserMeta(type):
Expand Down Expand Up @@ -250,7 +251,11 @@ def parse(b):
for _ in range(n):
k, remain = Parser.parse(remain)
v, remain = Parser.parse(remain)
d[k] = v
try:
d[k] = v
except TypeError:
# make the key hashable by deep converting lists to tuples
d[list_to_tuple(k)] = v
return d, remain


Expand Down
5 changes: 5 additions & 0 deletions viewstate/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def list_to_tuple(lst):
if isinstance(lst, list) or isinstance(lst, tuple):
return tuple([list_to_tuple(e) for e in lst])
else:
return lst

0 comments on commit 39ffaef

Please sign in to comment.