Skip to content

gh-133244: TPen.pensize raises TurtleGraphicsError if called with a negative number #135268

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

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
5 changes: 5 additions & 0 deletions Doc/library/turtle.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1079,6 +1079,8 @@

:param width: a positive number

:raises TurtleGraphicsError: If *width* is less than zero.

Set the line thickness to *width* or return it. If resizemode is set to
"auto" and turtleshape is a polygon, that polygon is drawn with the same line
thickness. If no argument is given, the current pensize is returned.
Expand All @@ -1090,6 +1092,9 @@
1
>>> turtle.pensize(10) # from here on lines of width 10 are drawn

.. versionchanged:: next
Raise :exc:`TurtleGraphicsError` if *width* is less than zero.

Check warning on line 1096 in Doc/library/turtle.rst

View workflow job for this annotation

GitHub Actions / Docs / Docs

py:exc reference target not found: TurtleGraphicsError [ref.exc]


.. function:: pen(pen=None, **pendict)

Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_turtle.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,25 @@ def test_teleport(self):
tpen.teleport(-100, -100, fill_gap=fill_gap_value)
self.assertTrue(tpen.isdown())

def test_pensize_with_positive_numbers(self):
tpen = turtle.TPen()

tpen.pensize(42)
self.assertEqual(42, tpen.pensize())

def test_pensize_with_nonpositive_numbers(self):
tpen = turtle.TPen()

tpen.pensize(0)
self.assertEqual(0, tpen.pensize())

width = -1
msg = f"width argument must be a positive number, but got {width}."
with self.assertRaisesRegex(turtle.TurtleGraphicsError, re.escape(msg)):
tpen.pensize(width)

self.assertEqual(0, tpen.pensize())


class TestTurtleScreen(unittest.TestCase):
def test_save_raises_if_wrong_extension(self) -> None:
Expand Down
6 changes: 5 additions & 1 deletion Lib/turtle.py
Original file line number Diff line number Diff line change
Expand Up @@ -2141,7 +2141,11 @@ def pensize(self, width=None):
"""
if width is None:
return self._pensize
self.pen(pensize=width)
elif width < 0:
msg = f"width argument must be a positive number, but got {width}."
raise TurtleGraphicsError(msg)
else:
self.pen(pensize=width)


def penup(self):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:meth:`!turtle.TPen.pensize` raises an exception if called with a negative *width* argument.
Loading