-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathEqualsOrHash.qhelp
More file actions
44 lines (32 loc) · 1.55 KB
/
EqualsOrHash.qhelp
File metadata and controls
44 lines (32 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>A hashable class has an <code>__eq__</code> method, and a <code>__hash__</code> method that agrees with equality.
When a hash method is defined, an equality method should also be defined; otherwise object identity is used for equality comparisons
which may not be intended.
</p>
<p>Note that defining an <code>__eq__</code> method without defining a <code>__hash__</code> method automatically makes the class unhashable in Python 3.
(even if a superclass defines a hash method).</p>
</overview>
<recommendation>
<p>
If a <code>__hash__</code> method is defined, ensure a compatible <code>__eq__</code> method is also defined.
</p>
<p>
To explicitly declare a class as unhashable, set <code>__hash__ = None</code>, rather than defining a <code>__hash__</code> method that always
raises an exception. Otherwise, the class would be incorrectly identified as hashable by an <code>isinstance(obj, collections.abc.Hashable)</code> call.
</p>
</recommendation>
<example>
<p>In the following example, the <code>A</code> class defines an hash method but
no equality method. Equality will be determined by object identity, which may not be the expected behaviour.
</p>
<sample src="examples/EqualsOrHash.py" />
</example>
<references>
<li>Python Language Reference: <a href="http://docs.python.org/reference/datamodel.html#object.__hash__">object.__hash__</a>.</li>
<li>Python Glossary: <a href="http://docs.python.org/3/glossary.html#term-hashable">hashable</a>.</li>
</references>
</qhelp>