Rewrite compute and remove reference to computing in OPERATORS
This commit is contained in:
parent
832946ed49
commit
e9046c49ff
@ -12,6 +12,15 @@ Computing with MO
|
||||
|
||||
from ..operator import OPERATORS
|
||||
from .exceptions import ComputeError
|
||||
from .add import add
|
||||
from .minus import minus
|
||||
from .multiply import multiply
|
||||
|
||||
OPERATIONS = {
|
||||
"+": add,
|
||||
"-": minus,
|
||||
"*": multiply,
|
||||
}
|
||||
|
||||
def compute(node, left_v, right_v):
|
||||
"""
|
||||
@ -19,28 +28,24 @@ def compute(node, left_v, right_v):
|
||||
|
||||
:example:
|
||||
|
||||
>>> compute("+", 1, 2)
|
||||
3
|
||||
>>> compute("-", None, 2)
|
||||
-2
|
||||
>>> compute("-", 1, 2)
|
||||
>>> from ..MO.mo import MOnumber
|
||||
>>> compute("+", MOnumber(1), MOnumber(2))
|
||||
<MOnumber 3>
|
||||
>>> compute("-", None, MOnumber(2))
|
||||
<MOnumber - 2>
|
||||
>>> compute("*", MOnumber(1), MOnumber(2))
|
||||
<MOnumber 2>
|
||||
>>> compute("~", MOnumber(1), MOnumber(2))
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
mapytex.calculus.core.compute.exceptions.ComputeError: left_v need to be None for operator with arity 1
|
||||
mapytex.calculus.core.compute.exceptions.ComputeError: Unknown operation (~)
|
||||
"""
|
||||
op = OPERATORS[node]
|
||||
lv = left_v
|
||||
rv = right_v
|
||||
if op['arity'] == 1:
|
||||
if lv is None:
|
||||
return op["operate"](rv)()
|
||||
else:
|
||||
raise ComputeError("left_v need to be None for operator with arity 1")
|
||||
else:
|
||||
try:
|
||||
return op["operate"](lv)(rv)
|
||||
except NotImplemented:
|
||||
return op["roperate"](rv)(lv)
|
||||
try:
|
||||
operation = OPERATIONS[node]
|
||||
except KeyError:
|
||||
raise ComputeError(f"Unknown operation ({node})")
|
||||
|
||||
return operation(left_v, right_v)
|
||||
|
||||
|
||||
# -----------------------------
|
||||
|
@ -15,31 +15,22 @@ OPERATORS = {
|
||||
"+": {'repr': "+",
|
||||
'arity': 2,
|
||||
'precedence': 0,
|
||||
'operate': lambda x: x.__getattribute__("__add__"),
|
||||
'roperate': lambda x: x.__getattribute__("__radd__"),
|
||||
},
|
||||
"-": {'repr': "-",
|
||||
'arity': 1,
|
||||
'precedence': 1,
|
||||
'operate': lambda x: x.__getattribute__("__neg__"),
|
||||
},
|
||||
"*": {'repr': "*",
|
||||
'arity': 2,
|
||||
'precedence': 2,
|
||||
'operate': lambda x: x.__getattribute__("__mul__"),
|
||||
'roperate': lambda x: x.__getattribute__("__rmul__"),
|
||||
},
|
||||
"/": {'repr': "/",
|
||||
'arity': 2,
|
||||
'precedence': 3,
|
||||
'operate': lambda x: x.__getattribute__("__div__"),
|
||||
'roperate': lambda x: x.__getattribute__("__rdiv__"),
|
||||
},
|
||||
"^": {'repr': "^",
|
||||
'arity': 2,
|
||||
'precedence': 4,
|
||||
'operate': lambda x: x.__getattribute__("__pow__"),
|
||||
'roperate': lambda x: x.__getattribute__("__rpow__"),
|
||||
},
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user