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

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
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
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 @@ -1925,6 +1993,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
6 changes: 6 additions & 0 deletions Doc/whatsnew/3.14.rst
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,12 @@ sys
which only exists in specialized builds of Python, may now return objects
from other interpreters than the one it's called in.

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
113 changes: 112 additions & 1 deletion Lib/test/test_turtle.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import os
import pickle
import re
import sys
import tempfile
import unittest
import unittest.mock
import tempfile
from contextlib import contextmanager
from test import support
from test.support import import_helper
from test.support import os_helper
Expand Down Expand Up @@ -54,6 +56,24 @@
"""


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

We must patch the _Screen class itself instead of the _Screen
instance because instatiating it requires a display.
"""
m = unittest.mock.MagicMock()
m.__class__ = turtle._Screen
m.mode.return_value = "standard"

patch = unittest.mock.patch('turtle._Screen.__new__', return_value=m)
try:
yield patch.__enter__()
finally:
patch.__exit__(*sys.exc_info())


class TurtleConfigTest(unittest.TestCase):

def get_cfg_file(self, cfg_str):
Expand Down Expand Up @@ -526,6 +546,97 @@ def test_save(self) -> None:
with open(file_path) as f:
assert f.read() == "postscript"

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

with s.no_animation():
assert 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
assert 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):
def test_all_signatures(self):
Expand Down
Loading
Loading