|
1 | 1 | ''' Mutable Primitives ''' |
2 | | -#from types import FunctionType |
| 2 | +from types import FunctionType |
| 3 | +import sys |
3 | 4 |
|
4 | 5 |
|
5 | 6 | EQUALITY_FUNCTIONS = [ |
6 | 7 | '__eq__', |
7 | 8 | '__ne__', |
8 | 9 | ] |
9 | 10 |
|
| 11 | +MATH_FUNCTIONS = [ |
| 12 | + ('add', '+'), |
| 13 | + ('sub', '-'), |
| 14 | + ('mul', '*'), |
| 15 | + # Division is handled differently in python2 and python3 |
| 16 | + ] |
| 17 | +if sys.version_info[0] < 3: |
| 18 | + MATH_FUNCTIONS.append(('div', '/')) |
| 19 | +else: |
| 20 | + MATH_FUNCTIONS.extend([ |
| 21 | + ('floordiv', '//'), |
| 22 | + ('truediv', '/'), |
| 23 | + ]) |
| 24 | + |
| 25 | + |
| 26 | +FORMATS = { |
| 27 | + '': 'return self.val {} other', |
| 28 | + 'r': 'return other {} self.val', |
| 29 | + 'i': 'self.val {}= other', |
| 30 | + } |
10 | 31 |
|
11 | 32 |
|
12 | 33 | class Mutable(object): # pylint: disable=useless-object-inheritance |
@@ -35,15 +56,21 @@ def __repr__(self): |
35 | 56 | return '<{}>'.format(self) |
36 | 57 |
|
37 | 58 |
|
38 | | - |
39 | 59 | class Bool(Mutable): |
40 | 60 | ''' Mutable version of float ''' |
41 | 61 |
|
42 | 62 |
|
43 | | - |
44 | 63 | class MutableNumeric(Mutable): |
45 | 64 | ''' Base class for mutable numeric primitives ''' |
46 | 65 |
|
| 66 | + for fmt, basecode in FORMATS.items(): |
| 67 | + for (basename, op) in MATH_FUNCTIONS: |
| 68 | + name = '__{}{}__'.format(fmt, basename) |
| 69 | + code = 'def {}(self, other): {}'.format(name, basecode.format(op)) |
| 70 | + code = compile(code, "<string>", "exec") |
| 71 | + locals()[name] = FunctionType(code.co_consts[0], globals(), name) |
| 72 | + del code, name, op |
| 73 | + |
47 | 74 |
|
48 | 75 | class Int(MutableNumeric): |
49 | 76 | ''' Mutable version of int ''' |
|
0 commit comments