Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for the matmul (@) operator. #270

Merged
merged 1 commit into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ Changes
- Allow to use the package with Python 3.13 -- Caution: No security
audit has been done so far.

- Add support for the matmul (``@``) operator.


7.0 (2023-11-17)
----------------
Expand Down
4 changes: 2 additions & 2 deletions src/RestrictedPython/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -768,8 +768,8 @@ def visit_BitAnd(self, node):
return self.node_contents_visit(node)

def visit_MatMult(self, node):
"""Matrix multiplication (`@`) is currently not allowed."""
self.not_allowed(node)
"""Allow multiplication (`@`)."""
return self.node_contents_visit(node)

def visit_BoolOp(self, node):
"""Allow bool operator without restrictions."""
Expand Down
15 changes: 9 additions & 6 deletions tests/transformer/operators/test_arithmetic_operators.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from RestrictedPython import compile_restricted_eval
from tests.helper import restricted_eval


Expand Down Expand Up @@ -33,8 +32,12 @@ def test_FloorDiv():


def test_MatMult():
result = compile_restricted_eval('(8, 3, 5) @ (2, 7, 1)')
assert result.errors == (
'Line None: MatMult statements are not allowed.',
)
assert result.code is None
class Vector:
def __init__(self, values):
self.values = values

def __matmul__(self, other):
return sum(x * y for x, y in zip(self.values, other.values))

assert restricted_eval(
'Vector((8, 3, 5)) @ Vector((2, 7, 1))', {'Vector': Vector}) == 42
Loading