A community-maintained Python framework for creating mathematical animations.
Deprecation Decorators (#1404)
Anton Ballmaier71b86d5dfa83
diff --git a/docs/source/reference.rst b/docs/source/reference.rstindex d98e62477..56daaf710 100644--- a/docs/source/reference.rst+++ b/docs/source/reference.rst@@ -205,6 +205,7 @@ Utilities~utils.bezier~utils.color~utils.config_ops+ ~utils.deprecation~utils.hashing~utils.ipython_magic~utils.imagesdiff --git a/manim/animation/animation.py b/manim/animation/animation.pyindex 001f8ec25..ce6f03888 100644--- a/manim/animation/animation.py+++ b/manim/animation/animation.py@@ -14,6 +14,7 @@ from .. import loggerfrom ..mobject import mobject, opengl_mobjectfrom ..mobject.mobject import Mobjectfrom ..mobject.opengl_mobject import OpenGLMobject+from ..utils.deprecation import deprecatedfrom ..utils.rate_functions import smoothDEFAULT_ANIMATION_RUN_TIME: float = 1.0@@ -138,15 +139,8 @@ class Animation:alpha = min(max(alpha, 0), 1)self.interpolate_mobject(self.rate_func(alpha))+ @deprecated(until="v0.6.0", replacement="interpolate")def update(self, alpha: float) -> None:- """- This method shouldn't exist, but it's here to- keep many old scenes from breaking- """- logger.warning(- "animation.update() has been deprecated. "- "Please use animation.interpolate() instead."- )self.interpolate(alpha)def interpolate_mobject(self, alpha: float) -> None:diff --git a/manim/animation/creation.py b/manim/animation/creation.pyindex 1227734c2..d758caa48 100644--- a/manim/animation/creation.py+++ b/manim/animation/creation.py@@ -76,8 +76,6 @@ from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional, Tuplimport numpy as npfrom colour import Color-from .. import logger-if TYPE_CHECKING:from manim.mobject.svg.text_mobject import Text@@ -87,6 +85,7 @@ from ..mobject.mobject import Group, Mobjectfrom ..mobject.types.opengl_vectorized_mobject import OpenGLVMobjectfrom ..mobject.types.vectorized_mobject import VMobjectfrom ..utils.bezier import integer_interpolate+from ..utils.deprecation import deprecatedfrom ..utils.rate_functions import double_smooth, linear, smoothdiff --git a/manim/animation/indication.py b/manim/animation/indication.pyindex a86e3be14..655c3ebf6 100644--- a/manim/animation/indication.py+++ b/manim/animation/indication.py@@ -52,7 +52,6 @@ import numpy as npfrom colour import Colorfrom .. import config-from .._config import loggerfrom ..animation.animation import Animationfrom ..animation.composition import AnimationGroup, Successionfrom ..animation.creation import Create, ShowPartial, Uncreate@@ -66,6 +65,7 @@ from ..mobject.shape_matchers import SurroundingRectanglefrom ..mobject.types.vectorized_mobject import VGroup, VMobjectfrom ..utils.bezier import interpolate, inverse_interpolatefrom ..utils.color import GREY, YELLOW+from ..utils.deprecation import deprecatedfrom ..utils.rate_functions import smooth, there_and_back, wigglefrom ..utils.space_ops import normalize@@ -278,9 +278,8 @@ class Flash(AnimationGroup):]+@deprecated(since="v0.5.0", until="v0.7.0", replacement="Circumscribe")class CircleIndicate(Indicate):- """Deprecated. Use :class:`~.Circumscribe` instead."""-def __init__(self,mobject: "Mobject",@@ -291,9 +290,6 @@ class CircleIndicate(Indicate):remover: bool = True,**kwargs) -> None:- logger.warning(- "ShowCreationThenDestructionAround has been deprecated in favor of Circumscribe. Please use Circumscribe instead!"- )self.circle_config = circle_configcircle = self.get_circle(mobject)super().__init__(circle, rate_func=rate_func, remover=remover, **kwargs)@@ -383,15 +379,11 @@ class ShowPassingFlashWithThinningStrokeWidth(AnimationGroup):)+@deprecated(since="v0.5.0", until="v0.7.0", replacement="ShowPassingFlash")class ShowCreationThenDestruction(ShowPassingFlash):- """Deprecated. Use :class:`~.ShowPassingFlash` instead."""-def __init__(self, mobject: "Mobject", time_width: float = 2.0, run_time: float = 1, **kwargs) -> None:- logger.warning(- "ShowCreationThenDestruction has been deprecated in favor of ShowPassingFlash. Please use ShowPassingFlash instead!"- )super().__init__(mobject, time_width=time_width, run_time=run_time, **kwargs)@@ -404,9 +396,8 @@ class ShowCreationThenFadeOut(Succession):super().__init__(Create(mobject), FadeOut(mobject), remover=remover, **kwargs)+@deprecated(since="v0.5.0", until="v0.7.0", replacement="Circumscribe")class AnimationOnSurroundingRectangle(AnimationGroup):- """Deprecated. Use :class:`~.Circumscribe` instead or build an Animation using :class:`~SurroundingRectangle`."""-def __init__(self,mobject: "Mobject",@@ -414,9 +405,6 @@ class AnimationOnSurroundingRectangle(AnimationGroup):surrounding_rectangle_config: typing.Dict[str, typing.Any] = {},**kwargs) -> None:- logger.warning(- "AnimationOnSurroundingRectangle has been deprecated in favor of Circumscribe. Please use Circumscribe instead!"- )# Callable which takes in a rectangle, and spits out some animation. Could be# some animation class, could be something moreself.rect_animation = rect_animation@@ -436,45 +424,33 @@ class AnimationOnSurroundingRectangle(AnimationGroup):)+@deprecated(since="v0.5.0", until="v0.7.0", replacement="Circumscribe")class ShowPassingFlashAround(AnimationOnSurroundingRectangle):- """Deprecated. Use :class:`~.Circumscribe` instead."""-def __init__(self, mobject: "Mobject", rect_animation: Animation = ShowPassingFlash, **kwargs) -> None:- logger.warning(- "ShowPassingFlashAround has been deprecated in favor of Circumscribe. Please use Circumscribe instead!"- )super().__init__(mobject, rect_animation=rect_animation, **kwargs)+@deprecated(since="v0.5.0", until="v0.7.0", replacement="Circumscribe")class ShowCreationThenDestructionAround(AnimationOnSurroundingRectangle):- """Deprecated. Use :class:`~.Circumscribe` instead."""-def __init__(self,mobject: "Mobject",rect_animation: Animation = ShowCreationThenDestruction,**kwargs) -> None:- logger.warning(- "ShowCreationThenDestructionAround has been deprecated in favor of Circumscribe. Please use Circumscribe instead!"- )super().__init__(mobject, rect_animation=rect_animation, **kwargs)+@deprecated(since="v0.5.0", until="v0.7.0", replacement="Circumscribe")class ShowCreationThenFadeAround(AnimationOnSurroundingRectangle):- """Deprecated. Use :class:`~.Circumscribe` instead."""-def __init__(self,mobject: "Mobject",rect_animation: Animation = ShowCreationThenFadeOut,**kwargs) -> None:- logger.warning(- "ShowCreationThenFadeAround has been deprecated in favor of Circumscribe. Please use Circumscribe instead!"- )super().__init__(mobject, rect_animation=rect_animation, **kwargs)@@ -677,23 +653,19 @@ class Wiggle(Animation):)+@deprecated(since="v0.5.0", until="v0.7.0", replacement="Wiggle")class WiggleOutThenIn(Wiggle):- """Deprecated. Use :class:`~.Wiggle` instead."""-def __init__(*args, **kwargs):- logger.warning(- "WiggleOutThenIn has been deprecated in favor of Wiggle. Please use Wiggle instead!"- )- super().__init__(*args, **kwargs)+ super().__init(*args, **kwargs)+@deprecated(+ since="v0.5.0",+ until="v0.7.0",+ message="Use :code:`mobject.animate.become(mobject.copy().reverse_points())` instead if you have to.",+)class TurnInsideOut(Transform):- """Deprecated. Use :code:`mobject.animate.become(mobject.copy().reverse_points())` instead if you have to."""-def __init__(self, mobject: "Mobject", path_arc: float = TAU / 4, **kwargs) -> None:- logger.warning(- "TurnInsideOut has been deprecated. Please stop using TurnInsideOut!"- )super().__init__(mobject, path_arc=path_arc, **kwargs)def create_target(self) -> "Mobject":diff --git a/manim/animation/numbers.py b/manim/animation/numbers.pyindex 4482c8c83..223118bb6 100644--- a/manim/animation/numbers.py+++ b/manim/animation/numbers.py@@ -9,9 +9,15 @@ import warningsfrom ..animation.animation import Animationfrom ..mobject.numbers import DecimalNumberfrom ..utils.bezier import interpolate+from ..utils.deprecation import deprecated_paramsclass ChangingDecimal(Animation):+ @deprecated_params(+ "tracked_mobject position_update_func",+ until="v0.6.0",+ message="Use a mobject updater instead.",+ )def __init__(self,decimal_mob: DecimalNumber,@@ -20,7 +26,6 @@ class ChangingDecimal(Animation):**kwargs,) -> None:self.check_validity_of_input(decimal_mob)- self.yell_about_deprecated_configuration(**kwargs)self.number_update_func = number_update_funcsuper().__init__(decimal_mob, suspend_mobject_updating=suspend_mobject_updating, **kwargs@@ -30,20 +35,6 @@ class ChangingDecimal(Animation):if not isinstance(decimal_mob, DecimalNumber):raise TypeError("ChangingDecimal can only take in a DecimalNumber")- def yell_about_deprecated_configuration(self, **kwargs) -> None:- # Obviously this would optimally be removed at- # some point.- for attr in ["tracked_mobject", "position_update_func"]:- if attr in kwargs:- warnings.warn(- f"""- Don't use {attr} for ChangingDecimal,- that functionality has been deprecated- and you should use a mobject updater- instead- """- )-def interpolate_mobject(self, alpha: float) -> None:self.mobject.set_value(self.number_update_func(alpha))diff --git a/manim/mobject/opengl_geometry.py b/manim/mobject/opengl_geometry.pyindex 493207079..b501dec52 100644--- a/manim/mobject/opengl_geometry.py+++ b/manim/mobject/opengl_geometry.py@@ -9,6 +9,7 @@ from ..mobject.types.opengl_vectorized_mobject import (OpenGLVMobject,)from ..utils.color import *+from ..utils.deprecation import deprecatedfrom ..utils.iterables import adjacent_n_tuples, adjacent_pairsfrom ..utils.simple_functions import clip, fdivfrom ..utils.space_ops import (@@ -340,14 +341,10 @@ class OpenGLDot(OpenGLCircle):)+@deprecated(until="v0.6.0", replacement="OpenGLDot")class OpenGLSmallDot(OpenGLDot):- """Deprecated"""-def __init__(self, radius=DEFAULT_SMALL_DOT_RADIUS, **kwargs):- logger.warning(- "OpenGLSmallDot has been deprecated and will be removed in a future release."- "Use OpenGLDot instead."- )+super().__init__(radius=radius, **kwargs)diff --git a/manim/mobject/svg/opengl_tex_mobject.py b/manim/mobject/svg/opengl_tex_mobject.pyindex 1556ebca4..b8564d1ef 100644--- a/manim/mobject/svg/opengl_tex_mobject.py+++ b/manim/mobject/svg/opengl_tex_mobject.py@@ -171,16 +171,18 @@ __all__ = [import operator as opfrom functools import reduce-from ... import config, logger+from ... import configfrom ...constants import *from ...mobject.opengl_geometry import OpenGLLinefrom ...mobject.svg.opengl_svg_mobject import OpenGLSVGMobjectfrom ...mobject.svg.opengl_svg_path import OpenGLSVGPathMobject+from ...mobject.svg.tex_mobject import MathTex, Texfrom ...mobject.types.opengl_vectorized_mobject import (OpenGLVectorizedPoint,OpenGLVGroup,)from ...utils.color import BLACK+from ...utils.deprecation import deprecatedfrom ...utils.strings import split_string_list_to_isolate_substringsfrom ...utils.tex_file_writing import tex_to_svg_filefrom .style_utils import parse_style@@ -597,19 +599,13 @@ class OpenGLTitle(OpenGLTex):self.underline = underline+@deprecated(until="v0.7.0", replacement="MathTex")class OpenGLTexMobject(OpenGLMathTex):def __init__(self, *tex_strings, **kwargs):- logger.warning(- "TexMobject has been deprecated (due to its confusing name) "- "in favour of MathTex. Please use MathTex instead!"- )MathTex.__init__(self, *tex_strings, **kwargs)+@deprecated(until="v0.7.0", replacement="Tex")class OpenGLTextMobject(OpenGLTex):def __init__(self, *text_parts, **kwargs):- logger.warning(- "TextMobject has been deprecated (due to its confusing name) "- "in favour of Tex. Please use Tex instead!"- )Tex.__init__(self, *text_parts, **kwargs)diff --git a/manim/mobject/svg/svg_path.py b/manim/mobject/svg/svg_path.pyindex c69edba81..8d41d33fa 100644--- a/manim/mobject/svg/svg_path.py+++ b/manim/mobject/svg/svg_path.py@@ -10,11 +10,10 @@ from typing import Listimport numpy as np-from manim import logger-from ... import configfrom ...constants import *from ...mobject.types.vectorized_mobject import VMobject+from ...utils.deprecation import deprecateddef correct_out_of_range_radii(rx, ry, x1p, y1p):@@ -444,12 +443,7 @@ class SVGPathMobject(VMobject):return self+@deprecated(until="v0.7.0", replacement="SVGPathMobject")class VMobjectFromSVGPathstring(SVGPathMobject):- """Pure alias of SVGPathMobject, retained for backwards compatibility"""-def __init__(self, *args, **kwargs):- logger.warning(- "VMobjectFromSVGPathstring has been deprecated in favour "- "of SVGPathMobject. Please use SVGPathMobject instead."- )- SVGPathMobject.__init__(self, *args, **kwargs)+ super().__init__(self, *args, **kwargs)diff --git a/manim/utils/debug.py b/manim/utils/debug.pyindex a2b6d114d..2451db64e 100644--- a/manim/utils/debug.py+++ b/manim/utils/debug.py@@ -4,11 +4,12 @@__all__ = ["print_family", "index_labels", "get_submobject_index_labels"]-import logging+from os import replacefrom ..mobject.numbers import Integerfrom ..mobject.types.vectorized_mobject import VGroupfrom .color import BLACK+from .deprecation import deprecateddef print_family(mobject, n_tabs=0):@@ -29,9 +30,6 @@ def index_labels(mobject, label_height=0.15):return labels+@deprecated(until="v0.6.0", replacement="index_labels")def get_submobject_index_labels(mobject, label_height=0.15):- logging.getLogger("manim").warning(- "get_submobject_index_labels has been deprecated and has been replaced by index_labels, which does the same thing, and will thus be removed in a future release."- )-return index_labels(mobject, label_height)diff --git a/manim/utils/deprecation.py b/manim/utils/deprecation.pynew file mode 100644index 000000000..4d73ec975--- /dev/null+++ b/manim/utils/deprecation.py@@ -0,0 +1,468 @@+"""Decorators for deprecating classes, functions and function parameters."""++__all__ = ["deprecated", "deprecated_params"]+++import inspect+import re+from typing import Any, Callable, Iterable, List, Optional, Tuple, Union++from decorator import decorate, decorator++from .. import logger+++def _get_callable_info(callable: Callable) -> Tuple[str, str]:+ """Returns type and name of a callable.++ Parameters+ ----------+ callable+ The callable++ Returns+ -------+ Tuple[str, str]+ The type and name of the callable. Type can can be one of "class", "method" (for+ functions defined in classes) or "function"). For methods, name is Class.method.+ """+ what = type(callable).__name__+ name = callable.__qualname__+ if what == "function" and "." in name:+ what = "method"+ elif what != "function":+ what = "class"+ return (what, name)+++def _deprecation_text_component(+ since: Optional[str], until: Optional[str], message: str+) -> str:+ """Generates a text component used in deprecation messages.++ Parameters+ ----------+ since+ The version or date since deprecation+ until+ The version or date until removal of the deprecated callable+ message+ The reason for why the callable has been deprecated++ Returns+ -------+ str+ The deprecation message text component.+ """+ since = f"since {since} " if since else ""+ until = (+ f"is expected to be removed after {until}"+ if until+ else "may be removed in a later version"+ )+ msg = " " + message if message else ""+ return f"deprecated {since}and {until}.{msg}"+++def deprecated(+ func: Callable = None,+ since: Optional[str] = None,+ until: Optional[str] = None,+ replacement: Optional[str] = None,+ message: Optional[str] = "",+) -> Callable:+ """Decorator to mark a callable as deprecated.++ The decorated callable will cause a warning when used. The docstring of the+ deprecated callable is adjusted to indicate that this callable is deprecated.++ Parameters+ ----------+ func+ The function to be decorated. Should not be set by the user.+ since+ The version or date since deprecation.+ until+ The version or date until removal of the deprecated callable.+ replacement+ The identifier of the callable replacing the deprecated one.+ message+ The reason for why the callable has been deprecated.++ Returns+ -------+ Callable+ The decorated callable.++ Examples+ --------+ Basic usage::++ @deprecated+ def foo(**kwargs):+ pass++ @deprecated+ class Bar:+ def __init__(self):+ pass++ @deprecated+ def baz(self):+ pass++ foo()+ # WARNING The function foo has been deprecated and may be removed in a later version.++ a = Bar()+ # WARNING The class Bar has been deprecated and may be removed in a later version.++ a.baz()+ # WARNING The method Bar.baz has been deprecated and may be removed in a later version.++ You can specify additional information for a more precise warning::++ @deprecated(+ since="v0.2",+ until="v0.4",+ replacement="bar",+ message="It is cooler."+ )+ def foo():+ pass++ foo()+ # WARNING The function foo has been deprecated since v0.2 and is expected to be removed after v0.4. Use bar instead. It is cooler.++ You may also use dates instead of versions::++ @deprecated(since="05/01/2021", until="06/01/2021")+ def foo():+ pass++ foo()+ # WARNING The function foo has been deprecated since 05/01/2021 and is expected to be removed after 06/01/2021.++ """+ # If used as factory:+ if func is None:+ return lambda func: deprecated(func, since, until, replacement, message)++ what, name = _get_callable_info(func)++ def warning_msg(for_docs: bool = False) -> str:+ """Generate the deprecation warning message.++ Parameters+ ----------+ for_docs+ Whether or not to format the message for use in documentation.++ Returns+ -------+ str+ The deprecation message.+ """+ msg = message+ if replacement is not None:+ repl = replacement+ if for_docs:+ mapper = {"class": "class", "method": "meth", "function": "func"}+ repl = f":{mapper[what]}:`~.{replacement}`"+ msg = f"Use {repl} instead.{' ' + message if message else ''}"+ deprecated = _deprecation_text_component(since, until, msg)+ return f"The {what} {name} has been {deprecated}"++ def deprecate_docs(func: Callable):+ """Adjust docstring to indicate the deprecation.++ Parameters+ ----------+ func+ The callable whose docstring to adjust.+ """+ warning = warning_msg(True)+ doc_string = func.__doc__ or ""+ func.__doc__ = f"{doc_string}\n\n.. admonition:: Deprecated\n :class: attention\n\n {warning}"++ def deprecate(func: Callable, *args, **kwargs):+ """The actual decorator used to extend the callables behavior.++ Logs a warning message.++ Parameters+ ----------+ func+ The callable to decorate.+ args+ The arguments passed to the given callable.+ kwargs+ The keyword arguments passed to the given callable.++ Returns+ -------+ Any+ The return value of the given callable when beeing passed the given+ arguments.+ """+ logger.warning(warning_msg())+ return func(*args, **kwargs)++ if type(func).__name__ != "function":+ deprecate_docs(func)+ func.__init__ = decorate(func.__init__, deprecate)+ return func++ print(type(func))+ func = decorate(func, deprecate)+ deprecate_docs(func)+ return func+++def deprecated_params(+ params: Optional[Union[str, Iterable[str]]] = None,+ since: Optional[str] = None,+ until: Optional[str] = None,+ message: Optional[str] = "",+ redirections: Optional[+ "Iterable[Union[Tuple[str, str], Callable[..., dict[str, Any]]]]"+ ] = None,+) -> Callable:+ """Decorator to mark parameters of a callable as deprecated.++ It can also be used to automatically redirect deprecated parameter values to their+ replacements.++ Parameters+ ----------+ params+ The parameters to be deprecated. Can consist of:++ * An iterable of strings, with each element representing a parameter to deprecate+ * A single string, with parameter names separated by commas or spaces.+ since+ The version or date since deprecation.+ until+ The version or date until removal of the deprecated callable.+ message+ The reason for why the callable has been deprecated.+ redirections+ A list of parameter redirections. Each redirection can be one of the following:++ * A tuple of two strings. The first string defines the name of the deprecated+ parameter; the second string defines the name of the parameter to redirect to,+ when attempting to use the first string.++ * A function performing the mapping operation. The parameter names of the+ function determine which parameters are used as input. The function must+ return a dictionary which contains the redirected arguments.++ Redirected parameters are also implicitly deprecated.++ Returns+ -------+ Callable+ The decorated callable.++ Raises+ ------+ ValueError+ If no parameters are defined (neither explicitly nor implicitly).+ ValueError+ If defined parameters are invalid python identifiers.++ Examples+ --------+ Basic usage::++ @deprecated_params(params="a, b, c")+ def foo(**kwargs):+ pass++ foo(x=2, y=3, z=4)+ # No warning++ foo(a=2, b=3, z=4)+ # WARNING The parameters a and b of method foo have been deprecated and may be removed in a later version.++ You can also specify additional information for a more precise warning::++ @deprecated_params(+ params="a, b, c",+ since="v0.2",+ until="v0.4",+ message="The letters x, y, z are cooler."+ )+ def foo(**kwargs):+ pass++ foo(a=2)+ # WARNING The parameter a of method foo has been deprecated since v0.2 and is expected to be removed after v0.4. The letters x, y, z are cooler.++ Basic parameter redirection::++ @deprecated_params(redirections=[+ # Two ways to redirect one parameter to another:+ ("old_param", "new_param"),+ lambda old_param2: {"new_param22": old_param2}+ ])+ def foo(**kwargs):+ return kwargs++ foo(x=1, old_param=2)+ # WARNING The parameter old_param of method foo has been deprecated and may be removed in a later version.+ # returns {"x": 1, "new_param": 2}++ Redirecting using a calculated value::++ @deprecated_params(redirections=[+ lambda runtime_in_ms: {"run_time": runtime_in_ms / 1000}+ ])+ def foo(**kwargs):+ return kwargs++ foo(runtime_in_ms=500)+ # WARNING The parameter runtime_in_ms of method foo has been deprecated and may be removed in a later version.+ # returns {"run_time": 0.5}++ Redirecting multiple parameter values to one::++ @deprecated_params(redirections=[+ lambda buff_x=1, buff_y=1: {"buff": (buff_x, buff_y)}+ ])+ def foo(**kwargs):+ return kwargs++ foo(buff_x=2)+ # WARNING The parameter buff_x of method foo has been deprecated and may be removed in a later version.+ # returns {"buff": (2, 1)}++ Redirect one parameter to multiple::++ @deprecated_params(redirections=[+ lambda buff=1: {"buff_x": buff[0], "buff_y": buff[1]} if isinstance(buff, tuple)+ else {"buff_x": buff, "buff_y": buff}+ ])+ def foo(**kwargs):+ return kwargs++ foo(buff=0)+ # WARNING The parameter buff of method foo has been deprecated and may be removed in a later version.+ # returns {"buff_x": 0, buff_y: 0}++ foo(buff=(1,2))+ # WARNING The parameter buff of method foo has been deprecated and may be removed in a later version.+ # returns {"buff_x": 1, buff_y: 2}+++ """+ # Check if decorator is used without parenthesis+ if callable(params):+ raise ValueError("deprecate_parameters requires arguments to be specified.")++ if params is None:+ params = []++ # Construct params list+ params = re.split("[,\s]+", params) if isinstance(params, str) else list(params)++ # Add params which are only implicitly given via redirections+ if redirections is None:+ redirections = []+ for redirector in redirections:+ if isinstance(redirector, tuple):+ params.append(redirector[0])+ else:+ params.extend(inspect.getargspec(redirector).args)+ print(inspect.getargspec(redirector).args)+ # Keep ordering of params so that warning message is consistently the same+ # This will also help pass unit testing+ params = list(dict.fromkeys(params))++ # Make sure params only contains valid identifiers+ identifier = re.compile(r"^[^\d\W]\w*\Z", re.UNICODE)+ if not all(re.match(identifier, param) for param in params):+ raise ValueError("Given parameter values are invalid.")++ redirections = list(redirections)++ def warning_msg(func: Callable, used: List[str]):+ """Generate the deprecation warning message.++ Parameters+ ----------+ func+ The callable with deprecated parameters.+ used+ The list of deprecated parameters used in a call.++ Returns+ -------+ str+ The deprecation message.+ """+ what, name = _get_callable_info(func)+ plural = len(used) > 1+ parameter_s = "s" if plural else ""+ used_ = ", ".join(used[:-1]) + " and " + used[-1] if plural else used[0]+ has_have_been = "have been" if plural else "has been"+ deprecated = _deprecation_text_component(since, until, message)+ return f"The parameter{parameter_s} {used_} of {what} {name} {has_have_been} {deprecated}"++ def redirect_params(kwargs: dict, used: List[str]):+ """Adjust the keyword arguments as defined by the redirections.++ Parameters+ ----------+ kwargs+ The keyword argument dictionary to be updated.+ used+ The list of depecated parameters used in a call.+ """+ for redirector in redirections:+ if isinstance(redirector, tuple):+ old_param, new_param = redirector+ if old_param in used:+ kwargs[new_param] = kwargs.pop(old_param)+ else:+ redirector_params = inspect.getargspec(redirector).args+ redirector_args = {}+ for redirector_param in redirector_params:+ if redirector_param in used:+ redirector_args[redirector_param] = kwargs.pop(redirector_param)+ if len(redirector_args) > 0:+ kwargs.update(redirector(**redirector_args))++ def deprecate_params(func, *args, **kwargs):+ """The actual decorator function used to extend the callables behavior.++ Logs a warning message when a deprecated parameter is used and redirects it if+ specified.++ Parameters+ ----------+ func+ The callable to decorate.+ args+ The arguments passed to the given callable.+ kwargs+ The keyword arguments passed to the given callable.++ Returns+ -------+ Any+ The return value of the given callable when beeing passed the given+ arguments.++ """+ used = []+ for param in params:+ if param in kwargs:+ used.append(param)++ if len(used) > 0:+ logger.warning(warning_msg(func, used))+ redirect_params(kwargs, used)+ return func(*args, **kwargs)++ return decorator(deprecate_params)diff --git a/manim/utils/space_ops.py b/manim/utils/space_ops.pyindex 60a9cb644..aae9d1a98 100644--- a/manim/utils/space_ops.py+++ b/manim/utils/space_ops.py@@ -41,14 +41,12 @@ from mapbox_earcut import triangulate_float32 as earcutfrom .. import configfrom ..constants import DOWN, OUT, PI, RIGHT, TAU+from ..utils.deprecation import deprecatedfrom ..utils.iterables import adjacent_pairs+@deprecated(since="v0.6.0", until="v0.8.0", replacement="np.linalg.norm")def get_norm(vect):- logger.warning(- "get_norm has been deprecated and will be removed in a future release."- "Use np.linalg.norm instead."- )return np.linalg.norm(vect)@@ -215,11 +213,8 @@ def z_to_vector(vector):return np.dot(rotation_about_z(theta), phi_down)+@deprecated(since="v0.6.0", until="v0.8.0", replacement="angle_between_vectors")def angle_between(v1, v2):- logger.warning(- "angle_between has been deprecated and will be removed in a future release."- "Use angle_between_vectors instead."- )return np.arccos(np.dot(v1 / np.linalg.norm(v1), v2 / np.linalg.norm(v2)))@@ -275,11 +270,8 @@ def normalize_along_axis(array, axis, fall_back=None):return array+@deprecated(since="v0.6.0", until="v0.8.0", replacement="np.cross")def cross(v1, v2):- logger.warning(- "cross has been deprecated and will be removed in a future release."- "Use np.cross instead."- )return np.cross(v1, v2)diff --git a/poetry.lock b/poetry.lockindex ca5f40a80..2c8a32796 100644--- a/poetry.lock+++ b/poetry.lock@@ -273,11 +273,11 @@ six = "*"[[package]]name = "decorator"-version = "4.4.2"+version = "5.0.7"description = "Decorators for Humans"category = "main"optional = false-python-versions = ">=2.6, !=3.0.*, !=3.1.*"+python-versions = ">=3.5"[[package]]name = "defusedxml"@@ -977,14 +977,14 @@ python-versions = ">=3.5"[[package]]name = "networkx"-version = "2.5.1"+version = "2.5"description = "Python package for creating and manipulating graphs and networks"category = "main"optional = falsepython-versions = ">=3.6"[package.dependencies]-decorator = ">=4.3,<5"+decorator = ">=4.3.0"[package.extras]all = ["numpy", "scipy", "pandas", "matplotlib", "pygraphviz", "pydot", "pyyaml", "lxml", "pytest"]@@ -2031,8 +2031,8 @@ cycler = [{file = "cycler-0.10.0.tar.gz", hash = "sha256:cd7b2d1018258d7247a71425e9f26463dfb444d411c39569972f4ce586b0c9d8"},]decorator = [- {file = "decorator-4.4.2-py2.py3-none-any.whl", hash = "sha256:41fa54c2a0cc4ba648be4fd43cff00aedf5b9465c9bf18d64325bc225f08f760"},- {file = "decorator-4.4.2.tar.gz", hash = "sha256:e3a62f0520172440ca0dcc823749319382e377f37f140a0b99ef45fecb84bfe7"},+ {file = "decorator-5.0.7-py3-none-any.whl", hash = "sha256:945d84890bb20cc4a2f4a31fc4311c0c473af65ea318617f13a7257c9a58bc98"},+ {file = "decorator-5.0.7.tar.gz", hash = "sha256:6f201a6c4dac3d187352661f508b9364ec8091217442c9478f1f83c003a0f060"},]defusedxml = [{file = "defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61"},@@ -2541,8 +2541,8 @@ nest-asyncio = [{file = "nest_asyncio-1.5.1.tar.gz", hash = "sha256:afc5a1c515210a23c461932765691ad39e8eba6551c055ac8d5546e69250d0aa"},]networkx = [- {file = "networkx-2.5.1-py3-none-any.whl", hash = "sha256:0635858ed7e989f4c574c2328380b452df892ae85084144c73d8cd819f0c4e06"},- {file = "networkx-2.5.1.tar.gz", hash = "sha256:109cd585cac41297f71103c3c42ac6ef7379f29788eb54cb751be5a663bb235a"},+ {file = "networkx-2.5-py3-none-any.whl", hash = "sha256:8c5812e9f798d37c50570d15c4a69d5710a18d77bafc903ee9c5fba7454c616c"},+ {file = "networkx-2.5.tar.gz", hash = "sha256:7978955423fbc9639c10498878be59caf99b44dc304c2286162fd24b458c1602"},]nodeenv = [{file = "nodeenv-1.6.0-py2.py3-none-any.whl", hash = "sha256:621e6b7076565ddcacd2db0294c0381e01fd28945ab36bcf00f41c5daf63bef7"},diff --git a/pyproject.toml b/pyproject.tomlindex b3a3d0f18..b5cdd9d95 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -39,7 +39,8 @@ rich = "^6.0"pycairo = "^1.19"manimpango = "^0.2.4"networkx = "^2.5"-decorator = "<5.0.0" # remove as soon as https://github.com/networkx/networkx/issues/4718 is resolved+decorator = "^5.0.7"+setuptools = "*"importlib-metadata = {version = "*", python = "<3.8"}grpcio = { version = "1.33.*", optional = true }grpcio-tools = { version = "1.33.*", optional = true }diff --git a/scripts/template_docsting_with_example.py b/scripts/template_docsting_with_example.pyindex e08c0186a..77ed8445b 100644--- a/scripts/template_docsting_with_example.py+++ b/scripts/template_docsting_with_example.py@@ -6,8 +6,6 @@ class SomeClass:A short paragraph providing more details.- Deprecation warning-Extended SummaryParametersdiff --git a/tests/test_deprecation.py b/tests/test_deprecation.pynew file mode 100644index 000000000..fd698b44b--- /dev/null+++ b/tests/test_deprecation.py@@ -0,0 +1,389 @@+import warnings++import pytest++from manim import logger+from manim.utils.deprecation import deprecated, deprecated_params+++@deprecated+class Foo:+ def __init__(self):+ pass+++@deprecated(since="v0.6.0")+class Bar:+ """The Bar class."""++ def __init__(self):+ pass+++@deprecated(until="06/01/2021")+class Baz:+ """The Baz class."""++ def __init__(self):+ pass+++@deprecated(since="0.7.0", until="0.9.0-rc2")+class Qux:+ def __init__(self):+ pass+++@deprecated(message="Use something else.")+class Quux:+ def __init__(self):+ pass+++@deprecated(replacement="ReplaceQuuz")+class Quuz:+ def __init__(self):+ pass+++class ReplaceQuuz:+ def __init__(self):+ pass+++@deprecated(+ since="0.7.0",+ until="1.2.1",+ replacement="ReplaceQuuz",+ message="Don't use this please.",+)+class QuuzAll:+ def __init__(self):+ pass+++doc_admonition = "\n\n.. admonition:: Deprecated\n :class: attention\n\n "+++def test_deprecate_class_no_args(caplog):+ """Test the deprecation of a class (decorator with no arguments)."""+ f = Foo()+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The class Foo has been deprecated and may be removed in a later version."+ )+ assert f.__doc__ == f"{doc_admonition}{msg}"+++def test_deprecate_class_since(caplog):+ """Test the deprecation of a class (decorator with since argument)."""+ b = Bar()+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The class Bar has been deprecated since v0.6.0 and may be removed in a later version."+ )+ assert b.__doc__ == f"The Bar class.{doc_admonition}{msg}"+++def test_deprecate_class_until(caplog):+ """Test the deprecation of a class (decorator with until argument)."""+ bz = Baz()+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The class Baz has been deprecated and is expected to be removed after 06/01/2021."+ )+ assert bz.__doc__ == f"The Baz class.{doc_admonition}{msg}"+++def test_deprecate_class_since_and_until(caplog):+ """Test the deprecation of a class (decorator with since and until arguments)."""+ qx = Qux()+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The class Qux has been deprecated since 0.7.0 and is expected to be removed after 0.9.0-rc2."+ )+ assert qx.__doc__ == f"{doc_admonition}{msg}"+++def test_deprecate_class_msg(caplog):+ """Test the deprecation of a class (decorator with msg argument)."""+ qu = Quux()+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The class Quux has been deprecated and may be removed in a later version. Use something else."+ )+ assert qu.__doc__ == f"{doc_admonition}{msg}"+++def test_deprecate_class_replacement(caplog):+ """Test the deprecation of a class (decorator with replacement argument)."""+ qz = Quuz()+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The class Quuz has been deprecated and may be removed in a later version. Use ReplaceQuuz instead."+ )+ doc_msg = "The class Quuz has been deprecated and may be removed in a later version. Use :class:`~.ReplaceQuuz` instead."+ assert qz.__doc__ == f"{doc_admonition}{doc_msg}"+++def test_deprecate_class_all(caplog):+ """Test the deprecation of a class (decorator with all arguments)."""+ qza = QuuzAll()+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The class QuuzAll has been deprecated since 0.7.0 and is expected to be removed after 1.2.1. Use ReplaceQuuz instead. Don't use this please."+ )+ doc_msg = "The class QuuzAll has been deprecated since 0.7.0 and is expected to be removed after 1.2.1. Use :class:`~.ReplaceQuuz` instead. Don't use this please."+ assert qza.__doc__ == f"{doc_admonition}{doc_msg}"+++def _get_caplog_record_msg(caplog):+ logger_name, level, message = caplog.record_tuples[0]+ return message+++@deprecated+def useless(**kwargs):+ pass+++class Top:+ def __init__(self):+ pass++ @deprecated(since="0.8.0", message="This method is useless.")+ def mid_func(self):+ """Middle function in Top."""++ pass++ @deprecated(until="1.4.0", replacement="Top.NewNested")+ class Nested:+ def __init__(self):+ pass++ class NewNested:+ def __init__(self):+ pass++ @deprecated(since="1.0.0", until="12/25/2025")+ def nested_func(self):+ """Nested function in Top.NewNested."""++ pass++ class Bottom:+ def __init__(self):+ pass++ def normal_func(self):+ @deprecated+ def nested_func(self):+ pass++ return nested_func++ @deprecated_params(params="a, b, c", message="Use something else.")+ def foo(self, **kwargs):+ pass++ @deprecated_params(params="a", since="v0.2", until="v0.4")+ def bar(self, **kwargs):+ pass++ @deprecated_params(redirections=[("old_param", "new_param")])+ def baz(self, **kwargs):+ return kwargs++ @deprecated_params(+ redirections=[lambda runtime_in_ms: {"run_time": runtime_in_ms / 1000}]+ )+ def qux(self, **kwargs):+ return kwargs++ @deprecated_params(+ redirections=[+ lambda point2D_x=1, point2D_y=1: {"point2D": (point2D_x, point2D_y)}+ ]+ )+ def quux(self, **kwargs):+ return kwargs++ @deprecated_params(+ redirections=[+ lambda point2D=1: {"x": point2D[0], "y": point2D[1]}+ if isinstance(point2D, tuple)+ else {"x": point2D, "y": point2D}+ ]+ )+ def quuz(self, **kwargs):+ return kwargs+++def test_deprecate_func_no_args(caplog):+ """Test the deprecation of a method (decorator with no arguments)."""+ useless()+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The function useless has been deprecated and may be removed in a later version."+ )+ assert useless.__doc__ == f"{doc_admonition}{msg}"+++def test_deprecate_func_in_class_since_and_message(caplog):+ """Test the deprecation of a method within a class (decorator with since and message arguments)."""+ t = Top()+ t.mid_func()+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The method Top.mid_func has been deprecated since 0.8.0 and may be removed in a later version. This method is useless."+ )+ assert t.mid_func.__doc__ == f"Middle function in Top.{doc_admonition}{msg}"+++def test_deprecate_nested_class_until_and_replacement(caplog):+ """Test the deprecation of a nested class (decorator with until and replacement arguments)."""+ n = Top().Nested()+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The class Top.Nested has been deprecated and is expected to be removed after 1.4.0. Use Top.NewNested instead."+ )+ doc_msg = "The class Top.Nested has been deprecated and is expected to be removed after 1.4.0. Use :class:`~.Top.NewNested` instead."+ assert n.__doc__ == f"{doc_admonition}{doc_msg}"+++def test_deprecate_nested_class_func_since_and_until(caplog):+ """Test the deprecation of a method within a nested class (decorator with since and until arguments)."""+ n = Top().NewNested()+ n.nested_func()+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The method Top.NewNested.nested_func has been deprecated since 1.0.0 and is expected to be removed after 12/25/2025."+ )+ assert (+ n.nested_func.__doc__+ == f"Nested function in Top.NewNested.{doc_admonition}{msg}"+ )+++def test_deprecate_nested_func(caplog):+ """Test the deprecation of a nested method (decorator with no arguments)."""+ b = Top().Bottom()+ ans = b.normal_func()+ ans(1)+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The method Top.Bottom.normal_func.<locals>.nested_func has been deprecated and may be removed in a later version."+ )+ assert ans.__doc__ == f"{doc_admonition}{msg}"+++def test_deprecate_func_params(caplog):+ """Test the deprecation of method parameters (decorator with params argument)."""+ t = Top()+ t.foo(a=2, b=3, z=4)+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The parameters a and b of method Top.foo have been deprecated and may be removed in a later version. Use something else."+ )+++def test_deprecate_func_single_param_since_and_until(caplog):+ """Test the deprecation of a single method parameter (decorator with since and until arguments)."""+ t = Top()+ t.bar(a=1, b=2)+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The parameter a of method Top.bar has been deprecated since v0.2 and is expected to be removed after v0.4."+ )+++def test_deprecate_func_param_redirect_tuple(caplog):+ """Test the deprecation of a method parameter and redirecting it to a new one using tuple."""+ t = Top()+ obj = t.baz(x=1, old_param=2)+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The parameter old_param of method Top.baz has been deprecated and may be removed in a later version."+ )+ assert obj == {"x": 1, "new_param": 2}+++def test_deprecate_func_param_redirect_lambda(caplog):+ """Test the deprecation of a method parameter and redirecting it to a new one using lambda function."""+ t = Top()+ obj = t.qux(runtime_in_ms=500)+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The parameter runtime_in_ms of method Top.qux has been deprecated and may be removed in a later version."+ )+ assert obj == {"run_time": 0.5}+++def test_deprecate_func_param_redirect_many_to_one(caplog):+ """Test the deprecation of multiple method parameters and redirecting them to one."""+ t = Top()+ obj = t.quux(point2D_x=3, point2D_y=5)+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The parameters point2D_x and point2D_y of method Top.quux have been deprecated and may be removed in a later version."+ )+ assert obj == {"point2D": (3, 5)}+++def test_deprecate_func_param_redirect_one_to_many(caplog):+ """Test the deprecation of one method parameter and redirecting it to many."""+ t = Top()+ obj1 = t.quuz(point2D=0)+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The parameter point2D of method Top.quuz has been deprecated and may be removed in a later version."+ )+ assert obj1 == {"x": 0, "y": 0}++ caplog.clear()++ obj2 = t.quuz(point2D=(2, 3))+ assert len(caplog.record_tuples) == 1+ msg = _get_caplog_record_msg(caplog)+ assert (+ msg+ == "The parameter point2D of method Top.quuz has been deprecated and may be removed in a later version."+ )+ assert obj2 == {"x": 2, "y": 3}