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

gh-126349: Add context managers to turtle for fill, poly and no_animation #126350

Merged
merged 30 commits into from
Jan 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
3379b3d
Add context managers for turtle.fill and turtle.poly
yngvem Oct 6, 2024
879d886
Add documentation
MarieRoald Oct 20, 2024
54f709c
Add context manager to turtle.TurtleScreen for disabling auto-update
MarieRoald Oct 27, 2024
437c8ce
Forward functions correctly
yngvem Oct 27, 2024
d11d8f9
Add documentation
yngvem Oct 27, 2024
1f04ee4
📜🤖 Added by blurb_it.
blurb-it[bot] Nov 3, 2024
3947de1
Fix typo in docs
MarieRoald Nov 3, 2024
5ee489b
Apply suggestions from code review
MarieRoald Nov 8, 2024
28a5ac6
Address review comments
MarieRoald Nov 8, 2024
6621bd3
Apply suggestions from code review
MarieRoald Nov 8, 2024
2f5c488
Address review comments
MarieRoald Nov 8, 2024
302a1ed
Apply suggestions from code review
MarieRoald Nov 9, 2024
ad779d5
Use setUp for unit tests
yngvem Nov 9, 2024
fd89c95
Address review comments
yngvem Nov 9, 2024
fe39751
Add missing blank line
MarieRoald Nov 9, 2024
0a5e250
Update Lib/turtle.py
MarieRoald Nov 9, 2024
6d381ec
Apply suggestions from code review
MarieRoald Nov 14, 2024
42d678d
Update Lib/turtle.py
MarieRoald Nov 14, 2024
7928306
Address reviewer comments
MarieRoald Nov 14, 2024
815a8a3
Update Lib/test/test_turtle.py
MarieRoald Dec 18, 2024
fc01695
Merge branch 'main' into fix-issue-126349
hugovk Dec 29, 2024
8487336
Re-sort
hugovk Dec 29, 2024
401c07f
Merge branch 'main' into fix-issue-126349
erlend-aasland Dec 30, 2024
3f2b4ef
Pull in main and resolve conflicts
erlend-aasland Dec 30, 2024
0c2fca0
Remove unneeded stylistic change; remove unprintable char from NEWS e…
erlend-aasland Dec 30, 2024
6115eef
Change assert to self.assertEqual
MarieRoald Jan 5, 2025
11d9bc3
Change assert to self.assertEqual
MarieRoald Jan 18, 2025
061fe2a
Improve usage of unittest.mock.patch
MarieRoald Jan 18, 2025
32bbf68
Merge branch 'main' into fix-issue-126349
MarieRoald Jan 18, 2025
b2ab84b
Merge branch 'main' into fix-issue-126349
MarieRoald Jan 18, 2025
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
85 changes: 85 additions & 0 deletions Doc/library/turtle.rst
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,31 @@ useful when working with learners for whom typing is not a skill.
use turtle graphics with a learner.


Automatically begin and end filling
-----------------------------------

Starting with Python 3.14, you can use the :func:`fill` :term:`context manager`
instead of :func:`begin_fill` and :func:`end_fill` to automatically begin and
end fill. Here is an example::

with fill():
for i in range(4):
forward(100)
right(90)

forward(200)

The code above is equivalent to::

begin_fill()
picnixz marked this conversation as resolved.
Show resolved Hide resolved
for i in range(4):
forward(100)
right(90)
end_fill()

forward(200)


Use the ``turtle`` module namespace
-----------------------------------

Expand Down Expand Up @@ -351,6 +376,7 @@ Pen control

Filling
| :func:`filling`
| :func:`fill`
| :func:`begin_fill`
| :func:`end_fill`

Expand Down Expand Up @@ -381,6 +407,7 @@ Using events
| :func:`ondrag`

Special Turtle methods
| :func:`poly`
| :func:`begin_poly`
| :func:`end_poly`
| :func:`get_poly`
Expand All @@ -403,6 +430,7 @@ Window control
| :func:`setworldcoordinates`

Animation control
| :func:`no_animation`
| :func:`delay`
| :func:`tracer`
| :func:`update`
Expand Down Expand Up @@ -1275,6 +1303,29 @@ Filling
... else:
... turtle.pensize(3)

.. function:: fill()
hugovk marked this conversation as resolved.
Show resolved Hide resolved

Fill the shape drawn in the ``with turtle.fill():`` block.

.. doctest::
:skipif: _tkinter is None

>>> turtle.color("black", "red")
>>> with turtle.fill():
... turtle.circle(80)

Using :func:`!fill` is equivalent to adding the :func:`begin_fill` before the
fill-block and :func:`end_fill` after the fill-block:

.. doctest::
:skipif: _tkinter is None

>>> turtle.color("black", "red")
>>> turtle.begin_fill()
>>> turtle.circle(80)
>>> turtle.end_fill()

.. versionadded:: next


.. function:: begin_fill()
Expand Down Expand Up @@ -1648,6 +1699,23 @@ Using events
Special Turtle methods
----------------------


.. function:: poly()

Record the vertices of a polygon drawn in the ``with turtle.poly():`` block.
The first and last vertices will be connected.

.. doctest::
:skipif: _tkinter is None

>>> with turtle.poly():
... turtle.forward(100)
... turtle.right(60)
... turtle.forward(100)

.. versionadded:: next


picnixz marked this conversation as resolved.
Show resolved Hide resolved
.. function:: begin_poly()

