2017-03-23 | Paul Boddie | file changeset files shortlog | Represent integers as __attr values with bit 0 set. Since pointers must be aligned (to four-byte boundaries on many modern systems, maybe two-byte boundaries on older or embedded systems, eight-byte boundaries on some 64-bit systems), any value with bit 0 set will not be referencing an object. This avoids allocating objects for integers and instead just allows them to be passed around. Bit 0 needs to be tested when attributes are accessed, and for integers, a common instance is employed to provide any instance attributes, an instance table reference and a reference to the integer class. | integers-as-tagged-attrs |
paul@364 | 1 | class A: |
paul@364 | 2 | def __init__(self, x): |
paul@364 | 3 | self.x = x |
paul@364 | 4 | def __sub__(self, other): |
paul@364 | 5 | return self.x - other.x |
paul@364 | 6 | |
paul@364 | 7 | class B: |
paul@364 | 8 | def __init__(self, x): |
paul@364 | 9 | self.x = x |
paul@364 | 10 | def __rsub__(self, other): |
paul@364 | 11 | return other.x - self.x |
paul@364 | 12 | |
paul@364 | 13 | class C: |
paul@364 | 14 | def __init__(self, x): |
paul@364 | 15 | self.x = x |
paul@364 | 16 | |
paul@364 | 17 | a = A(10) |
paul@364 | 18 | b = B(5) |
paul@364 | 19 | c = C(3) |
paul@364 | 20 | |
paul@364 | 21 | print a - b # 5 |
paul@364 | 22 | print c - b # -2 |
paul@364 | 23 | print a - c # 7 |
paul@364 | 24 | |
paul@364 | 25 | try: |
paul@364 | 26 | print b - c # should raise an exception |
paul@364 | 27 | except TypeError: |
paul@364 | 28 | print "b - c: b and c do not respectively support the __sub__ and __rsub__ operations" |