A community-maintained Python framework for creating mathematical animations.
Update VGroup to support item assignment (#1530) (#1559)
Ryan McCauley1aba7c73f98f
diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.pyindex e9b19094e..10816f8a6 100644--- a/manim/mobject/types/vectorized_mobject.py+++ b/manim/mobject/types/vectorized_mobject.py@@ -1541,6 +1541,32 @@ class VGroup(VMobject):def __isub__(self, vmobject):return self.remove(vmobject)+ def __setitem__(self, key: int, value: Union[VMobject, typing.Sequence[VMobject]]):+ """Override the [] operator for item assignment.++ Parameters+ ----------+ key+ The index of the submobject to be assigned+ value+ The vmobject value to assign to the key++ Returns+ -------+ None++ Examples+ --------+ Normal usage::++ >>> vgroup = VGroup(VMobject())+ >>> new_obj = VMobject()+ >>> vgroup[0] = new_obj+ """+ if not all(isinstance(m, VMobject) for m in value):+ raise TypeError("All submobjects must be of type VMobject")+ self.submobjects[key] = value+class VDict(VMobject):"""A VGroup-like class, also offering submobject access bydiff --git a/tests/test_vectorized_mobject.py b/tests/test_vectorized_mobject.pyindex 6776c15af..346e8fe76 100644--- a/tests/test_vectorized_mobject.py+++ b/tests/test_vectorized_mobject.py@@ -174,3 +174,33 @@ def test_vdict_remove():assert len(obj.submob_dict) == 0with pytest.raises(KeyError):obj.remove("a")+++def test_vgroup_supports_item_assigment():+ """Test VGroup supports array-like assignment for VMObjects"""+ a = VMobject()+ b = VMobject()+ vgroup = VGroup(a)+ assert vgroup[0] == a+ vgroup[0] = b+ assert vgroup[0] == b+ assert len(vgroup) == 1+++def test_vgroup_item_assignment_at_correct_position():+ """Test VGroup item-assignment adds to correct position for VMObjects"""+ n_items = 10+ vgroup = VGroup()+ for i in range(n_items):+ vgroup.add(VMobject())+ new_obj = VMobject()+ vgroup[6] = new_obj+ assert vgroup[6] == new_obj+ assert len(vgroup) == n_items+++def test_vgroup_item_assignment_only_allows_vmobjects():+ """Test VGroup item-assignment raises TypeError when invalid type is passed"""+ vgroup = VGroup(VMobject())+ with pytest.raises(TypeError, match="All submobjects must be of type VMobject"):+ vgroup[0] = "invalid object"