From 7a353f7776ad29ad5dce1953c61f841f7c3e6427 Mon Sep 17 00:00:00 2001 From: Nick Johnson <24689722+ntjohnson1@users.noreply.github.com> Date: Fri, 14 Nov 2025 09:56:51 -0500 Subject: [PATCH] Add __radd__ for sptensor --- pyttb/sptensor.py | 23 +++++++++++++++++++++++ tests/test_sptensor.py | 8 ++++++++ 2 files changed, 31 insertions(+) diff --git a/pyttb/sptensor.py b/pyttb/sptensor.py index d1c7574e..3602c23b 100644 --- a/pyttb/sptensor.py +++ b/pyttb/sptensor.py @@ -2901,6 +2901,29 @@ def __add__(self, other): # Otherwise return negated sub return self.__sub__(-other) + def __radd__(self, other): + """ + Right binary addition operator (+). + + Parameters + ---------- + other: + Object to add to the sparse tensor. + + Examples + -------- + Add a scalar value, returning a dense tensor: + + >>> S = ttb.sptensor(shape=(2, 2)) + >>> S[1, 1] = 1.0 + >>> 1 + S + tensor of shape (2, 2) with order F + data[:, :] = + [[1. 1.] + [1. 2.]] + """ + return self.__add__(other) + def __pos__(self): """ Unary plus operator (+). diff --git a/tests/test_sptensor.py b/tests/test_sptensor.py index 3d7eeea7..35d6493e 100644 --- a/tests/test_sptensor.py +++ b/tests/test_sptensor.py @@ -910,6 +910,14 @@ def test_sptensor__add__(sample_sptensor): assert np.array_equal(subSptensor.data, sptensorInstance.to_tensor().data) +def test_sptensor__radd__(sample_sptensor): + (data, sptensorInstance) = sample_sptensor + + # scalar + Sptensor + subSptensor = 0 + sptensorInstance + assert np.array_equal(subSptensor.data, sptensorInstance.to_tensor().data) + + def test_sptensor_isequal(sample_sptensor): (data, sptensorInstance) = sample_sptensor