Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

New Feature: Add generic set method and compatibility layer between properties and get_*/set_* methods (#995)

friedkeenana7ff7bbe7e2c
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index 7f726554a..4b1035866 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -10,6 +10,8 @@ import itertools as it
import operator as op
import random
import sys
+import types
+import warnings
from pathlib import Path
from colour import Color
@@ -34,6 +36,10 @@ from ..utils.space_ops import rotation_matrix
class Mobject(Container):
"""Mathematical Object: base class for objects that can be displayed on screen.
+ There is a compatibility layer that allows for
+ getting and setting generic attributes with ``get_*``
+ and ``set_*`` methods. See :meth:`set` for more details.
+
Attributes
----------
submobjects : :class:`list`
@@ -248,6 +254,106 @@ class Mobject(Container):
def __isub__(self, other):
raise NotImplementedError
+ def set(self, **kwargs):
+ """Sets attributes.
+
+ Mainly to be used along with :attr:`animate` to
+ animate setting attributes.
+
+ In addition to this method, there is a compatibility
+ layer that allows ``get_*`` and ``set_*`` methods to
+ get and set generic attributes. For instance::
+
+ >>> mob = Mobject()
+ >>> mob.set_foo(0)
+ Mobject
+ >>> mob.get_foo()
+ 0
+ >>> mob.foo
+ 0
+
+ This compatibility layer does not interfere with any
+ ``get_*`` or ``set_*`` methods that are explicitly
+ defined.
+
+ .. warning::
+
+ This compatibility layer is for backwards compatibility
+ and is not guaranteed to stay around. Where applicable,
+ please prefer getting/setting attributes normally or with
+ the :meth:`set` method.
+
+ Parameters
+ ----------
+ **kwargs
+ The attributes and corresponding values to set.
+
+ Returns
+ -------
+ :class:`Mobject`
+ ``self``
+
+ Examples
+ --------
+ ::
+
+ >>> mob = Mobject()
+ >>> mob.set(foo=0)
+ Mobject
+ >>> mob.foo
+ 0
+ """
+
+ for attr, value in kwargs.items():
+ setattr(self, attr, value)
+
+ return self
+
+ def __getattr__(self, attr):
+ # Add automatic compatibility layer
+ # between properties and get_* and set_*
+ # methods.
+ #
+ # In python 3.9+ we could change this
+ # logic to use str.remove_prefix instead.
+
+ if attr.startswith("get_"):
+ # Remove the "get_" prefix
+ to_get = attr[4:]
+
+ def getter(self):
+ warnings.warn(
+ "This method is not guaranteed to stay around. Please prefer getting the attribute normally.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ return getattr(self, to_get)
+
+ # Return a bound method
+ return types.MethodType(getter, self)
+
+ if attr.startswith("set_"):
+ # Remove the "set_" prefix
+ to_set = attr[4:]
+
+ def setter(self, value):
+ warnings.warn(
+ "This method is not guaranteed to stay around. Please prefer setting the attribute normally or with Mobject.set().",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
+ setattr(self, to_set, value)
+
+ return self
+
+ # Return a bound method
+ return types.MethodType(setter, self)
+
+ # Unhandled attribute, therefore error
+ raise AttributeError
+
def get_array_attrs(self):
return ["points"]
diff --git a/manim/utils/module_ops.py b/manim/utils/module_ops.py
index ce54904e1..4d57f86ad 100644
--- a/manim/utils/module_ops.py
+++ b/manim/utils/module_ops.py
@@ -6,6 +6,7 @@ from pathlib import Path
import sys
import types
import re
+import warnings
def get_module(file_name: Path):
@@ -33,6 +34,11 @@ def get_module(file_name: Path):
if ext != ".py":
raise ValueError(f"{file_name} is not a valid Manim python script.")
module_name = ext.replace(os.sep, ".").split(".")[-1]
+
+ warnings.filterwarnings(
+ "default", category=DeprecationWarning, module=module_name
+ )
+
spec = importlib.util.spec_from_file_location(module_name, file_name)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
diff --git a/tests/test_get_set.py b/tests/test_get_set.py
new file mode 100644
index 000000000..47d1852d6
--- /dev/null
+++ b/tests/test_get_set.py
@@ -0,0 +1,40 @@
+import types
+import pytest
+
+from manim.mobject.mobject import Mobject
+
+
+def test_generic_set():
+ m = Mobject()
+ m.set(test=0)
+
+ assert m.test == 0
+
+
[email protected]("ignore::DeprecationWarning")
+def test_get_compat_layer():
+ m = Mobject()
+
+ assert isinstance(m.get_test, types.MethodType)
+ with pytest.raises(AttributeError):
+ m.get_test()
+
+ m.test = 0
+ assert m.get_test() == 0
+
+
[email protected]("ignore::DeprecationWarning")
+def test_set_compat_layer():
+ m = Mobject()
+
+ assert isinstance(m.set_test, types.MethodType)
+ m.set_test(0)
+
+ assert m.test == 0
+
+
+def test_nonexistent_attr():
+ m = Mobject()
+
+ with pytest.raises(AttributeError):
+ m.test