Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Added sanity checks to :meth:`~.Mobject.add_to_back` for Mobjects (#1220)

Ricky Chondd259bbe306f
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index 3ac4e6569..a34c191d4 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -353,9 +353,36 @@ class Mobject(Container):
the head of :attr:`submobjects`. The head of this list is rendered
first, which places the corresponding mobjects behind the
subsequent list members.
+
+ Raises
+ ------
+ :class:`ValueError`
+ When a mobject tries to add itself.
+ :class:`TypeError`
+ When trying to add an object that is not an instance of :class:`Mobject`.
+
+ Notes
+ -----
+ A mobject cannot contain itself, and it cannot contain a submobject
+ more than once. If the parent mobject is displayed, the newly-added
+ submobjects will also be displayed (i.e. they are automatically added
+ to the parent Scene).
+
+ See Also
+ --------
+ :meth:`remove`
+ :meth:`add`
+
"""
+ for mobject in mobjects:
+ if self in mobjects:
+ raise ValueError("Mobject cannot contain self")
+ if not isinstance(mobject, Mobject):
+ raise TypeError("All submobjects must be of type Mobject")
+
+ filtered = list_update(mobjects, self.submobjects)
self.remove(*mobjects)
- self.submobjects = list(mobjects) + self.submobjects
+ self.submobjects = list(filtered) + self.submobjects
return self
def remove(self, *mobjects: "Mobject") -> "Mobject":
diff --git a/tests/test_vectorized_mobject.py b/tests/test_vectorized_mobject.py
index f8f9e1e93..b9507682f 100644
--- a/tests/test_vectorized_mobject.py
+++ b/tests/test_vectorized_mobject.py
@@ -1,6 +1,6 @@
import pytest
-from manim import Mobject, VDict, VGroup, VMobject
+from manim import Line, Mobject, VDict, VGroup, VMobject
def test_vgroup_init():
@@ -86,6 +86,24 @@ def test_vgroup_remove_dunder():
assert len(obj.submobjects) == 0
+def test_vmob_add_to_back():
+ """Test the Mobject add_to_back method."""
+ a = VMobject()
+ b = Line()
+ c = "text"
+ with pytest.raises(ValueError):
+ # Mobject cannot contain self
+ a.add_to_back(a)
+ with pytest.raises(TypeError):
+ # All submobjects must be of type Mobject
+ a.add_to_back(c)
+
+ # No submobject gets added twice
+ a.add_to_back(b)
+ a.add_to_back(b, b)
+ assert len(a.submobjects) == 1
+
+
def test_vdict_init():
"""Test the VDict instantiation."""
# Test empty VDict