A community-maintained Python framework for creating mathematical animations.
Fix duplicate references in `Scene.mobjects` after `ReplacementTransform` with existing target mobject (#4242)
Irvanal Haqdea245ad9a73
diff --git a/manim/scene/scene.py b/manim/scene/scene.pyindex 574ba59fd..ba162320f 100644--- a/manim/scene/scene.py+++ b/manim/scene/scene.py@@ -592,6 +592,19 @@ class Scene:def replace_in_list(mobj_list: list[Mobject], old_m: Mobject, new_m: Mobject) -> bool:+ # Avoid duplicate references to the same object in self.mobjects+ if new_m in mobj_list:+ if old_m is new_m:+ # In this case, one could say that the old Mobject was already found.+ # No replacement is needed, since old_m is new_m, so no action is required.+ # This might be unexpected, so raise a warning.+ logger.warning(+ f"Attempted to replace {type(old_m).__name__} "+ "with itself in Scene.mobjects."+ )+ return True+ mobj_list.remove(new_m)+# We use breadth-first search because some Mobjects get very deep and# we expect top-level elements to be the most common targets for replace.for i in range(0, len(mobj_list)):diff --git a/tests/module/animation/test_transform.py b/tests/module/animation/test_transform.pynew file mode 100644index 000000000..d1b9c43ae--- /dev/null+++ b/tests/module/animation/test_transform.py@@ -0,0 +1,27 @@+from __future__ import annotations++from manim import Circle, ReplacementTransform, Scene, Square, VGroup+++def test_no_duplicate_references():+ scene = Scene()+ c = Circle()+ sq = Square()+ scene.add(c, sq)++ scene.play(ReplacementTransform(c, sq))+ assert len(scene.mobjects) == 1+ assert scene.mobjects[0] is sq+++def test_duplicate_references_in_group():+ scene = Scene()+ c = Circle()+ sq = Square()+ vg = VGroup(c, sq)+ scene.add(vg)++ scene.play(ReplacementTransform(c, sq))+ submobs = vg.submobjects+ assert len(submobs) == 1+ assert submobs[0] is sq