diff options
author | Nao Pross <np@0hm.ch> | 2024-03-04 00:00:45 +0100 |
---|---|---|
committer | Nao Pross <np@0hm.ch> | 2024-03-04 00:00:57 +0100 |
commit | a3f00754fc0dce1b237aa99f1619b41fed69b3e7 (patch) | |
tree | 5898c4bd93f3d05ae16ea0bf2ff1e6c5181beb8e | |
parent | Reword docstrings (diff) | |
download | mdpoly-a3f00754fc0dce1b237aa99f1619b41fed69b3e7.tar.gz mdpoly-a3f00754fc0dce1b237aa99f1619b41fed69b3e7.zip |
Improve algebra.unary_operator decorator
Diffstat (limited to '')
-rw-r--r-- | mdpoly/algebra.py | 42 |
1 files 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 + + # ┏━┓┏━┓╻ ╻ ╻┏┓╻┏━┓┏┳┓╻┏━┓╻ ┏━┓╻ ┏━╸┏━╸┏┓ ┏━┓┏━┓ # ┣━┛┃ ┃┃ ┗┳┛┃┗┫┃ ┃┃┃┃┃┣━┫┃ ┣━┫┃ ┃╺┓┣╸ ┣┻┓┣┳┛┣━┫ # ╹ ┗━┛┗━╸ ╹ ╹ ╹┗━┛╹ ╹╹╹ ╹┗━╸ ╹ ╹┗━╸┗━┛┗━╸┗━┛╹┗╸╹ ╹ |