Skip to content

Commit 0436719

Browse files
committed
Add radd, rsub, and rmul to PVector so expressions like (x,y) - PVector(...) and 2 * PVector(...) work without raising TypeError.
Replace the generic iter check in rmul with an explicit isinstance(..., (tuple, list)) guard so the type checker no longer warns about calling list() on non-iterables. Improves learner ergonomics and removes a linter/type-checker complaint.
1 parent 49b6350 commit 0436719

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

src/pycreative/vector.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,31 @@ def __truediv__(self, scalar: float) -> "PVector":
147147
return self.copy()
148148
return PVector(self.x / s, self.y / s)
149149

150+
# Right-side operator overloads so Python will dispatch here when the
151+
# left operand doesn't know how to handle an operation (e.g., a tuple).
152+
# This makes expressions like (x,y) - PVector(...) or 2 * PVector(...) work
153+
# and prevents confusing TypeErrors for learners.
154+
def __radd__(self, other) -> "PVector":
155+
ox, oy = (other.x, other.y) if isinstance(other, PVector) else (float(other[0]), float(other[1]))
156+
return PVector(ox + self.x, oy + self.y)
157+
158+
def __rsub__(self, other) -> "PVector":
159+
ox, oy = (other.x, other.y) if isinstance(other, PVector) else (float(other[0]), float(other[1]))
160+
return PVector(ox - self.x, oy - self.y)
161+
162+
def __rmul__(self, scalar: float) -> "PVector":
163+
# support scalar * PVector
164+
try:
165+
s = float(scalar)
166+
except Exception:
167+
# if a 2-length iterable was provided, fall back to elementwise
168+
if isinstance(scalar, (tuple, list)):
169+
vals = list(scalar)
170+
if len(vals) >= 2:
171+
return PVector(float(vals[0]) * self.x, float(vals[1]) * self.y)
172+
raise TypeError("Unsupported operand type(s) for *: '{}' and 'PVector'".format(type(scalar).__name__))
173+
return PVector(self.x * s, self.y * s)
174+
150175
def __repr__(self) -> str: # pragma: no cover - trivial
151176
return f"PVector({self.x!r}, {self.y!r})"
152177

0 commit comments

Comments
 (0)