Start recording the vertices of a polygon. Current turtle position is first
Expand Down Expand Up @@ -1926,6 +1994,23 @@ Window control
Animation control
-----------------

.. function:: no_animation()

Temporarily disable turtle animation. The code written inside the
``no_animation`` block will not be animated;
once the code block is exited, the drawing will appear.

.. doctest::
:skipif: _tkinter is None

>>> with screen.no_animation():
... for dist in range(2, 400, 2):
... fd(dist)
... rt(90)

.. versionadded:: next
picnixz marked this conversation as resolved.
Show resolved Hide resolved


.. function:: delay(delay=None)

:param delay: positive integer
Expand Down
8 changes: 8 additions & 0 deletions Doc/whatsnew/3.14.rst
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,14 @@ tkinter
(Contributed by Zhikang Yan in :gh:`126899`.)


turtle
------

* Add context managers for :func:`turtle.fill`, :func:`turtle.poly`
and :func:`turtle.no_animation`.
(Contributed by Marie Roald and Yngve Mardal Moe in :gh:`126350`.)


unicodedata
-----------

Expand Down
112 changes: 109 additions & 3 deletions Lib/test/test_turtle.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import os
import pickle
import re
import tempfile
import unittest
import unittest.mock
import tempfile
from test import support
from test.support import import_helper
from test.support import os_helper
Expand Down Expand Up @@ -54,6 +54,21 @@
"""


def patch_screen():
"""Patch turtle._Screen for testing without a display.

We must patch the _Screen class itself instead of the _Screen
instance because instantiating it requires a display.
"""
return unittest.mock.patch(
"turtle._Screen.__new__",
**{
"return_value.__class__": turtle._Screen,
"return_value.mode.return_value": "standard",
},
)


class TurtleConfigTest(unittest.TestCase):

def get_cfg_file(self, cfg_str):
Expand Down Expand Up @@ -513,7 +528,7 @@ def test_save_overwrites_if_specified(self) -> None:

turtle.TurtleScreen.save(screen, file_path, overwrite=True)
with open(file_path) as f:
assert f.read() == "postscript"
self.assertEqual(f.read(), "postscript")

def test_save(self) -> None:
screen = unittest.mock.Mock()
Expand All @@ -524,7 +539,98 @@ def test_save(self) -> None:

turtle.TurtleScreen.save(screen, file_path)
with open(file_path) as f:
assert f.read() == "postscript"
self.assertEqual(f.read(), "postscript")

def test_no_animation_sets_tracer_0(self):
s = turtle.TurtleScreen(cv=unittest.mock.MagicMock())

with s.no_animation():
self.assertEqual(s.tracer(), 0)

def test_no_animation_resets_tracer_to_old_value(self):
s = turtle.TurtleScreen(cv=unittest.mock.MagicMock())

for tracer in [0, 1, 5]:
s.tracer(tracer)
with s.no_animation():
pass
self.assertEqual(s.tracer(), tracer)

def test_no_animation_calls_update_at_exit(self):
s = turtle.TurtleScreen(cv=unittest.mock.MagicMock())
s.update = unittest.mock.MagicMock()

with s.no_animation():
s.update.assert_not_called()
s.update.assert_called_once()


class TestTurtle(unittest.TestCase):
def setUp(self):
with patch_screen():
self.turtle = turtle.Turtle()

def test_begin_end_fill(self):
self.assertFalse(self.turtle.filling())
self.turtle.begin_fill()
self.assertTrue(self.turtle.filling())
self.turtle.end_fill()
self.assertFalse(self.turtle.filling())

def test_fill(self):
# The context manager behaves like begin_fill and end_fill.
self.assertFalse(self.turtle.filling())
with self.turtle.fill():
self.assertTrue(self.turtle.filling())
self.assertFalse(self.turtle.filling())

def test_fill_resets_after_exception(self):
# The context manager cleans up correctly after exceptions.
try:
with self.turtle.fill():
self.assertTrue(self.turtle.filling())
raise ValueError
except ValueError:
self.assertFalse(self.turtle.filling())

def test_fill_context_when_filling(self):
# The context manager works even when the turtle is already filling.
self.turtle.begin_fill()
self.assertTrue(self.turtle.filling())
with self.turtle.fill():
self.assertTrue(self.turtle.filling())
self.assertFalse(self.turtle.filling())

def test_begin_end_poly(self):
self.assertFalse(self.turtle._creatingPoly)
self.turtle.begin_poly()
self.assertTrue(self.turtle._creatingPoly)
self.turtle.end_poly()
self.assertFalse(self.turtle._creatingPoly)

def test_poly(self):
# The context manager behaves like begin_poly and end_poly.
self.assertFalse(self.turtle._creatingPoly)
with self.turtle.poly():
self.assertTrue(self.turtle._creatingPoly)
self.assertFalse(self.turtle._creatingPoly)

def test_poly_resets_after_exception(self):
# The context manager cleans up correctly after exceptions.
try:
with self.turtle.poly():
self.assertTrue(self.turtle._creatingPoly)
raise ValueError
except ValueError:
self.assertFalse(self.turtle._creatingPoly)

def test_poly_context_when_creating_poly(self):
# The context manager works when the turtle is already creating poly.
self.turtle.begin_poly()
self.assertTrue(self.turtle._creatingPoly)
with self.turtle.poly():
self.assertTrue(self.turtle._creatingPoly)
self.assertFalse(self.turtle._creatingPoly)


class TestModuleLevel(unittest.TestCase):
Expand Down
Loading
Loading