Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert lists to tuples to make dict keys hashable, fixes #24 #25

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions tests/samples/unhashablelist.sample

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
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