Skip to content

Commit 7857c4b

Browse files
authored
Merge pull request #3217 from thocevar/valuehash
[FIX] Variable: Prevent hashing of Values of DiscreteVariable.
2 parents 33d7012 + a2cb09f commit 7857c4b

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

Orange/data/variable.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,10 +207,15 @@ def __contains__(self, other):
207207
raise TypeError("invalid operation on Value()")
208208

209209
def __hash__(self):
210+
if self.variable.is_discrete:
211+
# It is not possible to hash the id and the domain value to the same number as required by __eq__.
212+
# hash(1) == hash(Value(DiscreteVariable("var", ["red", "green", "blue"]), 1)) == hash("green")
213+
# User should hash directly ids or domain values instead.
214+
raise TypeError("unhashable type - cannot hash values of discrete variables!")
210215
if self._value is None:
211216
return super().__hash__()
212217
else:
213-
return hash((super().__hash__(), self._value))
218+
return hash(self._value)
214219

215220
@property
216221
def value(self):

Orange/tests/test_value.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
import unittest
66
import numpy as np
77

8-
from Orange.data import Table, Domain, DiscreteVariable
8+
from Orange.data import Table, Domain, Value,\
9+
DiscreteVariable, ContinuousVariable, StringVariable, TimeVariable
910

1011

1112
class TestValue(unittest.TestCase):
@@ -50,3 +51,16 @@ def test_compare_string(self):
5051
zoo2 = zoo[1]['name'] # antelope
5152
self.assertTrue(zoo1 < zoo2)
5253
self.assertTrue(zoo1 >= "aardvark")
54+
55+
def test_hash(self):
56+
v = 1234.5
57+
val = Value(ContinuousVariable("var"), v)
58+
self.assertTrue(val == v and hash(val) == hash(v))
59+
v = "test"
60+
val = Value(StringVariable("var"), v)
61+
self.assertTrue(val == v and hash(val) == hash(v))
62+
v = 1234.5
63+
val = Value(TimeVariable("var"), v)
64+
self.assertTrue(val == v and hash(val) == hash(v))
65+
val = Value(DiscreteVariable("var", ["red", "green", "blue"]), 1)
66+
self.assertRaises(TypeError, hash, val)

0 commit comments

Comments
 (0)