From a3f00754fc0dce1b237aa99f1619b41fed69b3e7 Mon Sep 17 00:00:00 2001 From: Nao Pross Date: Mon, 4 Mar 2024 00:00:45 +0100 Subject: Improve algebra.unary_operator decorator --- mdpoly/algebra.py | 42 +++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/mdpoly/algebra.py b/mdpoly/algebra.py index d44a528..78e4965 100644 --- a/mdpoly/algebra.py +++ b/mdpoly/algebra.py @@ -16,19 +16,6 @@ from abc import abstractmethod import operator -def unary_operator(cls: Expr) -> Expr: - """ Class decorator to modify constructor of unary operators. """ - __init_cls__ = cls.__init__ - @wraps(cls.__init__) - def __init_unary__(self, left, *args, **kwargs): - __init_cls__(self, *args, **kwargs) - self.left, self.right = left, Nothing - self.inner = left - - cls.__init__ = __init_unary__ - return cls - - T = TypeVar("T") @runtime_checkable @@ -140,6 +127,35 @@ def binary_operator(left_type: AlgebraicStructure, right_type: AlgebraicStructur return cls return decorator + +def unary_operator(inner_type: AlgebraicStructure): + """ Class decorator that adss constructor for unary operations of Expr + + This is the special case of the binary operator, where only *left* is used + (because it is assumed that the operator acts from the left. The field for + *right* contains a placeholder :py:class:`mdpoly.leaves.Nothing`, + furthermore a new field *inner* is added as alias to *left*. + + See also :py:fun:`mdpoly.algebra.binary_operator`. + """ + def decorator(cls: Expr) -> Expr: + """ Class decorator to modify constructor of unary operators. """ + init_cls = cls.__init__ + @wraps(cls.__init__) + def new_init_cls(self, left, *args, **kwargs): + init_cls(self, *args, **kwargs) + self.left, self.right = left, Nothing + + @property + def inner(self): + return self.left + + cls.__init__ = new_init_cls + cls.inner = inner + return cls + return decorator + + # ┏━┓┏━┓╻ ╻ ╻┏┓╻┏━┓┏┳┓╻┏━┓╻ ┏━┓╻ ┏━╸┏━╸┏┓ ┏━┓┏━┓ # ┣━┛┃ ┃┃ ┗┳┛┃┗┫┃ ┃┃┃┃┃┣━┫┃ ┣━┫┃ ┃╺┓┣╸ ┣┻┓┣┳┛┣━┫ # ╹ ┗━┛┗━╸ ╹ ╹ ╹┗━┛╹ ╹╹╹ ╹┗━╸ ╹ ╹┗━╸┗━┛┗━╸┗━┛╹┗╸╹ ╹ -- cgit v1.2.1