Debian Codegraph @

rpython/tool/uid.py

raw symbols SCIP
1 import math
2 import struct
3
4 HUGEVAL_BYTES = struct.calcsize('P')
5 HUGEVAL = 256 ** HUGEVAL_BYTES
6
7
8 def fixid(result):
9 if result < 0:
10 result += HUGEVAL
11 return result
12
13 uid = id # guaranteed to be positive from CPython 2.5 onwards
14
15
16 class Hashable(object):
17 """
18 A Hashable instance encapsulates any object, but is always usable as a
19 key in dictionaries. This is based on id() for mutable objects and on
20 real hash/compare for immutable ones.
21 """
22 __slots__ = ["key", "value"]
23
24 def __init__(self, value):
25 self.value = value # a concrete value
26 # try to be smart about constant mutable or immutable values
27 key = type(self.value), self.value # to avoid confusing e.g. 0 and 0.0
28 #
29 # we also have to avoid confusing 0.0 and -0.0 (needed e.g. for
30 # translating the cmath module)
31 if key[0] is float and not self.value:
32 if math.copysign(1., self.value) == -1.: # -0.0
33 key = (float, "-0.0")
34 #
35 try:
36 hash(key)
37 except TypeError:
38 key = id(self.value)
39 self.key = key
40
41 def __eq__(self, other):
42 return self.__class__ is other.__class__ and self.key == other.key
43
44 def __ne__(self, other):
45 return not (self == other)
46
47 def __hash__(self):
48 return hash(self.key)
49
50 def __repr__(self):
51 return '(%s)' % (self,)
52
53 def __str__(self):
54 # try to limit the size of the repr to make it more readable
55 r = repr(self.value)
56 if (r.startswith('<') and r.endswith('>') and
57 hasattr(self.value, '__name__')):
58 r = '%s %s' % (type(self.value).__name__, self.value.__name__)
59 elif len(r) > 60 or (len(r) > 30 and type(self.value) is not str):
60 r = r[:22] + '...' + r[-7:]
61 return r