2014-11-15 11:30:01 -07:00
|
|
|
# test builtin hash function
|
|
|
|
|
2015-01-28 17:44:11 -07:00
|
|
|
print(hash(False))
|
|
|
|
print(hash(True))
|
|
|
|
print({():1}) # hash tuple
|
2016-08-14 18:46:02 -06:00
|
|
|
print({(1,):1}) # hash non-empty tuple
|
2015-01-28 17:44:11 -07:00
|
|
|
print(hash in {hash:1}) # hash function
|
|
|
|
|
|
|
|
try:
|
|
|
|
hash([])
|
|
|
|
except TypeError:
|
|
|
|
print("TypeError")
|
|
|
|
|
2014-11-15 11:30:01 -07:00
|
|
|
class A:
|
|
|
|
def __hash__(self):
|
|
|
|
return 123
|
|
|
|
def __repr__(self):
|
|
|
|
return "a instance"
|
|
|
|
|
|
|
|
print(hash(A()))
|
|
|
|
print({A():1})
|
2015-05-04 13:41:32 -06:00
|
|
|
|
2015-05-11 06:25:19 -06:00
|
|
|
# all user-classes have default __hash__
|
2015-05-04 13:41:32 -06:00
|
|
|
class B:
|
|
|
|
pass
|
|
|
|
hash(B())
|
|
|
|
|
2015-05-11 06:25:19 -06:00
|
|
|
# if __eq__ is defined then default __hash__ is not used
|
2015-05-04 13:41:32 -06:00
|
|
|
class C:
|
|
|
|
def __eq__(self, another):
|
|
|
|
return True
|
|
|
|
try:
|
|
|
|
hash(C())
|
|
|
|
except TypeError:
|
|
|
|
print("TypeError")
|
2015-05-11 06:25:19 -06:00
|
|
|
|
|
|
|
# __hash__ must return an int
|
|
|
|
class D:
|
|
|
|
def __hash__(self):
|
|
|
|
return None
|
|
|
|
try:
|
|
|
|
hash(D())
|
|
|
|
except TypeError:
|
|
|
|
print("TypeError")
|
2015-05-12 16:08:18 -06:00
|
|
|
|
|
|
|
# __hash__ returning a bool should be converted to an int
|
|
|
|
class E:
|
|
|
|
def __hash__(self):
|
|
|
|
return True
|
|
|
|
print(hash(E()))
|