A community-maintained Python framework for creating mathematical animations.
Convert all types of parameters in docstrings to proper type annotations (#2988)
NotWearingPants95bca6f24b42
diff --git a/manim/_config/__init__.py b/manim/_config/__init__.pyindex ebcca2d55..94bea642a 100644--- a/manim/_config/__init__.py+++ b/manim/_config/__init__.py@@ -49,7 +49,7 @@ def tempconfig(temp: ManimConfig | dict) -> _GeneratorContextManager:Parameters----------- temp : Union[:class:`ManimConfig`, :class:`dict`]+ tempObject whose keys will be used to temporarily update the global``config``.diff --git a/manim/_config/logger_utils.py b/manim/_config/logger_utils.pyindex 64b341b7b..ca31b4fa5 100644--- a/manim/_config/logger_utils.py+++ b/manim/_config/logger_utils.py@@ -56,10 +56,10 @@ def make_logger(Parameters----------- parser : :class:`configparser.ConfigParser`+ parserA parser containing any .cfg files in use.- verbosity : :class:`str`+ verbosityThe verbosity level of the logger.Returns@@ -106,7 +106,7 @@ def parse_theme(parser: configparser.ConfigParser) -> Theme:Parameters----------- parser : :class:`configparser.ConfigParser`+ parserA parser containing any .cfg files in use.Returns@@ -148,9 +148,12 @@ def set_file_logger(scene_name: str, module_name: str, log_dir: Path) -> None:Parameters----------- config : :class:`ManimConfig`- The global config, used to determine the log file path.-+ scene_name+ The name of the scene, used in the name of the log file.+ module_name+ The name of the module, used in the name of the log file.+ log_dir+ Path to the folder where log files are stored."""# Note: The log file name will be# <name_of_animation_file>_<name_of_scene>.log, gotten from config. So itdiff --git a/manim/_config/utils.py b/manim/_config/utils.pyindex 1e3bea7d5..723a94ba8 100644--- a/manim/_config/utils.py+++ b/manim/_config/utils.py@@ -342,7 +342,7 @@ class ManimConfig(MutableMapping):Parameters----------- obj : Union[:class:`ManimConfig`, :class:`dict`]+ objThe object to copy values from.Returns@@ -490,7 +490,7 @@ class ManimConfig(MutableMapping):Parameters----------- parser : :class:`ConfigParser`+ parserAn object reflecting the contents of one or many ``.cfg`` files. Inparticular, it may reflect the contents of multiple files that havebeen parsed in a cascading fashion.@@ -664,7 +664,7 @@ class ManimConfig(MutableMapping):Parameters----------- args : :class:`argparse.Namespace`+ argsAn object returned by :func:`.main_utils.parse_args()`.Returns@@ -1316,11 +1316,11 @@ class ManimConfig(MutableMapping):Parameters----------- key : :class:`str`+ keyThe config option to be resolved. Must be an option ending in``'_dir'``, for example ``'media_dir'`` or ``'video_dir'``.- kwargs : :class:`str`+ kwargsAny strings to be used when resolving the directory.Returnsdiff --git a/manim/animation/animation.py b/manim/animation/animation.pyindex 65b45c300..b35c67405 100644--- a/manim/animation/animation.py+++ b/manim/animation/animation.py@@ -415,9 +415,8 @@ class Animation:Parameters----------- run_time- The new time the animation should take in seconds.-+ rate_func+ The new function defining the animation progress based on the relative runtime (see :mod:`~.rate_functions`).Returns-------diff --git a/manim/animation/creation.py b/manim/animation/creation.pyindex 46c5ad9fa..541a2afaf 100644--- a/manim/animation/creation.py+++ b/manim/animation/creation.py@@ -138,7 +138,7 @@ class Create(ShowPartial):Parameters----------- mobject : :class:`~.VMobject`+ mobjectThe VMobject to animate.Raises@@ -374,7 +374,7 @@ class Unwrite(Write):Parameters----------- reverse : :class:`bool`+ reverseSet True to have the animation start erasing from the last submobject first.Examples@@ -542,7 +542,7 @@ class AddTextLetterByLetter(ShowIncreasingSubsets):Parameters----------- time_per_char : :class:`float`+ time_per_charFrequency of appearance of the letters... tip::@@ -585,7 +585,7 @@ class RemoveTextLetterByLetter(AddTextLetterByLetter):Parameters----------- time_per_char : :class:`float`+ time_per_charFrequency of appearance of the letters... tip::diff --git a/manim/animation/indication.py b/manim/animation/indication.pyindex d320ec3a4..405581025 100644--- a/manim/animation/indication.py+++ b/manim/animation/indication.py@@ -77,7 +77,7 @@ class FocusOn(Transform):The color of the spotlight.run_timeThe duration of the animation.- kwargs : Any+ kwargsAdditional arguments to be passed to the :class:`~.Succession` constructorExamples@@ -132,7 +132,7 @@ class Indicate(Transform):The color the mobject temporally takes.rate_funcThe function definig the animation progress at every point in time.- kwargs : Any+ kwargsAdditional arguments to be passed to the :class:`~.Succession` constructorExamples@@ -186,7 +186,7 @@ class Flash(AnimationGroup):The time width used for the flash lines. See :class:`.~ShowPassingFlash` for more details.run_timeThe duration of the animation.- kwargs : Any+ kwargsAdditional arguments to be passed to the :class:`~.Succession` constructorExamples@@ -486,7 +486,7 @@ class Wiggle(Animation):Parameters----------- mobject : Mobject+ mobjectThe mobject to wiggle.scale_valueThe factor by which the mobject will be temporarily scaled.@@ -581,7 +581,7 @@ class Circumscribe(Succession):The color of the surrounding shape.run_timeThe duration of the entire animation.- kwargs : Any+ kwargsAdditional arguments to be passed to the :class:`~.Succession` constructorExamplesdiff --git a/manim/camera/camera.py b/manim/camera/camera.pyindex 81dfa78d0..cdc625cc2 100644--- a/manim/camera/camera.py+++ b/manim/camera/camera.py@@ -11,7 +11,7 @@ import operator as opimport pathlibimport timefrom functools import reduce-from typing import Any+from typing import Any, Callable, Iterableimport cairoimport numpy as np@@ -36,42 +36,38 @@ class Camera:This is the object which takes care of what exactly is displayedon screen at any given moment.-- Some important configuration values and local variables to note are:-- background_image : :class:`str`, optional- The path to an image that should be the background image.- If not set, the background is filled with `self.background_color`-- pixel_height : :class:`int`, optional- The height of the scene in pixels.-"""def __init__(self,- background_image=None,- frame_center=ORIGIN,- image_mode="RGBA",- n_channels=4,- pixel_array_dtype="uint8",- z_buff_func=lambda m: np.round(m.get_center()[2], 2),- cairo_line_width_multiple=0.01,- use_z_index=True,- background=None,- pixel_height=None,- pixel_width=None,- frame_height=None,- frame_width=None,- frame_rate=None,+ background_image: str | None = None,+ frame_center: np.ndarray = ORIGIN,+ image_mode: str = "RGBA",+ n_channels: int = 4,+ pixel_array_dtype: str = "uint8",+ cairo_line_width_multiple: float = 0.01,+ use_z_index: bool = True,+ background: np.ndarray | None = None,+ pixel_height: int | None = None,+ pixel_width: int | None = None,+ frame_height: float | None = None,+ frame_width: float | None = None,+ frame_rate: float | None = None,**kwargs,):"""Initialises the Camera.Parameters----------- background : optional+ background_image+ The path to an image that should be the background image.+ If not set, the background is filled with `self.background_color`+ backgroundWhat self.background should be, by default None as will be set later.+ pixel_height+ The height of the scene in pixels.+ pixel_width+ The width of the scene in pixels.**kwargsAny local variables to be set."""@@ -80,7 +76,6 @@ class Camera:self.image_mode = image_modeself.n_channels = n_channelsself.pixel_array_dtype = pixel_array_dtype- self.z_buff_func = z_buff_funcself.cairo_line_width_multiple = cairo_line_width_multipleself.use_z_index = use_z_indexself.background = background@@ -149,7 +144,7 @@ class Camera:self._background_opacity = alphaself.init_background()- def type_or_raise(self, mobject):+ def type_or_raise(self, mobject: Mobject):"""Return the type of mobject, if it is a type that can be rendered.If `mobject` is an instance of a class that inherits from a class that@@ -159,7 +154,7 @@ class Camera:Parameters----------- mobject : :class:`~.Mobject`+ mobjectThe object to take the type of.Notes@@ -190,15 +185,15 @@ class Camera:return _typeraise TypeError(f"Displaying an object of class {_type} is not supported")- def reset_pixel_shape(self, new_height, new_width):+ def reset_pixel_shape(self, new_height: float, new_width: float):"""This method resets the height and widthof a single pixel to the passed new_height and new_width.Parameters----------- new_height : int, float+ new_heightThe new height of the entire scene in pixels- new_width : int, float+ new_widthThe new width of the entire scene in pixels"""self.pixel_width = new_width@@ -207,7 +202,7 @@ class Camera:self.resize_frame_shape()self.reset()- def resize_frame_shape(self, fixed_dimension=0):+ def resize_frame_shape(self, fixed_dimension: int = 0):"""Changes frame_shape to match the aspect ratioof the pixels, where fixed_dimension determines@@ -216,7 +211,7 @@ class Camera:Parameters----------- fixed_dimension : int+ fixed_dimensionIf 0, height is scaled with respect to widthelse, width is scaled with respect to height."""@@ -258,14 +253,14 @@ class Camera:)self.background[:, :] = background_rgba- def get_image(self, pixel_array=None):+ def get_image(self, pixel_array: np.ndarray | list | tuple | None = None):"""Returns an image from the passedpixel array, or from the current frameif the passed pixel array is none.Parameters----------- pixel_array : np.array, list, tuple, optional+ pixel_arrayThe pixel array from which to get an image, by default NoneReturns@@ -277,15 +272,17 @@ class Camera:pixel_array = self.pixel_arrayreturn Image.fromarray(pixel_array, mode=self.image_mode)- def convert_pixel_array(self, pixel_array, convert_from_floats=False):+ def convert_pixel_array(+ self, pixel_array: np.ndarray | list | tuple, convert_from_floats: bool = False+ ):"""Converts a pixel array from values that have floats in thento proper RGB values.Parameters----------- pixel_array : np.array, list, tuple+ pixel_arrayPixel array to convert.- convert_from_floats : bool, optional+ convert_from_floatsWhether or not to convert float values to ints, by default FalseReturns@@ -302,14 +299,16 @@ class Camera:)return retval- def set_pixel_array(self, pixel_array, convert_from_floats=False):+ def set_pixel_array(+ self, pixel_array: np.ndarray | list | tuple, convert_from_floats: bool = False+ ):"""Sets the pixel array of the camera to the passed pixel array.Parameters----------- pixel_array : np.array, list, tuple+ pixel_arrayThe pixel array to convert and then set as the camera's pixel array.- convert_from_floats : bool, optional+ convert_from_floatsWhether or not to convert float values to proper RGB values, by default False"""converted_array = self.convert_pixel_array(pixel_array, convert_from_floats)@@ -322,21 +321,25 @@ class Camera:# Set in placeself.pixel_array[:, :, :] = converted_array[:, :, :]- def set_background(self, pixel_array, convert_from_floats=False):+ def set_background(+ self, pixel_array: np.ndarray | list | tuple, convert_from_floats: bool = False+ ):"""Sets the background to the passed pixel_array after convertingto valid RGB values.Parameters----------- pixel_array : np.array, list, tuple+ pixel_arrayThe pixel array to set the background to.- convert_from_floats : bool, optional+ convert_from_floatsWhether or not to convert floats values to proper RGB valid ones, by default False"""self.background = self.convert_pixel_array(pixel_array, convert_from_floats)# TODO, this should live in utils, not as a method of Camera- def make_background_from_func(self, coords_to_colors_func):+ def make_background_from_func(+ self, coords_to_colors_func: Callable[[np.ndarray], np.ndarray]+ ):"""Makes a pixel array for the background by using coords_to_colors_func to determine each pixel's color. Each inputpixel's color. Each input to coords_to_colors_func is an (x, y) pair in space (in ordinary space coordinates; not@@ -344,7 +347,7 @@ class Camera:Parameters----------- coords_to_colors_func : function+ coords_to_colors_funcThe function whose input is an (x,y) pair of coordinates andwhose return values must be the colors for that point@@ -361,7 +364,9 @@ class Camera:return self.convert_pixel_array(new_background, convert_from_floats=True)- def set_background_from_func(self, coords_to_colors_func):+ def set_background_from_func(+ self, coords_to_colors_func: Callable[[np.ndarray], np.ndarray]+ ):"""Sets the background to a pixel array using coords_to_colors_func to determine each pixel's color. Each inputpixel's color. Each input to coords_to_colors_func is an (x, y) pair in space (in ordinary space coordinates; not@@ -369,7 +374,7 @@ class Camera:Parameters----------- coords_to_colors_func : function+ coords_to_colors_funcThe function whose input is an (x,y) pair of coordinates andwhose return values must be the colors for that point"""@@ -383,7 +388,7 @@ class Camera:-------CameraThe camera object after setting the pixel array.- """ ""+ """self.set_pixel_array(self.background)return self@@ -394,20 +399,20 @@ class Camera:def get_mobjects_to_display(self,- mobjects,- include_submobjects=True,- excluded_mobjects=None,+ mobjects: Iterable[Mobject],+ include_submobjects: bool = True,+ excluded_mobjects: list | None = None,):"""Used to get the list of mobjects to displaywith the camera.Parameters----------- mobjects : Mobject+ mobjectsThe Mobjects- include_submobjects : bool, optional+ include_submobjectsWhether or not to include the submobjects of mobjects, by default True- excluded_mobjects : list, optional+ excluded_mobjectsAny mobjects to exclude, by default NoneReturns@@ -427,15 +432,15 @@ class Camera:use_z_index=self.use_z_index,)mobjects = list_difference_update(mobjects, all_excluded)- return mobjects+ return list(mobjects)- def is_in_frame(self, mobject):+ def is_in_frame(self, mobject: Mobject):"""Checks whether the passed mobject is inframe or not.Parameters----------- mobject : Mobject+ mobjectThe mobject for which the checking needs to be done.Returns@@ -472,7 +477,7 @@ class Camera:"""return self.capture_mobjects([mobject], **kwargs)- def capture_mobjects(self, mobjects, **kwargs):+ def capture_mobjects(self, mobjects: Iterable[Mobject], **kwargs):"""Capture mobjects by printing them on :attr:`pixel_array`.This is the essential function that converts the contents of a Scene@@ -480,10 +485,10 @@ class Camera:Parameters----------- mobjects : :class:`~.Mobject`+ mobjectsMobjects to capture.- kwargs : Any+ kwargsKeyword arguments to be passed to :meth:`get_mobjects_to_display`.Notes@@ -507,13 +512,13 @@ class Camera:# NOTE: None of the methods below have been mentioned outside of their definitions. Their DocStrings are not as# detailed as possible.- def get_cached_cairo_context(self, pixel_array):+ def get_cached_cairo_context(self, pixel_array: np.ndarray):"""Returns the cached cairo context of the passedpixel array if it exists, and None if it doesn't.Parameters----------- pixel_array : np.array+ pixel_arrayThe pixel array to check.Returns@@ -523,19 +528,19 @@ class Camera:"""return self.pixel_array_to_cairo_context.get(id(pixel_array), None)- def cache_cairo_context(self, pixel_array, ctx):+ def cache_cairo_context(self, pixel_array: np.ndarray, ctx: cairo.Context):"""Caches the passed Pixel array into a Cairo ContextParameters----------- pixel_array : np.array+ pixel_arrayThe pixel array to cache- ctx : cairo.Context+ ctxThe context to cache it into."""self.pixel_array_to_cairo_context[id(pixel_array)] = ctx- def get_cairo_context(self, pixel_array):+ def get_cairo_context(self, pixel_array: np.ndarray):"""Returns the cairo context for a pixel array aftercaching it to self.pixel_array_to_cairo_contextIf that array has already been cached, it returns the@@ -543,7 +548,7 @@ class Camera:Parameters----------- pixel_array : np.array+ pixel_arrayThe Pixel array to get the cairo context of.Returns@@ -580,14 +585,16 @@ class Camera:self.cache_cairo_context(pixel_array, ctx)return ctx- def display_multiple_vectorized_mobjects(self, vmobjects, pixel_array):+ def display_multiple_vectorized_mobjects(+ self, vmobjects: list, pixel_array: np.ndarray+ ):"""Displays multiple VMobjects in the pixel_arrayParameters----------- vmobjects : list+ vmobjectslist of VMobjects to display- pixel_array : np.array+ pixel_arrayThe pixel array"""if len(vmobjects) == 0:@@ -602,29 +609,31 @@ class Camera:pixel_array,)- def display_multiple_non_background_colored_vmobjects(self, vmobjects, pixel_array):+ def display_multiple_non_background_colored_vmobjects(+ self, vmobjects: list, pixel_array: np.ndarray+ ):"""Displays multiple VMobjects in the cairo context, as long as they don't havebackground colors.Parameters----------- vmobjects : list+ vmobjectslist of the VMobjects- pixel_array : np.ndarray+ pixel_arrayThe Pixel array to add the VMobjects to."""ctx = self.get_cairo_context(pixel_array)for vmobject in vmobjects:self.display_vectorized(vmobject, ctx)- def display_vectorized(self, vmobject, ctx):+ def display_vectorized(self, vmobject: VMobject, ctx: cairo.Context):"""Displays a VMobject in the cairo contextParameters----------- vmobject : VMobject+ vmobjectThe Vectorized Mobject to display- ctx : cairo.Context+ ctxThe cairo context to use.Returns@@ -638,14 +647,14 @@ class Camera:self.apply_stroke(ctx, vmobject)return self- def set_cairo_context_path(self, ctx, vmobject):+ def set_cairo_context_path(self, ctx: cairo.Context, vmobject: VMobject):"""Sets a path for the cairo context with the vmobject passedParameters----------- ctx : cairo.Context+ ctxThe cairo context- vmobject : VMobject+ vmobjectThe VMobjectReturns@@ -672,16 +681,18 @@ class Camera:ctx.close_path()return self- def set_cairo_context_color(self, ctx, rgbas, vmobject):+ def set_cairo_context_color(+ self, ctx: cairo.Context, rgbas: np.ndarray, vmobject: VMobject+ ):"""Sets the color of the cairo contextParameters----------- ctx : cairo.Context+ ctxThe cairo context- rgbas : np.ndarray+ rgbasThe RGBA array with which to color the context.- vmobject : VMobject+ vmobjectThe VMobject with which to set the color.Returns@@ -704,14 +715,14 @@ class Camera:ctx.set_source(pat)return self- def apply_fill(self, ctx, vmobject):+ def apply_fill(self, ctx: cairo.Context, vmobject: VMobject):"""Fills the cairo contextParameters----------- ctx : cairo.Context+ ctxThe cairo context- vmobject : VMobject+ vmobjectThe VMobjectReturns@@ -723,16 +734,18 @@ class Camera:ctx.fill_preserve()return self- def apply_stroke(self, ctx, vmobject, background=False):+ def apply_stroke(+ self, ctx: cairo.Context, vmobject: VMobject, background: bool = False+ ):"""Applies a stroke to the VMobject in the cairo context.Parameters----------- ctx : cairo.Context+ ctxThe cairo context- vmobject : VMobject+ vmobjectThe VMobject- background : bool, optional+ backgroundWhether or not to consider the background when applying thisstroke width, by default False@@ -758,15 +771,15 @@ class Camera:ctx.stroke_preserve()return self- def get_stroke_rgbas(self, vmobject, background=False):+ def get_stroke_rgbas(self, vmobject: VMobject, background: bool = False):"""Gets the RGBA array for the stroke of the passedVMobject.Parameters----------- vmobject : VMobject+ vmobjectThe VMobject- background : bool, optional+ backgroundWhether or not to consider the background when getting the strokeRGBAs, by default False@@ -777,12 +790,12 @@ class Camera:"""return vmobject.get_stroke_rgbas(background)- def get_fill_rgbas(self, vmobject):+ def get_fill_rgbas(self, vmobject: VMobject):"""Returns the RGBA array of the fill of the passed VMobjectParameters----------- vmobject : VMobject+ vmobjectThe VMobjectReturns@@ -808,14 +821,16 @@ class Camera:setattr(self, bcvd, BackgroundColoredVMobjectDisplayer(self))return getattr(self, bcvd)- def display_multiple_background_colored_vmobjects(self, cvmobjects, pixel_array):+ def display_multiple_background_colored_vmobjects(+ self, cvmobjects: list, pixel_array: np.ndarray+ ):"""Displays multiple vmobjects that have the same color as the background.Parameters----------- cvmobjects : list+ cvmobjectsList of Colored VMobjects- pixel_array : np.array+ pixel_arrayThe pixel array.Returns@@ -833,14 +848,16 @@ class Camera:# NOTE: Out of the following methods, only `transform_points_pre_display` and `points_to_pixel_coords` have been mentioned outside of their definitions.# As a result, the other methods do not have as detailed docstrings as would be preferred.- def display_multiple_point_cloud_mobjects(self, pmobjects, pixel_array):+ def display_multiple_point_cloud_mobjects(+ self, pmobjects: list, pixel_array: np.ndarray+ ):"""Displays multiple PMobjects by modifying the passed pixel array.Parameters----------- pmobjects : list+ pmobjectsList of PMobjects- pixel_array : np.array+ pixel_arrayThe pixel array to modify."""for pmobject in pmobjects:@@ -852,20 +869,27 @@ class Camera:pixel_array,)- def display_point_cloud(self, pmobject, points, rgbas, thickness, pixel_array):+ def display_point_cloud(+ self,+ pmobject: PMobject,+ points: list,+ rgbas: np.ndarray,+ thickness: float,+ pixel_array: np.ndarray,+ ):"""Displays a PMobject by modifying the Pixel array suitably..TODO: Write a description for the rgbas argument.Parameters----------- pmobject : PMobject+ pmobjectPoint Cloud Mobject- points : list+ pointsThe points to display in the point cloud mobject- rgbas : np.array+ rgbas- thickness : int, float+ thicknessThe thickness of each point of the PMobject- pixel_array : np.array+ pixel_arrayThe pixel array to modify."""@@ -896,27 +920,31 @@ class Camera:new_pa[indices] = rgbaspixel_array[:, :] = new_pa.reshape((ph, pw, rgba_len))- def display_multiple_image_mobjects(self, image_mobjects, pixel_array):+ def display_multiple_image_mobjects(+ self, image_mobjects: list, pixel_array: np.ndarray+ ):"""Displays multiple image mobjects by modifying the passed pixel_array.Parameters----------- image_mobjects : list+ image_mobjectslist of ImageMobjects- pixel_array : np.array+ pixel_arrayThe pixel array to modify."""for image_mobject in image_mobjects:self.display_image_mobject(image_mobject, pixel_array)- def display_image_mobject(self, image_mobject: AbstractImageMobject, pixel_array):+ def display_image_mobject(+ self, image_mobject: AbstractImageMobject, pixel_array: np.ndarray+ ):"""Displays an ImageMobject by changing the pixel_array suitably.Parameters----------- image_mobject : ImageMobject+ image_mobjectThe imageMobject to display- pixel_array : np.ndarray+ pixel_arrayThe Pixel array to put the imagemobject in."""corner_coords = self.points_to_pixel_coords(image_mobject, image_mobject.points)@@ -966,26 +994,26 @@ class Camera:# Paint on top of existing pixel arrayself.overlay_PIL_image(pixel_array, full_image)- def overlay_rgba_array(self, pixel_array, new_array):+ def overlay_rgba_array(self, pixel_array: np.ndarray, new_array: np.ndarray):"""Overlays an RGBA array on top of the given Pixel array.Parameters----------- pixel_array : np.array+ pixel_arrayThe original pixel array to modify.- new_array : np.array+ new_arrayThe new pixel array to overlay."""self.overlay_PIL_image(pixel_array, self.get_image(new_array))- def overlay_PIL_image(self, pixel_array, image):+ def overlay_PIL_image(self, pixel_array: np.ndarray, image: Image):"""Overlays a PIL image on the passed pixel array.Parameters----------- pixel_array : np.ndarray+ pixel_arrayThe Pixel array- image : PIL.Image+ imageThe Image to overlay."""pixel_array[:, :] = np.array(@@ -993,13 +1021,13 @@ class Camera:dtype="uint8",)- def adjust_out_of_range_points(self, points):+ def adjust_out_of_range_points(self, points: np.ndarray):"""If any of the points in the passed array are out ofthe viable range, they are adjusted suitably.Parameters----------- points : np.array+ pointsThe points to adjustReturns@@ -1061,13 +1089,13 @@ class Camera:result[:, 1] = shifted_points[:, 1] * height_mult + height_addreturn result.astype("int")- def on_screen_pixels(self, pixel_coords):+ def on_screen_pixels(self, pixel_coords: np.ndarray):"""Returns array of pixels that are on the screen from a givenarray of pixel_coordinatesParameters----------- pixel_coords : np.array+ pixel_coordsThe pixel coords to check.Returns@@ -1085,12 +1113,12 @@ class Camera:],)- def adjusted_thickness(self, thickness):+ def adjusted_thickness(self, thickness: float):"""Parameters----------- thickness : int, float+ thicknessReturns-------@@ -1103,12 +1131,12 @@ class Camera:factor = big_sum / this_sumreturn 1 + (thickness - 1) * factor- def get_thickening_nudges(self, thickness):+ def get_thickening_nudges(self, thickness: float):"""Parameters----------- thickness : int, float+ thicknessReturns-------@@ -1119,15 +1147,15 @@ class Camera:_range = list(range(-thickness // 2 + 1, thickness // 2 + 1))return np.array(list(it.product(_range, _range)))- def thickened_coordinates(self, pixel_coords, thickness):+ def thickened_coordinates(self, pixel_coords: np.ndarray, thickness: float):"""Returns thickened coordinates for a passed array of pixel coords anda thickness to thicken by.Parameters----------- pixel_coords : np.array+ pixel_coordsPixel coordinates- thickness : int, float+ thicknessThicknessReturns@@ -1178,11 +1206,11 @@ class Camera:# NOTE: The methods of the following class have not been mentioned outside of their definitions.# Their DocStrings are not as detailed as preferred.class BackgroundColoredVMobjectDisplayer:- def __init__(self, camera):+ def __init__(self, camera: Camera):"""Parameters----------- camera : Camera+ cameraCamera object to use."""self.camera = camera@@ -1195,22 +1223,22 @@ class BackgroundColoredVMobjectDisplayer:def resize_background_array(self,- background_array,- new_width,- new_height,- mode="RGBA",+ background_array: np.ndarray,+ new_width: float,+ new_height: float,+ mode: str = "RGBA",):"""Resizes the pixel array representing the background.Parameters----------- background_array : np.array+ background_arrayThe pixel- new_width : int, float+ new_widthThe new width of the background- new_height : int, float+ new_heightThe new height of the background- mode : str, optional+ modeThe PIL image mode, by default "RGBA"Returns@@ -1223,14 +1251,16 @@ class BackgroundColoredVMobjectDisplayer:resized_image = image.resize((new_width, new_height))return np.array(resized_image)- def resize_background_array_to_match(self, background_array, pixel_array):+ def resize_background_array_to_match(+ self, background_array: np.ndarray, pixel_array: np.ndarray+ ):"""Resizes the background array to match the passed pixel array.Parameters----------- background_array : np.array+ background_arrayThe prospective pixel array.- pixel_array : np.array+ pixel_arrayThe pixel array whose width and height should be matched.Returns@@ -1271,12 +1301,12 @@ class BackgroundColoredVMobjectDisplayer:self.file_name_to_pixel_array_map[image_key] = back_arrayreturn back_array- def display(self, *cvmobjects):+ def display(self, *cvmobjects: VMobject):"""Displays the colored VMobjects.Parameters----------- *cvmobjects : VMobject+ *cvmobjectsThe VMobjectsReturnsdiff --git a/manim/camera/moving_camera.py b/manim/camera/moving_camera.pyindex 22d6be22e..1d01d01e2 100644--- a/manim/camera/moving_camera.py+++ b/manim/camera/moving_camera.py@@ -10,6 +10,8 @@ from __future__ import annotations__all__ = ["MovingCamera"]+import numpy as np+from .. import configfrom ..camera.camera import Camerafrom ..constants import DOWN, LEFT, RIGHT, UP@@ -87,34 +89,34 @@ class MovingCamera(Camera):return self.frame.get_center()@frame_height.setter- def frame_height(self, frame_height):+ def frame_height(self, frame_height: float):"""Sets the height of the frame in MUnits.Parameters----------- frame_height : int, float+ frame_heightThe new frame_height."""self.frame.stretch_to_fit_height(frame_height)@frame_width.setter- def frame_width(self, frame_width):+ def frame_width(self, frame_width: float):"""Sets the width of the frame in MUnits.Parameters----------- frame_width : int, float+ frame_widthThe new frame_width."""self.frame.stretch_to_fit_width(frame_width)@frame_center.setter- def frame_center(self, frame_center):+ def frame_center(self, frame_center: np.ndarray | list | tuple | Mobject):"""Sets the centerpoint of the frame.Parameters----------- frame_center : np.array, list, tuple, Mobject+ frame_centerThe point to which the frame must be moved.If is of type mobject, the frame will be moved tothe center of that mobject.diff --git a/manim/camera/multi_camera.py b/manim/camera/multi_camera.pyindex a9eb74969..a5202135e 100644--- a/manim/camera/multi_camera.py+++ b/manim/camera/multi_camera.py@@ -5,6 +5,8 @@ from __future__ import annotations__all__ = ["MultiCamera"]+from manim.mobject.types.image_mobject import ImageMobject+from ..camera.moving_camera import MovingCamerafrom ..utils.iterables import list_difference_update@@ -14,7 +16,7 @@ class MultiCamera(MovingCamera):def __init__(self,- image_mobjects_from_cameras=None,+ image_mobjects_from_cameras: ImageMobject | None = None,allow_cameras_to_capture_their_own_display=False,**kwargs,):@@ -22,7 +24,7 @@ class MultiCamera(MovingCamera):Parameters----------- image_mobjects_from_cameras : ImageMobject+ image_mobjects_from_cameraskwargsAny valid keyword arguments of MovingCamera.@@ -36,13 +38,13 @@ class MultiCamera(MovingCamera):)super().__init__(**kwargs)- def add_image_mobject_from_camera(self, image_mobject_from_camera):+ def add_image_mobject_from_camera(self, image_mobject_from_camera: ImageMobject):"""Adds an ImageMobject that's been obtained from the camerainto the list ``self.image_mobject_from_cameras``Parameters----------- image_mobject_from_camera : ImageMobject+ image_mobject_from_cameraThe ImageMobject to add to self.image_mobject_from_cameras"""# A silly method to have right now, but maybe there are thingsdiff --git a/manim/camera/three_d_camera.py b/manim/camera/three_d_camera.pyindex 863cf03e8..87b48f9fa 100644--- a/manim/camera/three_d_camera.py+++ b/manim/camera/three_d_camera.py@@ -5,8 +5,11 @@ from __future__ import annotations__all__ = ["ThreeDCamera"]+from typing import Callable+import numpy as np+from manim.mobject.mobject import Mobjectfrom manim.mobject.three_d.three_d_utils import (get_3d_vmob_end_corner,get_3d_vmob_end_corner_unit_normal,@@ -43,8 +46,6 @@ class ThreeDCamera(Camera):Parameters----------- *args- Any argument of Camera*kwargsAny keyword argument of Camera."""@@ -197,52 +198,52 @@ class ThreeDCamera(Camera):"""return self.zoom_tracker.get_value()- def set_phi(self, value):+ def set_phi(self, value: float):"""Sets the polar angle i.e the angle between Z_AXIS and Camera through ORIGIN in radians.Parameters----------- value : int, float+ valueThe new value of the polar angle in radians."""self.phi_tracker.set_value(value)- def set_theta(self, value):+ def set_theta(self, value: float):"""Sets the azimuthal angle i.e the angle that spins the camera around Z_AXIS in radians.Parameters----------- value : int, float+ valueThe new value of the azimuthal angle in radians."""self.theta_tracker.set_value(value)- def set_focal_distance(self, value):+ def set_focal_distance(self, value: float):"""Sets the focal_distance of the Camera.Parameters----------- value : int, float+ valueThe focal_distance of the Camera."""self.focal_distance_tracker.set_value(value)- def set_gamma(self, value):+ def set_gamma(self, value: float):"""Sets the angle of rotation of the camera about the vector from the ORIGIN to the Camera.Parameters----------- value : int, float+ valueThe new angle of rotation of the camera."""self.gamma_tracker.set_value(value)- def set_zoom(self, value):+ def set_zoom(self, value: float):"""Sets the zoom amount of the camera.Parameters----------- value : int, float+ valueThe zoom amount of the camera."""self.zoom_tracker.set_value(value)@@ -284,13 +285,13 @@ class ThreeDCamera(Camera):result = np.dot(matrix, result)return result- def project_points(self, points):+ def project_points(self, points: np.ndarray | list):"""Applies the current rotation_matrix as a projectionmatrix to the passed array of points.Parameters----------- points : np.array, list+ pointsThe list of points to project.Returns@@ -321,13 +322,13 @@ class ThreeDCamera(Camera):points[:, i] *= factor * zoomreturn points- def project_point(self, point):+ def project_point(self, point: list | np.ndarray):"""Applies the current rotation_matrix as a projectionmatrix to the passed point.Parameters----------- point : list, np.array+ pointThe point to project.Returns@@ -357,7 +358,10 @@ class ThreeDCamera(Camera):return self.project_points(points)def add_fixed_orientation_mobjects(- self, *mobjects, use_static_center_func=False, center_func=None+ self,+ *mobjects: Mobject,+ use_static_center_func: bool = False,+ center_func: Callable[[], np.ndarray] | None = None,):"""This method allows the mobject to have a fixed orientation,even when the camera moves around.@@ -367,12 +371,12 @@ class ThreeDCamera(Camera):Parameters----------- *mobjects : Mobject+ *mobjectsThe mobject whose orientation must be fixed.- use_static_center_func : bool, optional+ use_static_center_funcWhether or not to use the function that takes the mobject'scenter as centerpoint, by default False- center_func : func, optional+ center_funcThe function which returns the centerpointwith respect to which the mobject will be oriented, by default None"""@@ -392,7 +396,7 @@ class ThreeDCamera(Camera):for submob in mobject.get_family():self.fixed_orientation_mobjects[submob] = func- def add_fixed_in_frame_mobjects(self, *mobjects):+ def add_fixed_in_frame_mobjects(self, *mobjects: Mobject):"""This method allows the mobject to have a fixed position,even when the camera moves around.E.G If it was passed through this method, at the top of the frame, it@@ -402,34 +406,34 @@ class ThreeDCamera(Camera):Parameters----------- **mobjects : Mobject+ **mobjectsThe mobject to fix in frame."""for mobject in extract_mobject_family_members(mobjects):self.fixed_in_frame_mobjects.add(mobject)- def remove_fixed_orientation_mobjects(self, *mobjects):+ def remove_fixed_orientation_mobjects(self, *mobjects: Mobject):"""If a mobject was fixed in its orientation by passing it through:meth:`.add_fixed_orientation_mobjects`, then this undoes that fixing.The Mobject will no longer have a fixed orientation.Parameters----------- mobjects : :class:`Mobject`+ mobjectsThe mobjects whose orientation need not be fixed any longer."""for mobject in extract_mobject_family_members(mobjects):if mobject in self.fixed_orientation_mobjects:del self.fixed_orientation_mobjects[mobject]- def remove_fixed_in_frame_mobjects(self, *mobjects):+ def remove_fixed_in_frame_mobjects(self, *mobjects: Mobject):"""If a mobject was fixed in frame by passing it through:meth:`.add_fixed_in_frame_mobjects`, then this undoes that fixing.The Mobject will no longer be fixed in frame.Parameters----------- mobjects : :class:`Mobject`+ mobjectsThe mobjects which need not be fixed in frame any longer."""for mobject in extract_mobject_family_members(mobjects):diff --git a/manim/cli/cfg/group.py b/manim/cli/cfg/group.pyindex 44fdff5ac..bc04f6682 100644--- a/manim/cli/cfg/group.py+++ b/manim/cli/cfg/group.py@@ -33,7 +33,7 @@ def value_from_string(value: str) -> str | int | bool:"""Extracts the literal of proper datatype from a string.Parameters----------- value : :class:`str`+ valueThe value to check get the literal from.Returns@@ -54,12 +54,12 @@ def _is_expected_datatype(value: str, expected: str, style: bool = False) -> booParameters----------- value : :class:`str`+ valueThe string of the value to check (obtained from reading the user input).- expected : :class:`str`+ expectedThe string of the literal datatype must be matched by `value`. Obtained fromreading the cfg file.- style : :class:`bool`, optional+ styleWhether or not to confirm if `value` is a style, by default FalseReturns@@ -77,7 +77,7 @@ def is_valid_style(style: str) -> bool:"""Checks whether the entered color is a valid color according to richParameters----------- style : :class:`str`+ styleThe style to check whether it is valid.Returns-------@@ -95,7 +95,7 @@ def replace_keys(default: dict) -> dict:"""Replaces _ to . and vice versa in a dictionary for richParameters----------- default : :class:`dict`+ defaultThe dictionary to check and replaceReturns-------diff --git a/manim/cli/init/commands.py b/manim/cli/init/commands.pyindex ef4a20188..67dc75164 100644--- a/manim/cli/init/commands.py+++ b/manim/cli/init/commands.py@@ -54,14 +54,14 @@ def select_resolution():return [res for res in resolution_options if f"{res[0]}p" == choice][0]-def update_cfg(cfg_dict, project_cfg_path):+def update_cfg(cfg_dict: dict, project_cfg_path: Path):"""Updates the manim.cfg file after reading it from the project_cfg_path.Parameters----------- cfg : :class:`dict`+ cfg_dictvalues used to update manim.cfg found project_cfg_path.- project_cfg_path : :class:`Path`+ project_cfg_pathPath of manim.cfg file."""config = configparser.ConfigParser()diff --git a/manim/cli/new/group.py b/manim/cli/new/group.pyindex 840698261..605810269 100644--- a/manim/cli/new/group.py+++ b/manim/cli/new/group.py@@ -47,14 +47,14 @@ def select_resolution():return [res for res in resolution_options if f"{res[0]}p" == choice][0]-def update_cfg(cfg_dict, project_cfg_path):+def update_cfg(cfg_dict: dict, project_cfg_path: Path):"""Updates the manim.cfg file after reading it from the project_cfg_path.Parameters----------- cfg : :class:`dict`+ cfg_dictvalues used to update manim.cfg found project_cfg_path.- project_cfg_path : :class:`Path`+ project_cfg_pathPath of manim.cfg file."""config = configparser.ConfigParser()diff --git a/manim/mobject/geometry/line.py b/manim/mobject/geometry/line.pyindex cd9e60869..418981374 100644--- a/manim/mobject/geometry/line.py+++ b/manim/mobject/geometry/line.py@@ -14,7 +14,7 @@ __all__ = ["RightAngle",]-from typing import Sequence+from typing import Any, Sequenceimport numpy as npfrom colour import Color@@ -28,6 +28,7 @@ from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGLfrom manim.mobject.opengl.opengl_mobject import OpenGLMobjectfrom manim.mobject.types.vectorized_mobject import DashedVMobject, VGroup, VMobjectfrom manim.utils.color import *+from manim.utils.color import Colorsfrom manim.utils.space_ops import angle_of_vector, line_intersection, normalize@@ -190,13 +191,13 @@ class DashedLine(Line):Parameters----------- args : Any+ argsArguments to be passed to :class:`Line`- dash_length : :class:`float`, optional+ dash_lengthThe length of each individual dash of the line.- dashed_ratio : :class:`float`, optional+ dashed_ratioThe ratio of dash space to empty space. Range of 0-1.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`Line`@@ -221,9 +222,9 @@ class DashedLine(Line):def __init__(self,- *args,- dash_length=DEFAULT_DASH_LENGTH,- dashed_ratio=0.5,+ *args: Any,+ dash_length: float = DEFAULT_DASH_LENGTH,+ dashed_ratio: float = 0.5,**kwargs,):self.dash_length = dash_length@@ -318,15 +319,15 @@ class TangentLine(Line):Parameters----------- vmob : :class:`~.VMobject`+ vmobThe VMobject on which the tangent line is drawn.- alpha : :class:`float`+ alphaHow far along the shape that the line will be constructed. range: 0-1.- length : :class:`float`, optional+ lengthLength of the tangent line.- d_alpha: :class:`float`, optional+ d_alphaThe ``dx`` value- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`Line`@@ -346,7 +347,14 @@ class TangentLine(Line):self.add(circle, line_1, line_2)"""- def __init__(self, vmob, alpha, length=1, d_alpha=1e-6, **kwargs):+ def __init__(+ self,+ vmob: VMobject,+ alpha: float,+ length: float = 1,+ d_alpha: float = 1e-6,+ **kwargs,+ ):self.length = lengthself.d_alpha = d_alphada = self.d_alpha@@ -363,11 +371,11 @@ class Elbow(VMobject, metaclass=ConvertToOpenGL):Parameters----------- width : :class:`float`, optional+ widthThe length of the elbow's sides.- angle : :class:`float`, optional+ angleThe rotation of the elbow.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`~.VMobject`.. seealso::@@ -388,7 +396,7 @@ class Elbow(VMobject, metaclass=ConvertToOpenGL):self.add(elbow_group)"""- def __init__(self, width=0.2, angle=0, **kwargs):+ def __init__(self, width: float = 0.2, angle: float = 0, **kwargs):self.angle = anglesuper().__init__(**kwargs)self.set_points_as_corners([UP, UP + RIGHT, RIGHT])@@ -401,17 +409,17 @@ class Arrow(Line):Parameters----------- args : Any+ argsArguments to be passed to :class:`Line`.- stroke_width : :class:`float`, optional+ stroke_widthThe thickness of the arrow. Influenced by :attr:`max_stroke_width_to_length_ratio`.- buff : :class:`float`, optional+ buffThe distance of the arrow from its start and end points.- max_tip_length_to_length_ratio : :class:`float`, optional+ max_tip_length_to_length_ratio:attr:`tip_length` scales with the length of the arrow. Increasing this ratio raises the max value of :attr:`tip_length`.- max_stroke_width_to_length_ratio : :class:`float`, optional+ max_stroke_width_to_length_ratio:attr:`stroke_width` scales with the length of the arrow. Increasing this ratio ratios the max value of :attr:`stroke_width`.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`Line`.@@ -486,11 +494,11 @@ class Arrow(Line):def __init__(self,- *args,- stroke_width=6,- buff=MED_SMALL_BUFF,- max_tip_length_to_length_ratio=0.25,- max_stroke_width_to_length_ratio=5,+ *args: Any,+ stroke_width: float = 6,+ buff: float = MED_SMALL_BUFF,+ max_tip_length_to_length_ratio: float = 0.25,+ max_stroke_width_to_length_ratio: float = 5,**kwargs,):self.max_tip_length_to_length_ratio = max_tip_length_to_length_ratio@@ -608,11 +616,11 @@ class Vector(Arrow):Parameters----------- direction : Union[:class:`list`, :class:`numpy.ndarray`]+ directionThe direction of the arrow.- buff : :class:`float`+ buffThe distance of the vector from its endpoints.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`Arrow`Examples@@ -628,7 +636,7 @@ class Vector(Arrow):self.add(plane, vector_1, vector_2)"""- def __init__(self, direction=RIGHT, buff=0, **kwargs):+ def __init__(self, direction: list | np.ndarray = RIGHT, buff: float = 0, **kwargs):self.buff = buffif len(direction) == 2:direction = np.hstack([direction, 0])@@ -704,9 +712,9 @@ class DoubleArrow(Arrow):Parameters----------- args : Any+ argsArguments to be passed to :class:`Arrow`- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`Arrow`@@ -744,7 +752,7 @@ class DoubleArrow(Arrow):self.add(box, d1, d2, d3)"""- def __init__(self, *args, **kwargs):+ def __init__(self, *args: Any, **kwargs):if "tip_shape_end" in kwargs:kwargs["tip_shape"] = kwargs.pop("tip_shape_end")tip_shape_start = kwargs.pop("tip_shape_start", ArrowTriangleFilledTip)@@ -763,7 +771,7 @@ class Angle(VMobject, metaclass=ConvertToOpenGL):The second line.radius :The radius of the :class:`Arc`.- quadrant : Sequence[:class:`int`]+ quadrantA sequence of two :class:`int` numbers determining which of the 4 quadrants should be used.The first value indicates whether to anchor the arc on the first line closer to the end point (1)or start point (-1), and the second value functions similarly for the@@ -773,16 +781,16 @@ class Angle(VMobject, metaclass=ConvertToOpenGL):Toggles between the two possible angles defined by two points and an arc center. If set toFalse (default), the arc will always go counterclockwise from the point on line1 untilthe point on line2 is reached. If set to True, the angle will go clockwise from line1 to line2.- dot : :class:`bool`+ dotAllows for a :class:`Dot` in the arc. Mainly used as an convention to indicate a right angle.The dot can be customized in the next three parameters.- dot_radius : :class:`float`+ dot_radiusThe radius of the :class:`Dot`. If not specified otherwise, this radius will be 1/10 of the arc radius.- dot_distance : :class:`float`+ dot_distanceRelative distance from the center to the arc: 0 puts the dot in the center and 1 on the arc itself.- dot_color : :class:`~.Colors`+ dot_colorThe color of the :class:`Dot`.- elbow : :class:`bool`+ elbowProduces an elbow-type mobject indicating a right angle, see :class:`RightAngle` for more informationand a shorthand.**kwargs@@ -866,13 +874,13 @@ class Angle(VMobject, metaclass=ConvertToOpenGL):line1: Line,line2: Line,radius: float = None,- quadrant=(1, 1),+ quadrant: Sequence[int] = (1, 1),other_angle: bool = False,- dot=False,- dot_radius=None,- dot_distance=0.55,- dot_color=WHITE,- elbow=False,+ dot: bool = False,+ dot_radius: float | None = None,+ dot_distance: float = 0.55,+ dot_color: Colors = WHITE,+ elbow: bool = False,**kwargs,):super().__init__(**kwargs)diff --git a/manim/mobject/geometry/polygram.py b/manim/mobject/geometry/polygram.pyindex dbc1e77fa..f96557525 100644--- a/manim/mobject/geometry/polygram.py+++ b/manim/mobject/geometry/polygram.py@@ -478,7 +478,7 @@ class Triangle(RegularPolygon):Parameters----------- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`RegularPolygon`Examples@@ -503,21 +503,21 @@ class Rectangle(Polygon):Parameters----------- color : :class:`~.Colors`, optional+ colorThe color of the rectangle.- height : :class:`float`, optional+ heightThe vertical height of the rectangle.- width : :class:`float`, optional+ widthThe horizontal width of the rectangle.- grid_xstep : :class:`float`, optional+ grid_xstepSpace between vertical grid lines.- grid_ystep : :class:`float`, optional+ grid_ystepSpace between horizontal grid lines.- mark_paths_closed : :class:`bool`, optional+ mark_paths_closedNo purpose.- close_new_points : :class:`bool`, optional+ close_new_pointsNo purpose.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`Polygon`Examples@@ -541,8 +541,8 @@ class Rectangle(Polygon):width: float = 4.0,grid_xstep: float | None = None,grid_ystep: float | None = None,- mark_paths_closed=True,- close_new_points=True,+ mark_paths_closed: bool = True,+ close_new_points: bool = True,**kwargs,):super().__init__(UR, UL, DL, DR, color=color, **kwargs)@@ -586,9 +586,9 @@ class Square(Rectangle):Parameters----------- side_length : :class:`float`, optional+ side_lengthThe length of the sides of the square.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`Rectangle`.Examples@@ -604,7 +604,7 @@ class Square(Rectangle):self.add(square_1, square_2, square_3)"""- def __init__(self, side_length=2.0, **kwargs):+ def __init__(self, side_length: float = 2.0, **kwargs):self.side_length = side_lengthsuper().__init__(height=side_length, width=side_length, **kwargs)@@ -614,9 +614,9 @@ class RoundedRectangle(Rectangle):Parameters----------- corner_radius : :class:`float`, optional+ corner_radiusThe curvature of the corners of the rectangle.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`Rectangle`Examples@@ -633,7 +633,7 @@ class RoundedRectangle(Rectangle):self.add(rect_group)"""- def __init__(self, corner_radius=0.5, **kwargs):+ def __init__(self, corner_radius: float = 0.5, **kwargs):super().__init__(**kwargs)self.corner_radius = corner_radiusself.round_corners(self.corner_radius)@@ -644,9 +644,9 @@ class Cutout(VMobject, metaclass=ConvertToOpenGL):Parameters----------- main_shape : :class:`~.VMobject`+ main_shapeThe primary shape from which cutouts are made.- mobjects : :class:`~.VMobject`+ mobjectsThe smaller shapes which are to be cut out of the ``main_shape``.kwargsFurther keyword arguments that are passed to the constructor of@@ -674,7 +674,7 @@ class Cutout(VMobject, metaclass=ConvertToOpenGL):self.wait()"""- def __init__(self, main_shape, *mobjects, **kwargs):+ def __init__(self, main_shape: VMobject, *mobjects: VMobject, **kwargs):super().__init__(**kwargs)self.append_points(main_shape.points)if main_shape.get_direction() == "CW":diff --git a/manim/mobject/geometry/shape_matchers.py b/manim/mobject/geometry/shape_matchers.pyindex 4376213ef..b2eec1c72 100644--- a/manim/mobject/geometry/shape_matchers.py+++ b/manim/mobject/geometry/shape_matchers.py@@ -169,11 +169,6 @@ class Cross(VGroup):class Underline(Line):"""Creates an underline.- Parameters- ----------- Line- The underline.-Examples--------.. manim:: UnderLinediff --git a/manim/mobject/graphing/number_line.py b/manim/mobject/graphing/number_line.pyindex cafea17c9..aa56c9358 100644--- a/manim/mobject/graphing/number_line.py+++ b/manim/mobject/graphing/number_line.py@@ -592,14 +592,12 @@ class NumberLine(Line):self, label_tex: str | float | VMobject, **kwargs) -> VMobject:"""Checks if the label is a :class:`~.VMobject`, otherwise, creates a- label according to the ``label_constructor``.+ label according to :attr:`label_constructor`.Parameters----------label_texThe label to be compared against the above types.- label_constructor- The VMobject class used to construct the label.Returns-------diff --git a/manim/mobject/graphing/scale.py b/manim/mobject/graphing/scale.pyindex 0e570a6a1..bee130ffd 100644--- a/manim/mobject/graphing/scale.py+++ b/manim/mobject/graphing/scale.py@@ -122,7 +122,7 @@ class LogBase(_ScaleBase):----------baseThe base of the log, by default 10.- custom_labels : bool, optional+ custom_labelsFor use with :class:`~.Axes`:Whetherer or not to include ``LaTeX`` axis labels, by default True.diff --git a/manim/mobject/matrix.py b/manim/mobject/matrix.pyindex f5aadf00e..f8cc6b0af 100644--- a/manim/mobject/matrix.py+++ b/manim/mobject/matrix.py@@ -44,6 +44,7 @@ from typing import Iterable, Sequenceimport numpy as np+from manim.mobject.mobject import Mobjectfrom manim.mobject.opengl.opengl_compatibility import ConvertToOpenGLfrom manim.mobject.text.numbers import DecimalNumber, Integerfrom manim.mobject.text.tex_mobject import MathTex, Tex@@ -227,16 +228,16 @@ class Matrix(VMobject, metaclass=ConvertToOpenGL):)return self- def _add_brackets(self, left="[", right="]", **kwargs):+ def _add_brackets(self, left: str = "[", right: str = "]", **kwargs):"""Adds the brackets to the Matrix mobject.See Latex document for various bracket types.Parameters----------- left : :class:`str`, optional+ leftthe left bracket, by default "["- right : :class:`str`, optional+ rightthe right bracket, by default "]"Returns@@ -310,12 +311,12 @@ class Matrix(VMobject, metaclass=ConvertToOpenGL):))- def set_column_colors(self, *colors):+ def set_column_colors(self, *colors: str):"""Set individual colors for each columns of the matrix.Parameters----------- colors : :class:`str`+ colorsThe list of colors; each color specified corresponds to a column.Returns@@ -362,12 +363,12 @@ class Matrix(VMobject, metaclass=ConvertToOpenGL):"""return VGroup(*(VGroup(*row) for row in self.mob_matrix))- def set_row_colors(self, *colors):+ def set_row_colors(self, *colors: str):"""Set individual colors for each row of the matrix.Parameters----------- colors : :class:`str`+ colorsThe list of colors; each color specified corresponds to a row.Returns@@ -487,9 +488,9 @@ class DecimalMatrix(Matrix):def __init__(self,- matrix,- element_to_mobject=DecimalNumber,- element_to_mobject_config={"num_decimal_places": 1},+ matrix: Iterable,+ element_to_mobject: Mobject = DecimalNumber,+ element_to_mobject_config: dict[str, Mobject] = {"num_decimal_places": 1},**kwargs,):"""@@ -497,11 +498,11 @@ class DecimalMatrix(Matrix):Parameters----------- matrix : :class:`typing.Iterable`+ matrixA numpy 2d array or list of lists- element_to_mobject : :class:`~.Mobject`, optional+ element_to_mobjectMobject to use, by default DecimalNumber- element_to_mobject_config : Dict[:class:`str`, :class:`~.Mobject`], optional+ element_to_mobject_configConfig for the desired mobject, by default {"num_decimal_places": 1}"""super().__init__(@@ -530,15 +531,17 @@ class IntegerMatrix(Matrix):self.add(m0)"""- def __init__(self, matrix, element_to_mobject=Integer, **kwargs):+ def __init__(+ self, matrix: Iterable, element_to_mobject: Mobject = Integer, **kwargs+ ):"""Will round if there are decimal entries in the matrix.Parameters----------- matrix : :class:`typing.Iterable`+ matrixA numpy 2d array or list of lists- element_to_mobject : :class:`~.Mobject`, optional+ element_to_mobjectMobject to use, by default Integer"""super().__init__(matrix, element_to_mobject=element_to_mobject, **kwargs)@@ -568,25 +571,25 @@ class MobjectMatrix(Matrix):def get_det_text(- matrix,- determinant=None,- background_rect=False,- initial_scale_factor=2,+ matrix: Matrix,+ determinant: int | str | None = None,+ background_rect: bool = False,+ initial_scale_factor: float = 2,):r"""Helper function to create determinant.Parameters----------- matrix : :class:`~.Matrix`+ matrixThe matrix whose determinant is to be created- determinant : :class:`int|str`+ determinantThe value of the determinant of the matrix- background_rect : :class:`bool`+ background_rectThe background rectangle- initial_scale_factor : :class:`float`+ initial_scale_factorThe scale of the text `det` w.r.t the matrixReturnsdiff --git a/manim/mobject/opengl/opengl_vectorized_mobject.py b/manim/mobject/opengl/opengl_vectorized_mobject.pyindex 748e050b7..1d6f6d7a4 100644--- a/manim/mobject/opengl/opengl_vectorized_mobject.py+++ b/manim/mobject/opengl/opengl_vectorized_mobject.py@@ -202,7 +202,7 @@ class OpenGLVMobject(OpenGLMobject):Fill color of the :class:`OpenGLVMobject`.opacityFill opacity of the :class:`OpenGLVMobject`.- family+ recurseIf ``True``, the fill color of all submobjects is also set.Returns@@ -491,7 +491,7 @@ class OpenGLVMobject(OpenGLMobject):Parameters----------- point : Sequence[float]+ pointend of the straight line."""end = self.points[-1]@@ -572,7 +572,7 @@ class OpenGLVMobject(OpenGLMobject):Parameters----------- points : Iterable[float]+ pointsArray of points that will be set as corners.Returns@@ -674,13 +674,13 @@ class OpenGLVMobject(OpenGLMobject):return np.linalg.norm(p1 - p0) < self.tolerance_for_point_equality# Information about the curve- def force_direction(self, target_direction):+ def force_direction(self, target_direction: str):"""Makes sure that points are either directed clockwise orcounterclockwise.Parameters----------- target_direction : :class:`str`+ target_directionEither ``"CW"`` or ``"CCW"``."""if target_direction not in ("CW", "CCW"):@@ -760,7 +760,7 @@ class OpenGLVMobject(OpenGLMobject):Parameters----------- n : int+ nindex of the desired bezier curve.Returns@@ -777,7 +777,7 @@ class OpenGLVMobject(OpenGLMobject):Parameters----------- n : int+ nindex of the desired curve.Returns@@ -1260,9 +1260,9 @@ class OpenGLVMobject(OpenGLMobject):Parameters----------- n : int+ nNumber of desired curves.- points : np.ndarray+ pointsStarting points.Returns@@ -1319,13 +1319,13 @@ class OpenGLVMobject(OpenGLMobject):Parameters----------- vmobject : OpenGLVMobject+ vmobjectThe vmobject that will serve as a model.- a : float+ aupper-bound.- b : float+ blower-bound- remap : bool+ remapif the point amount should be kept the same (True)This option should be manually set to False if keeping the number of points is not needed"""@@ -1699,12 +1699,12 @@ class OpenGLVGroup(OpenGLVMobject):f"submobject{'s' if len(self.submobjects) > 0 else ''}")- def add(self, *vmobjects):+ def add(self, *vmobjects: OpenGLVMobject):"""Checks if all passed elements are an instance of OpenGLVMobject and then add them to submobjectsParameters----------- vmobjects : :class:`~.OpenGLVMobject`+ vmobjectsList of OpenGLVMobject to addReturnsdiff --git a/manim/mobject/svg/brace.py b/manim/mobject/svg/brace.pyindex e39591235..63267a5e0 100644--- a/manim/mobject/svg/brace.py+++ b/manim/mobject/svg/brace.py@@ -12,6 +12,7 @@ import svgelements as sefrom manim._config import configfrom manim.mobject.geometry.arc import Arcfrom manim.mobject.geometry.line import Line+from manim.mobject.mobject import Mobjectfrom manim.mobject.opengl.opengl_compatibility import ConvertToOpenGLfrom manim.mobject.text.tex_mobject import MathTex, Tex@@ -32,7 +33,7 @@ class Brace(VMobjectFromSVGPath):Parameters----------- mobject : :class:`~.Mobject`+ mobjectThe mobject adjacent to which the brace is placed.direction :The direction from which the brace faces the mobject.@@ -61,7 +62,7 @@ class Brace(VMobjectFromSVGPath):def __init__(self,- mobject,+ mobject: Mobject,direction: Sequence[float] | None = DOWN,buff=0.2,sharpness=2,diff --git a/manim/mobject/table.py b/manim/mobject/table.pyindex 731b7d128..989873644 100644--- a/manim/mobject/table.py+++ b/manim/mobject/table.py@@ -206,7 +206,7 @@ class Table(VGroup):Dict passed to :meth:`~.Mobject.arrange_in_grid`, customizes the arrangement of the table.line_configDict passed to :class:`~.Line`, customizes the lines of the table.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`~.VGroup`."""@@ -773,7 +773,7 @@ class Table(VGroup):posThe position of a specific entry on the table. ``(1,1)`` being the top left entryof the table.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`~.Polygon`.Returns@@ -834,7 +834,7 @@ class Table(VGroup):of the table.colorThe color used to highlight the cell.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`~.BackgroundRectangle`.Examples@@ -870,7 +870,7 @@ class Table(VGroup):of the table.colorThe color used to highlight the cell.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`~.BackgroundRectangle`.Examples@@ -901,15 +901,13 @@ class Table(VGroup):line_animation: Callable[[VMobject | VGroup], Animation] = Create,label_animation: Callable[[VMobject | VGroup], Animation] = Write,element_animation: Callable[[VMobject | VGroup], Animation] = Create,- entry_animation=FadeIn,+ entry_animation: Callable[[VMobject | VGroup], Animation] = FadeIn,**kwargs,) -> AnimationGroup:"""Customized create-type function for tables.Parameters----------- run_time- The run time of the line creation and the writing of the elements.lag_ratioThe lag ratio of the animation.line_animation@@ -918,7 +916,9 @@ class Table(VGroup):The animation style of the table labels, see :mod:`~.creation` for examples.element_animationThe animation style of the table elements, see :mod:`~.creation` for examples.- kwargs : Any+ entry_animation+ The entry animation of the table background, see :mod:`~.creation` for examples.+ kwargsFurther arguments passed to the creation animations.Returns@@ -1015,7 +1015,7 @@ class MathTable(Table):for :class:`~.MathTex`.element_to_mobjectThe :class:`~.Mobject` class applied to the table entries. Set as :class:`~.MathTex`.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`~.Table`."""super().__init__(@@ -1069,7 +1069,7 @@ class MobjectTable(Table):A 2D array or list of lists. Content of the table must be of type :class:`~.Mobject`.element_to_mobjectThe :class:`~.Mobject` class applied to the table entries. Set as ``lambda m : m`` to return itself.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`~.Table`."""super().__init__(table, element_to_mobject=element_to_mobject, **kwargs)@@ -1118,7 +1118,7 @@ class IntegerTable(Table):for :class:`~.Integer`.element_to_mobjectThe :class:`~.Mobject` class applied to the table entries. Set as :class:`~.Integer`.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`~.Table`."""super().__init__(table, element_to_mobject=element_to_mobject, **kwargs)@@ -1166,7 +1166,7 @@ class DecimalTable(Table):The :class:`~.Mobject` class applied to the table entries. Set as :class:`~.DecimalNumber`.element_to_mobject_configElement to mobject config, here set as {"num_decimal_places": 1}.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`~.Table`."""super().__init__(diff --git a/manim/mobject/text/code_mobject.py b/manim/mobject/text/code_mobject.pyindex fcb42150c..41742a18e 100644--- a/manim/mobject/text/code_mobject.py+++ b/manim/mobject/text/code_mobject.py@@ -7,6 +7,7 @@ __all__ = []import html+import osimport refrom pathlib import Path@@ -90,45 +91,45 @@ class Code(VGroup):----------file_nameName of the code file to display.- code : :class:`str`+ codeIf ``file_name`` is not specified, a code string can bepassed directly.- tab_width : :class:`int`, optional+ tab_widthNumber of space characters corresponding to a tab character. Defaults to 3.- line_spacing : :class:`float`, optional+ line_spacingAmount of space between lines in relation to font size. Defaults to 0.3, which means 30% of font size.- font_size : class:`float`, optional+ font_sizeA number which scales displayed code. Defaults to 24.- font : :class:`str`, optional+ fontThe name of the text font to be used. Defaults to ``"Monospac821 BT"``.- stroke_width : class:`float`, optional+ stroke_widthStroke width for text. 0 is recommended, and the default.- margin: class :`float`, optional+ marginInner margin of text from the background. Defaults to 0.3.- indentation_chars : :class:`str`, optional+ indentation_chars"Indentation chars" refers to the spaces/tabs at the beginning of a given code line. Defaults to ``" "`` (spaces).- background : :class:`str`, optional+ backgroundDefines the background's type. Currently supports only ``"rectangle"`` (default) and ``"window"``.- background_stroke_width : class:`float`, optional+ background_stroke_widthDefines the stroke width of the background. Defaults to 1.- background_stroke_color : class:`str`, optional+ background_stroke_colorDefines the stroke color for the background. Defaults to ``WHITE``.- corner_radius : :class:`float`, optional+ corner_radiusDefines the corner radius for the background. Defaults to 0.2.- insert_line_no : :class:`bool`, optional+ insert_line_noDefines whether line numbers should be inserted in displayed code. Defaults to ``True``.- line_no_from : :class:`int`, optional+ line_no_fromDefines the first line's number in the line count. Defaults to 1.- line_no_buff : :class:`float`, optional+ line_no_buffDefines the spacing between line numbers and displayed code. Defaults to 0.4.- style : :class:`str`, optional+ styleDefines the style type of displayed code. You can see possible names of styles in with :attr:`styles_list`. Defaults to ``"vim"``.- language : Optional[:class:`str`], optional+ languageSpecifies the programming language the given code was written in. If ``None``(the default), the language will be automatically detected. For the list ofpossible options, visit https://pygments.org/docs/lexers/ and look for'aliases or short names'.- generate_html_file : :class:`bool`, optional+ generate_html_fileDefines whether to generate highlighted html code to the folder `assets/codes/generated_html_files`. Defaults to `False`.Attributes@@ -153,25 +154,25 @@ class Code(VGroup):def __init__(self,- file_name: str | os.PathLike = None,- code=None,- tab_width=3,- line_spacing=0.3,- font_size=24,- font="Monospac821 BT",- stroke_width=0,- margin=0.3,- indentation_chars=" ",- background="rectangle", # or window- background_stroke_width=1,- background_stroke_color=WHITE,- corner_radius=0.2,- insert_line_no=True,- line_no_from=1,- line_no_buff=0.4,- style="vim",- language=None,- generate_html_file=False,+ file_name: str | os.PathLike | None = None,+ code: str | None = None,+ tab_width: int = 3,+ line_spacing: float = 0.3,+ font_size: float = 24,+ font: str = "Monospac821 BT",+ stroke_width: float = 0,+ margin: float = 0.3,+ indentation_chars: str = " ",+ background: str = "rectangle", # or window+ background_stroke_width: float = 1,+ background_stroke_color: str = WHITE,+ corner_radius: float = 0.2,+ insert_line_no: bool = True,+ line_no_from: int = 1,+ line_no_buff: float = 0.4,+ style: str = "vim",+ language: str | None = None,+ generate_html_file: bool = False,**kwargs,):super().__init__(@@ -472,12 +473,12 @@ class Code(VGroup):self.code_json[code_json_line_index].append([text, color])# print(self.code_json)- def _correct_non_span(self, line_str):+ def _correct_non_span(self, line_str: str):"""Function put text color to those strings that don't have one according to background_color of displayed code.Parameters---------- line_str : :class:`str`+ line_strTakes a html element's string to put color to it according to background_color of displayed code.Returns@@ -525,31 +526,31 @@ class Code(VGroup):def _hilite_me(- code,- language,- style,- insert_line_no,- divstyles,- file_path,- line_no_from,+ code: str,+ language: str,+ style: str,+ insert_line_no: bool,+ divstyles: str,+ file_path: Path,+ line_no_from: int,):"""Function to highlight code from string to html.Parameters---------- code : :class:`str`+ codeCode string.- language : :class:`str`+ languageThe name of the programming language the given code was written in.- style : :class:`str`+ styleCode style name.- insert_line_no : :class:`bool`+ insert_line_noDefines whether line numbers should be inserted in the html file.- divstyles : :class:`str`+ divstylesSome html css styles.- file_path : :class:`pathlib.Path`+ file_pathPath of code file.- line_no_from : :class:`int`+ line_no_fromDefines the first line's number in the line count."""style = style or "colorful"@@ -578,14 +579,14 @@ def _hilite_me(return html-def _insert_line_numbers_in_html(html, line_no_from):+def _insert_line_numbers_in_html(html: str, line_no_from: int):"""Function that inserts line numbers in the highlighted HTML code.Parameters---------- html : :class:`str`+ htmlhtml string of highlighted code.- line_no_from : :class:`int`+ line_no_fromDefines the first line's number in the line count.Returnsdiff --git a/manim/mobject/text/numbers.py b/manim/mobject/text/numbers.pyindex 963c11dc0..5a0c8413f 100644--- a/manim/mobject/text/numbers.py+++ b/manim/mobject/text/numbers.py@@ -11,7 +11,8 @@ import numpy as npfrom manim import configfrom manim.constants import *from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL-from manim.mobject.text.tex_mobject import MathTex, SingleStringMathTex+from manim.mobject.text.tex_mobject import MathTex, SingleStringMathTex, Tex+from manim.mobject.text.text_mobject import Textfrom manim.mobject.types.vectorized_mobject import VMobjectfrom manim.mobject.value_tracker import ValueTracker@@ -299,16 +300,16 @@ class Variable(VMobject, metaclass=ConvertToOpenGL):Parameters----------- var : Union[:class:`int`, :class:`float`]+ varThe initial value you need to keep track of and display.- label : Union[:class:`str`, :class:`~.Tex`, :class:`~.MathTex`, :class:`~.Text`, :class:`~.SingleStringMathTex`]+ labelThe label for your variable. Raw strings are convertex to :class:`~.MathTex` objects.- var_type : Union[:class:`DecimalNumber`, :class:`Integer`], optional+ var_typeThe class used for displaying the number. Defaults to :class:`DecimalNumber`.- num_decimal_places : :class:`int`, optional+ num_decimal_placesThe number of decimal places to display in your variable. Defaults to 2.If `var_type` is an :class:`Integer`, this parameter is ignored.- kwargs : Any+ kwargsOther arguments to be passed to `~.Mobject`.Attributes@@ -397,7 +398,12 @@ class Variable(VMobject, metaclass=ConvertToOpenGL):"""def __init__(- self, var, label, var_type=DecimalNumber, num_decimal_places=2, **kwargs+ self,+ var: float,+ label: str | Tex | MathTex | Text | SingleStringMathTex,+ var_type: DecimalNumber | Integer = DecimalNumber,+ num_decimal_places: int = 2,+ **kwargs,):self.label = MathTex(label) if isinstance(label, str) else labeldiff --git a/manim/mobject/three_d/three_dimensions.py b/manim/mobject/three_d/three_dimensions.pyindex bbde7d7c7..a2ab19e8b 100644--- a/manim/mobject/three_d/three_dimensions.py+++ b/manim/mobject/three_d/three_dimensions.py@@ -31,6 +31,7 @@ from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGLfrom manim.mobject.opengl.opengl_mobject import OpenGLMobjectfrom manim.mobject.types.vectorized_mobject import VGroup, VMobjectfrom manim.utils.color import *+from manim.utils.color import Colorsfrom manim.utils.deprecation import deprecated_paramsfrom manim.utils.iterables import tuplifyfrom manim.utils.space_ops import normalize, perpendicular_bisector, z_to_vector@@ -348,11 +349,11 @@ class Dot3D(Sphere):Parameters--------- point : Union[:class:`list`, :class:`numpy.ndarray`], optional+ pointThe location of the dot.- radius : :class:`float`, optional+ radiusThe radius of the dot.- color : :class:`~.Colors`, optional+ colorThe color of the :class:`Dot3D`Examples@@ -374,9 +375,9 @@ class Dot3D(Sphere):def __init__(self,- point=ORIGIN,- radius=DEFAULT_DOT_RADIUS,- color=WHITE,+ point: list | np.ndarray = ORIGIN,+ radius: float = DEFAULT_DOT_RADIUS,+ color: Colors = WHITE,resolution=(8, 8),**kwargs,):@@ -464,31 +465,31 @@ class Cone(Surface):Parameters--------- base_radius : :class:`float`+ base_radiusThe base radius from which the cone tapers.- height : :class:`float`+ heightThe height measured from the plane formed by the base_radius to the apex of the cone.- direction : :class:`numpy.array`+ directionThe direction of the apex.- show_base : :class:`bool`+ show_baseWhether to show the base plane or not.- v_range : :class:`Sequence[float]`+ v_rangeThe azimuthal angle to start and end at.- u_min : :class:`float`+ u_minThe radius at the apex.- checkerboard_colors : :class:`bool`+ checkerboard_colorsShow checkerboard grid texture on the cone."""def __init__(self,- base_radius=1,- height=1,- direction=Z_AXIS,- show_base=False,- v_range=[0, TAU],- u_min=0,- checkerboard_colors=False,+ base_radius: float = 1,+ height: float = 1,+ direction: np.ndarray = Z_AXIS,+ show_base: bool = False,+ v_range: Sequence[float] = [0, TAU],+ u_min: float = 0,+ checkerboard_colors: bool = False,**kwargs,):self.direction = direction@@ -517,13 +518,13 @@ class Cone(Surface):self._rotate_to_direction()- def func(self, u, v):+ def func(self, u: float, v: float):"""Converts from spherical coordinates to cartesian.Parameters---------- u : :class:`float`+ uThe radius.- v : :class:`float`+ vThe azimuthal angle."""r = u@@ -594,25 +595,25 @@ class Cylinder(Surface):Parameters---------- radius : :class:`float`+ radiusThe radius of the cylinder.- height : :class:`float`+ heightThe height of the cylinder.- direction : :class:`numpy.array`+ directionThe direction of the central axis of the cylinder.- v_range : :class:`Sequence[float]`+ v_rangeThe height along the height axis (given by direction) to start and end on.- show_ends : :class:`bool`+ show_endsWhether to show the end caps or not."""def __init__(self,- radius=1,- height=2,- direction=Z_AXIS,- v_range=[0, TAU],- show_ends=True,+ radius: float = 1,+ height: float = 2,+ direction: np.ndarray = Z_AXIS,+ v_range: Sequence[float] = [0, TAU],+ show_ends: bool = True,resolution=(24, 24),**kwargs,):@@ -631,13 +632,13 @@ class Cylinder(Surface):self._current_theta = 0self.set_direction(direction)- def func(self, u, v):+ def func(self, u: float, v: float):"""Converts from cylindrical coordinates to cartesian.Parameters---------- u : :class:`float`+ uThe height.- v : :class:`float`+ vThe azimuthal angle."""height = u@@ -728,15 +729,22 @@ class Line3D(Cylinder):Parameters---------- start : :class:`numpy.array`+ startThe start position of the line.- end : :class:`numpy.array`+ endThe end position of the line.- thickness : :class:`float`+ thicknessThe thickness of the line."""- def __init__(self, start=LEFT, end=RIGHT, thickness=0.02, color=None, **kwargs):+ def __init__(+ self,+ start: np.ndarray = LEFT,+ end: np.ndarray = RIGHT,+ thickness: float = 0.02,+ color=None,+ **kwargs,+ ):self.thickness = thicknessself.set_start_and_end_attrs(start, end, **kwargs)if color is not None:@@ -882,25 +890,25 @@ class Arrow3D(Line3D):Parameters---------- start : :class:`numpy.array`+ startThe start position of the arrow.- end : :class:`numpy.array`+ endThe end position of the arrow.- thickness : :class:`float`+ thicknessThe thickness of the arrow.- height : :class:`float`+ heightThe height of the conical tip.- base_radius: :class:`float`+ base_radiusThe base radius of the conical tip."""def __init__(self,- start=LEFT,- end=RIGHT,- thickness=0.02,- height=0.3,- base_radius=0.08,+ start: np.ndarray = LEFT,+ end: np.ndarray = RIGHT,+ thickness: float = 0.02,+ height: float = 0.3,+ base_radius: float = 0.08,color=WHITE,**kwargs,):@@ -940,16 +948,16 @@ class Torus(Surface):Parameters---------- major_radius : :class:`float`+ major_radiusDistance from the center of the tube to the center of the torus.- minor_radius : :class:`float`+ minor_radiusRadius of the tube."""def __init__(self,- major_radius=3,- minor_radius=1,+ major_radius: float = 3,+ minor_radius: float = 1,u_range=(0, TAU),v_range=(0, TAU),resolution=None,diff --git a/manim/mobject/types/image_mobject.py b/manim/mobject/types/image_mobject.pyindex c24584159..c0eff69c2 100644--- a/manim/mobject/types/image_mobject.py+++ b/manim/mobject/types/image_mobject.py@@ -27,7 +27,7 @@ class AbstractImageMobject(Mobject):Parameters----------- scale_to_resolution : :class:`int`+ scale_to_resolutionAt this resolution the image is placed pixel by pixel onto the screen, so itwill look the sharpest and best.This is a custom parameter of ImageMobject so that rendering a scene with@@ -37,7 +37,7 @@ class AbstractImageMobject(Mobject):def __init__(self,- scale_to_resolution,+ scale_to_resolution: int,pixel_array_dtype="uint8",resampling_algorithm=Resampling.BICUBIC,**kwargs,@@ -54,7 +54,7 @@ class AbstractImageMobject(Mobject):# Likely to be implemented in subclasses, but no obligationpass- def set_resampling_algorithm(self, resampling_algorithm):+ def set_resampling_algorithm(self, resampling_algorithm: int):"""Sets the interpolation method for upscaling the image. By default the image isinterpolated using bicubic algorithm. This method lets you change it.@@ -63,15 +63,16 @@ class AbstractImageMobject(Mobject):Parameters----------- resampling_algorithm : :class:`int`, an integer constant described in the- Pillow library, or one from the RESAMPLING_ALGORITHMS global dictionary, under- the following keys:- * 'bicubic' or 'cubic'- * 'nearest' or 'none'- * 'box'- * 'bilinear' or 'linear'- * 'hamming'- * 'lanczos' or 'antialias'+ resampling_algorithm+ An integer constant described in the Pillow library,+ or one from the RESAMPLING_ALGORITHMS global dictionary,+ under the following keys:+ * 'bicubic' or 'cubic'+ * 'nearest' or 'none'+ * 'box'+ * 'bilinear' or 'linear'+ * 'hamming'+ * 'lanczos' or 'antialias'"""if isinstance(resampling_algorithm, int):self.resampling_algorithm = resampling_algorithm@@ -107,7 +108,7 @@ class ImageMobject(AbstractImageMobject):Parameters----------- scale_to_resolution : :class:`int`+ scale_to_resolutionAt this resolution the image is placed pixel by pixel onto the screen, so itwill look the sharpest and best.This is a custom parameter of ImageMobject so that rendering a scene with@@ -167,7 +168,7 @@ class ImageMobject(AbstractImageMobject):def __init__(self,filename_or_array,- scale_to_resolution=QUALITIES[DEFAULT_QUALITY]["pixel_height"],+ scale_to_resolution: int = QUALITIES[DEFAULT_QUALITY]["pixel_height"],invert=False,image_mode="RGBA",**kwargs,@@ -205,12 +206,12 @@ class ImageMobject(AbstractImageMobject):self.color = colorreturn self- def set_opacity(self, alpha):+ def set_opacity(self, alpha: float):"""Sets the image's opacity.Parameters----------- alpha : float+ alphaThe alpha value of the object, 1 being opaque and 0 beingtransparent."""@@ -219,34 +220,36 @@ class ImageMobject(AbstractImageMobject):self.stroke_opacity = alphareturn self- def fade(self, darkness=0.5, family=True):+ def fade(self, darkness: float = 0.5, family: bool = True):"""Sets the image's opacity using a 1 - alpha relationship.Parameters----------- darkness : float+ darknessThe alpha value of the object, 1 being transparent and 0 beingopaque.- family : Boolean+ familyWhether the submobjects of the ImageMobject should be affected."""self.set_opacity(1 - darkness)super().fade(darkness, family)return self- def interpolate_color(self, mobject1, mobject2, alpha):+ def interpolate_color(+ self, mobject1: ImageMobject, mobject2: ImageMobject, alpha: float+ ):"""Interpolates the array of pixel color values from one ImageMobjectinto an array of equal size in the target ImageMobject.Parameters----------- mobject1 : ImageMobject+ mobject1The ImageMobject to transform from.- mobject2 : ImageMobject+ mobject2The ImageMobject to transform into.- alpha : float+ alphaUsed to track the lerp relationship. Not opacity related."""assert mobject1.pixel_array.shape == mobject2.pixel_array.shape, (diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.pyindex 3a59d3528..44a816791 100644--- a/manim/mobject/types/vectorized_mobject.py+++ b/manim/mobject/types/vectorized_mobject.py@@ -68,7 +68,7 @@ class VMobject(Mobject):close_new_pointsIndicates that it will not be displayed, butthat it should count in parent mobject's path- tolerance_point_for_equality+ tolerance_for_point_equalityThis is within a pixel"""@@ -460,7 +460,7 @@ class VMobject(Mobject):Parameters----------- direction : :class:`numpy.ndarray`, optional+ directionDirection from where the gradient is applied.Examples@@ -483,14 +483,14 @@ class VMobject(Mobject):self.sheen_direction = directionreturn self- def rotate_sheen_direction(self, angle: np.ndarray, axis: float = OUT, family=True):+ def rotate_sheen_direction(self, angle: float, axis: np.ndarray = OUT, family=True):"""Rotates the direction of the applied sheen.Parameters----------- angle : :class:`float`+ angleAngle by which the direction of sheen is rotated.- axis : :class:`numpy.ndarray`+ axisAxis of rotation.Examples@@ -514,16 +514,16 @@ class VMobject(Mobject):self.sheen_direction = rotate_vector(self.sheen_direction, angle, axis)return self- def set_sheen(self, factor, direction: np.ndarray = None, family=True):+ def set_sheen(self, factor: float, direction: np.ndarray = None, family=True):"""Applies a color gradient from a direction.Parameters----------- factor : :class:`float`+ factorThe extent of lustre/gradient to apply. If negative, the gradientstarts from black, if positive the gradient starts from white andchanges to the current color.- direction : :class:`numpy.ndarray`, optional+ directionDirection from where the gradient is applied.Examples@@ -668,11 +668,11 @@ class VMobject(Mobject):Parameters----------- handle1 : np.ndarray+ handle1first handle- handle2 : np.ndarray+ handle2second handle- anchor : np.ndarray+ anchoranchorReturns@@ -720,7 +720,7 @@ class VMobject(Mobject):Parameters----------- point : np.ndarray+ pointend of the straight line.Returns@@ -743,7 +743,7 @@ class VMobject(Mobject):Parameters----------- points: np.array+ pointsPoints (anchor and handle, or just anchor) to add a smooth curve fromReturns@@ -809,7 +809,7 @@ class VMobject(Mobject):Parameters----------- points : Iterable[float]+ pointsArray of points that will be set as corners.Returns@@ -947,9 +947,9 @@ class VMobject(Mobject):2D point case. NumPy is overkill for such a small question.Parameters----------- p0 : np.ndarray+ p0first point- p1 : np.ndarray+ p1second pointReturns@@ -979,7 +979,7 @@ class VMobject(Mobject):Parameters----------- points : np.ndarray+ pointsPoints from which control points will be extracted.Returns@@ -1011,9 +1011,9 @@ class VMobject(Mobject):Parameters----------- points : np.ndarray+ pointspoints defining the bezier curve.- filter_func : typing.Callable[int, bool]+ filter_funcFilter-func defining the relation.Returns@@ -1061,7 +1061,7 @@ class VMobject(Mobject):Parameters----------- n : int+ nindex of the desired bezier curve.Returns@@ -1078,7 +1078,7 @@ class VMobject(Mobject):Parameters----------- n : int+ nindex of the desired curve.Returns@@ -1492,9 +1492,9 @@ class VMobject(Mobject):Parameters----------- n : int+ nNumber of desired curves.- points : np.ndarray+ pointsStarting points.Returns@@ -1592,11 +1592,11 @@ class VMobject(Mobject):Parameters----------- vmobject : VMobject+ vmobjectThe vmobject that will serve as a model.- a : float+ aupper-bound.- b : float+ blower-boundReturns@@ -1716,13 +1716,13 @@ class VMobject(Mobject):self.points = self.points[::-1]return self- def force_direction(self, target_direction):+ def force_direction(self, target_direction: str):"""Makes sure that points are either directed clockwise orcounterclockwise.Parameters----------- target_direction : :class:`str`+ target_directionEither ``"CW"`` or ``"CCW"``."""if target_direction not in ("CW", "CCW"):@@ -1809,12 +1809,12 @@ class VGroup(VMobject, metaclass=ConvertToOpenGL):f"submobject{'s' if len(self.submobjects) > 0 else ''}")- def add(self, *vmobjects):+ def add(self, *vmobjects: VMobject):"""Checks if all passed elements are an instance of VMobject and then add them to submobjectsParameters----------- vmobjects : :class:`~.VMobject`+ vmobjectsList of VMobject to addReturns@@ -1907,14 +1907,14 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):Parameters----------- mapping_or_iterable : Union[:class:`Mapping`, Iterable[Tuple[Hashable, :class:`~.VMobject`]]], optional+ mapping_or_iterableThe parameter specifying the key-value mapping of keys and mobjects.- show_keys : :class:`bool`, optional+ show_keysWhether to also display the key associated withthe mobject. This might be useful when debugging,especially when there are a lot of mobjects in the:class:`VDict`. Defaults to False.- kwargs : Any+ kwargsOther arguments to be passed to `Mobject`.Attributes@@ -1999,7 +1999,15 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):self.wait()"""- def __init__(self, mapping_or_iterable={}, show_keys=False, **kwargs):+ def __init__(+ self,+ mapping_or_iterable: Union[+ typing.Mapping[typing.Hashable, VMobject],+ typing.Iterable[typing.Tuple[typing.Hashable, VMobject]],+ ] = {},+ show_keys: bool = False,+ **kwargs,+ ):super().__init__(**kwargs)self.show_keys = show_keysself.submob_dict = {}@@ -2008,7 +2016,13 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):def __repr__(self):return __class__.__name__ + "(" + repr(self.submob_dict) + ")"- def add(self, mapping_or_iterable):+ def add(+ self,+ mapping_or_iterable: Union[+ typing.Mapping[typing.Hashable, VMobject],+ typing.Iterable[typing.Tuple[typing.Hashable, VMobject]],+ ],+ ):"""Adds the key-value pairs to the :class:`VDict` object.Also, it internally adds the value to the `submobjects` :class:`list`@@ -2016,7 +2030,7 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):Parameters---------- mapping_or_iterable : Union[:class:`Mapping`, Iterable[Tuple[Hashable, :class:`~.VMobject`]]], optional+ mapping_or_iterableThe parameter specifying the key-value mapping of keys and mobjects.Returns@@ -2036,7 +2050,7 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):return self- def remove(self, key):+ def remove(self, key: typing.Hashable):"""Removes the mobject from the :class:`VDict` object having the key `key`Also, it internally removes the mobject from the `submobjects` :class:`list`@@ -2044,7 +2058,7 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):Parameters----------- key : :class:`typing.Hashable`+ keyThe key of the submoject to be removed.Returns@@ -2064,12 +2078,12 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):del self.submob_dict[key]return self- def __getitem__(self, key):+ def __getitem__(self, key: typing.Hashable):"""Override the [] operator for item retrieval.Parameters----------- key : :class:`typing.Hashable`+ keyThe key of the submoject to be accessedReturns@@ -2086,14 +2100,14 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):submob = self.submob_dict[key]return submob- def __setitem__(self, key, value):+ def __setitem__(self, key: typing.Hashable, value: VMobject):"""Override the [] operator for item assignment.Parameters----------- key : :class:`typing.Hashable`+ keyThe key of the submoject to be assigned- value : :class:`VMobject`+ valueThe submobject to bind the key toReturns@@ -2111,12 +2125,12 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):self.remove(key)self.add([(key, value)])- def __delitem__(self, key):+ def __delitem__(self, key: typing.Hashable):"""Override the del operator for deleting an item.Parameters----------- key : :class:`typing.Hashable`+ keyThe key of the submoject to be deletedReturns@@ -2143,12 +2157,12 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):"""del self.submob_dict[key]- def __contains__(self, key):+ def __contains__(self, key: typing.Hashable):"""Override the in operator.Parameters----------- key : :class:`typing.Hashable`+ keyThe key to check membership of.Returns@@ -2185,15 +2199,15 @@ class VDict(VMobject, metaclass=ConvertToOpenGL):submobjects = self.submob_dict.values()return submobjects- def add_key_value_pair(self, key, value):+ def add_key_value_pair(self, key: typing.Hashable, value: VMobject):"""A utility function used by :meth:`add` to add the key-value pairto :attr:`submob_dict`. Not really meant to be used externally.Parameters----------- key : :class:`typing.Hashable`+ keyThe key of the submobject to be added.- value : :class:`~.VMobject`+ valueThe mobject associated with the keyReturnsdiff --git a/manim/mobject/vector_field.py b/manim/mobject/vector_field.pyindex 16074017f..75b0f2814 100644--- a/manim/mobject/vector_field.py+++ b/manim/mobject/vector_field.py@@ -58,7 +58,7 @@ class VectorField(VGroup):The value of the color_scheme function to be mapped to the last color in `colors`. Higher values also result in the last color of the gradient.colorsThe colors defining the color gradient of the vector field.- kwargs : Any+ kwargsAdditional arguments to be passed to the :class:`~.VGroup` constructor"""@@ -143,7 +143,7 @@ class VectorField(VGroup):----------funcThe function defining a vector field.- shift_vector+ scalarThe scalar to be applied to the vector field.Examples@@ -486,7 +486,7 @@ class ArrowVectorField(VectorField):The opacity of the arrows.vector_configAdditional arguments to be passed to the :class:`~.Vector` constructor- kwargs : Any+ kwargsAdditional arguments to be passed to the :class:`~.VGroup` constructorExamples@@ -611,8 +611,6 @@ class ArrowVectorField(VectorField):----------pointThe root point of the vector.- kwargs : Any- Additional arguments to be passed to the :class:`~.Vector` constructor"""output = np.asarray(self.func(point))@@ -907,7 +905,7 @@ class StreamLines(VectorField):def start_animation(self,- warm_up=True,+ warm_up: bool = True,flow_speed: float = 1,time_width: float = 0.3,rate_func: Callable[[float], float] = linear,@@ -920,7 +918,7 @@ class StreamLines(VectorField):Parameters----------- warm_up : bool, optional+ warm_upIf `True` the animation is initialized line by line. Otherwise it starts with all lines shown.flow_speedAt `flow_speed=1` the distance the flow moves per second is equal to the magnitude of the vector field along its path. The speed value scales the speed of this flow.diff --git a/manim/renderer/cairo_renderer.py b/manim/renderer/cairo_renderer.pyindex c491f2f93..f11b7ea7c 100644--- a/manim/renderer/cairo_renderer.py+++ b/manim/renderer/cairo_renderer.py@@ -14,6 +14,9 @@ from ..scene.scene_file_writer import SceneFileWriterfrom ..utils.exceptions import EndSceneEarlyExceptionfrom ..utils.iterables import list_update+if typing.TYPE_CHECKING:+ from manim.scene.scene import Scene+class CairoRenderer:"""A renderer using Cairo.@@ -106,24 +109,23 @@ class CairoRenderer:def update_frame( # TODO Description in Docstringself,scene,- mobjects=None,- include_submobjects=True,- ignore_skipping=True,+ mobjects: typing.Iterable[Mobject] | None = None,+ include_submobjects: bool = True,+ ignore_skipping: bool = True,**kwargs,):"""Update the frame.Parameters----------- mobjects: list, optional- list of mobjects+ scene- background: np.ndarray, optional- Pixel Array for Background.+ mobjects+ list of mobjects- include_submobjects: bool, optional+ include_submobjects- ignore_skipping : bool, optional+ ignore_skipping**kwargs@@ -159,15 +161,15 @@ class CairoRenderer:"""return np.array(self.camera.pixel_array)- def add_frame(self, frame, num_frames=1):+ def add_frame(self, frame: np.ndarray, num_frames: int = 1):"""Adds a frame to the video_file_streamParameters----------- frame : numpy.ndarray+ frameThe frame to add, as a pixel array.- num_frames: int+ num_framesThe number of times to add frame."""dt = 1 / self.camera.frame_rate@@ -182,7 +184,7 @@ class CairoRenderer:Parameters----------- duration : float+ duration[description]"""dt = 1 / self.camera.frame_rate@@ -201,23 +203,23 @@ class CairoRenderer:def save_static_frame_data(self,- scene,+ scene: Scene,static_mobjects: typing.Iterable[Mobject],) -> typing.Iterable[Mobject] | None:- """Compute and save the static frame, that will be reused at each frame to avoid to unecesseraly computer- static mobjects.+ """Compute and save the static frame, that will be reused at each frame+ to avoid unnecessarily computing static mobjects.Parameters----------- scene : Scene+ sceneThe scene played.- static_mobjects : typing.Iterable[Mobject]+ static_mobjectsStatic mobjects of the scene. If None, self.static_image is set to NoneReturns-------typing.Iterable[Mobject]- the static image computed.+ The static image computed."""self.static_image = Noneif not static_mobjects:diff --git a/manim/scene/moving_camera_scene.py b/manim/scene/moving_camera_scene.pyindex f68ca4586..3adef5fc7 100644--- a/manim/scene/moving_camera_scene.py+++ b/manim/scene/moving_camera_scene.py@@ -70,6 +70,8 @@ from __future__ import annotations__all__ = ["MovingCameraScene"]+from manim.animation.animation import Animation+from ..camera.moving_camera import MovingCamerafrom ..scene.scene import Scenefrom ..utils.family import extract_mobject_family_members@@ -89,14 +91,14 @@ class MovingCameraScene(Scene):def __init__(self, camera_class=MovingCamera, **kwargs):super().__init__(camera_class=camera_class, **kwargs)- def get_moving_mobjects(self, *animations):+ def get_moving_mobjects(self, *animations: Animation):"""This method returns a list of all of the Mobjects in the Scene thatare moving, that are also in the animations passed.Parameters----------- *animations : Animation+ *animationsThe Animations whose mobjects will be checked."""moving_mobjects = super().get_moving_mobjects(*animations)diff --git a/manim/scene/scene.py b/manim/scene/scene.pyindex ebb0a42cf..63a718b08 100644--- a/manim/scene/scene.py+++ b/manim/scene/scene.py@@ -30,6 +30,7 @@ from tqdm import tqdmfrom watchdog.events import FileSystemEventHandlerfrom watchdog.observers import Observer+from manim.mobject.mobject import Mobjectfrom manim.mobject.opengl.opengl_mobject import OpenGLPointfrom .. import config, logger@@ -208,13 +209,13 @@ class Scene:result.mobject_updater_lists.append((mobject_clone, cloned_updaters))return result- def render(self, preview=False):+ def render(self, preview: bool = False):"""Renders this Scene.Parameters---------- preview : bool+ previewIf true, opens scene in a file viewer."""self.setup()@@ -312,13 +313,13 @@ class Scene:def __str__(self):return self.__class__.__name__- def get_attrs(self, *keys):+ def get_attrs(self, *keys: str):"""Gets attributes of a scene given the attribute's identifier/name.Parameters----------- *keys : str+ *keysName(s) of the argument(s) to return the attribute of.Returns@@ -328,13 +329,13 @@ class Scene:"""return [getattr(self, key) for key in keys]- def update_mobjects(self, dt):+ def update_mobjects(self, dt: float):"""Begins updating all mobjects in the Scene.Parameters----------- dt: int or float+ dtChange in time between updates. Defaults (mostly) to 1/frames_per_second"""for mobject in self.mobjects:@@ -434,14 +435,14 @@ class Scene:use_z_index=self.renderer.camera.use_z_index,)- def add(self, *mobjects):+ def add(self, *mobjects: Mobject):"""Mobjects will be displayed, from background toforeground in the order with which they are added.Parameters---------- *mobjects : Mobject+ *mobjectsMobjects to add.Returns@@ -486,7 +487,7 @@ class Scene:self.add(mob)curr_mobjects += mob.get_family()- def remove(self, *mobjects):+ def remove(self, *mobjects: Mobject):"""Removes mobjects in the passed list of mobjectsfrom the scene and the foreground, by removing them@@ -494,7 +495,7 @@ class Scene:Parameters----------- *mobjects : Mobject+ *mobjectsThe mobjects to remove."""if config.renderer == "opengl":@@ -566,9 +567,9 @@ class Scene:def restructure_mobjects(self,- to_remove,- mobject_list_name="mobjects",- extract_families=True,+ to_remove: Mobject,+ mobject_list_name: str = "mobjects",+ extract_families: bool = True,):"""tl:wr@@ -583,13 +584,13 @@ class Scene:Parameters----------- to_remove : Mobject+ to_removeThe Mobject to remove.- mobject_list_name : str, optional+ mobject_list_nameThe list of mobjects ("mobjects", "foreground_mobjects" etc) to remove from.- extract_families : bool, optional+ extract_familiesWhether the mobject's families should be recursively extracted.Returns@@ -607,7 +608,7 @@ class Scene:setattr(self, mobject_list_name, new_list)return self- def get_restructured_mobject_list(self, mobjects, to_remove):+ def get_restructured_mobject_list(self, mobjects: list, to_remove: list):"""Given a list of mobjects and a list of mobjects to be removed, thisfilters out the removable mobjects from the list of mobjects.@@ -615,10 +616,10 @@ class Scene:Parameters----------- mobjects : list+ mobjectsThe Mobjects to check.- to_remove : list+ to_removeThe list of mobjects to remove.Returns@@ -643,14 +644,14 @@ class Scene:return new_mobjects# TODO, remove this, and calls to this- def add_foreground_mobjects(self, *mobjects):+ def add_foreground_mobjects(self, *mobjects: Mobject):"""Adds mobjects to the foreground, and internally to the listforeground_mobjects, and mobjects.Parameters----------- *mobjects : Mobject+ *mobjectsThe Mobjects to add to the foreground.Returns@@ -662,14 +663,14 @@ class Scene:self.add(*mobjects)return self- def add_foreground_mobject(self, mobject):+ def add_foreground_mobject(self, mobject: Mobject):"""Adds a single mobject to the foreground, and internally to the listforeground_mobjects, and mobjects.Parameters----------- mobject : Mobject+ mobjectThe Mobject to add to the foreground.Returns@@ -679,14 +680,14 @@ class Scene:"""return self.add_foreground_mobjects(mobject)- def remove_foreground_mobjects(self, *to_remove):+ def remove_foreground_mobjects(self, *to_remove: Mobject):"""Removes mobjects from the foreground, and internally from the listforeground_mobjects.Parameters----------- *to_remove : Mobject+ *to_removeThe mobject(s) to remove from the foreground.Returns@@ -697,14 +698,14 @@ class Scene:self.restructure_mobjects(to_remove, "foreground_mobjects")return self- def remove_foreground_mobject(self, mobject):+ def remove_foreground_mobject(self, mobject: Mobject):"""Removes a single mobject from the foreground, and internally from the listforeground_mobjects.Parameters----------- mobject : Mobject+ mobjectThe mobject to remove from the foreground.Returns@@ -714,14 +715,14 @@ class Scene:"""return self.remove_foreground_mobjects(mobject)- def bring_to_front(self, *mobjects):+ def bring_to_front(self, *mobjects: Mobject):"""Adds the passed mobjects to the scene again,pushing them to he front of the scene.Parameters----------- *mobjects : Mobject+ *mobjectsThe mobject(s) to bring to the front of the scene.Returns@@ -733,14 +734,14 @@ class Scene:self.add(*mobjects)return self- def bring_to_back(self, *mobjects):+ def bring_to_back(self, *mobjects: Mobject):"""Removes the mobject from the scene andadds them to the back of the scene.Parameters----------- *mobjects : Mobject+ *mobjectsThe mobject(s) to push to the back of the scene.Returns@@ -769,13 +770,13 @@ class Scene:self.foreground_mobjects = []return self- def get_moving_mobjects(self, *animations):+ def get_moving_mobjects(self, *animations: Animation):"""Gets all moving mobjects in the passed animation(s).Parameters----------- *animations : Animation+ *animationsThe animations to check for moving mobjects.Returns@@ -818,14 +819,14 @@ class Scene:)return all_moving_mobject_families, static_mobjects- def compile_animations(self, *args, **kwargs):+ def compile_animations(self, *args: Animation, **kwargs):"""Creates _MethodAnimations from any _AnimationBuilders and updates animationkwargs with kwargs passed to play().Parameters----------- *args : Tuple[:class:`Animation`]+ *argsAnimations to be played.**kwargsConfiguration for the call to play().@@ -856,7 +857,9 @@ class Scene:return animations- def _get_animation_time_progression(self, animations, duration):+ def _get_animation_time_progression(+ self, animations: list[Animation], duration: float+ ):"""You will hardly use this when making your own animations.This method is for Manim's internal use.@@ -867,11 +870,11 @@ class Scene:Parameters----------- animations : List[:class:`~.Animation`, ...]+ animationsThe list of animations to getthe time progression for.- duration : int or float+ durationduration of wait timeReturns@@ -908,10 +911,10 @@ class Scene:def get_time_progression(self,- run_time,+ run_time: float,description,- n_iterations=None,- override_skip_animations=False,+ n_iterations: int | None = None,+ override_skip_animations: bool = False,):"""You will hardly use this when making your own animations.@@ -925,13 +928,13 @@ class Scene:Parameters----------- run_time : float+ run_timeThe ``run_time`` of the animation.- n_iterations : int, optional+ n_iterationsThe number of iterations in the animation.- override_skip_animations : bool, optional+ override_skip_animationsWhether or not to show skipped animations in the progress bar.Returns@@ -954,13 +957,13 @@ class Scene:)return time_progression- def get_run_time(self, animations):+ def get_run_time(self, animations: list[Animation]):"""Gets the total run time for a list of animations.Parameters----------- animations : List[:class:`Animation`, ...]+ animationsA list of the animations whose total``run_time`` is to be calculated.@@ -1093,7 +1096,7 @@ class Scene:"""self.wait(duration=duration, frozen_frame=True)- def wait_until(self, stop_condition, max_time=60):+ def wait_until(self, stop_condition: Callable[[], bool], max_time: float = 60):"""Like a wrapper for wait().You pass a function that determines whether to continue waiting,@@ -1101,10 +1104,10 @@ class Scene:Parameters----------- stop_condition : function+ stop_conditionThe function whose boolean return value determines whether to continue waiting- max_time : int or float, optional+ max_timeThe maximum wait time in seconds, if the stop_condition is never fulfilled."""self.wait(max_time, stop_condition=stop_condition)@@ -1117,8 +1120,11 @@ class Scene:Parameters----------- skip_rendering : bool, optional- Whether the rendering should be skipped, by default False+ animations+ Animation or mobject with mobject method and params+ play_kwargs+ named parameters affecting what was passed in ``animations``,+ e.g. ``run_time``, ``lag_ratio`` and so on.Returns-------@@ -1172,7 +1178,7 @@ class Scene:and self.animations[0].is_static_wait)- def play_internal(self, skip_rendering=False):+ def play_internal(self, skip_rendering: bool = False):"""This method is used to prep the animations for rendering,apply the arguments and parameters required to them,@@ -1180,11 +1186,8 @@ class Scene:Parameters----------- args- Animation or mobject with mobject method and params- kwargs- named parameters affecting what was passed in ``args``,- e.g. ``run_time``, ``lag_ratio`` and so on.+ skip_rendering+ Whether the rendering should be skipped, by default False"""self.duration = self.get_run_time(self.animations)self.time_progression = self._get_animation_time_progression(@@ -1479,19 +1482,25 @@ class Scene:)self.renderer.file_writer.subcaptions.append(subtitle)- def add_sound(self, sound_file, time_offset=0, gain=None, **kwargs):+ def add_sound(+ self,+ sound_file: str,+ time_offset: float = 0,+ gain: float | None = None,+ **kwargs,+ ):"""This method is used to add a sound to the animation.Parameters----------- sound_file : str+ sound_fileThe path to the sound file.- time_offset : int,float, optional+ time_offsetThe offset in the sound file after whichthe sound can be played.- gain : float+ gainAmplification of the sound.Examplesdiff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.pyindex 48131c751..f03f78319 100644--- a/manim/scene/scene_file_writer.py+++ b/manim/scene/scene_file_writer.py@@ -10,7 +10,7 @@ import shutilimport subprocessimport sysfrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Anyimport numpy as npimport srt@@ -36,6 +36,9 @@ from ..utils.file_ops import (from ..utils.sounds import get_full_sound_file_pathfrom .section import DefaultSectionType, Section+if TYPE_CHECKING:+ from manim.renderer.opengl_renderer import OpenGLRenderer+class SceneFileWriter:"""@@ -200,13 +203,13 @@ class SceneFileWriter:),)- def add_partial_movie_file(self, hash_animation):+ def add_partial_movie_file(self, hash_animation: str):"""Adds a new partial movie file path to `scene.partial_movie_files` and current section from a hash.This method will compute the path from the hash. In addition to that it adds the new animation to the current section.Parameters----------- hash_animation : str+ hash_animationHash of the animation."""if not hasattr(self, "partial_movie_directory") or not write_to_movie():@@ -267,21 +270,26 @@ class SceneFileWriter:"""self.audio_segment = AudioSegment.silent()- def add_audio_segment(self, new_segment, time=None, gain_to_background=None):+ def add_audio_segment(+ self,+ new_segment: AudioSegment,+ time: float | None = None,+ gain_to_background: float | None = None,+ ):"""This method adds an audio segment from anAudioSegment type object and suitable parameters.Parameters----------- new_segment : AudioSegment+ new_segmentThe audio segment to add- time : int, float, optional+ timethe timestamp at which thesound should be added.- gain_to_background : optional+ gain_to_backgroundThe gain of the segment from the background."""if not self.includes_sound:@@ -307,19 +315,25 @@ class SceneFileWriter:gain_during_overlay=gain_to_background,)- def add_sound(self, sound_file, time=None, gain=None, **kwargs):+ def add_sound(+ self,+ sound_file: str,+ time: float | None = None,+ gain: float | None = None,+ **kwargs,+ ):"""This method adds an audio segment from a sound file.Parameters----------- sound_file : str+ sound_fileThe path to the sound file.- time : float or int, optional+ timeThe timestamp at which the audio should be added.- gain : optional+ gainThe gain of the given audio segment.**kwargs@@ -334,40 +348,40 @@ class SceneFileWriter:self.add_audio_segment(new_segment, time, **kwargs)# Writers- def begin_animation(self, allow_write=False, file_path=None):+ def begin_animation(self, allow_write: bool = False, file_path=None):"""Used internally by manim to stream the animation to FFMPEG fordisplaying or writing to a file.Parameters----------- allow_write : bool, optional+ allow_writeWhether or not to write to a video file."""if write_to_movie() and allow_write:self.open_movie_pipe(file_path=file_path)- def end_animation(self, allow_write=False):+ def end_animation(self, allow_write: bool = False):"""Internally used by Manim to stop streaming toFFMPEG gracefully.Parameters----------- allow_write : bool, optional+ allow_writeWhether or not to write to a video file."""if write_to_movie() and allow_write:self.close_movie_pipe()- def write_frame(self, frame_or_renderer):+ def write_frame(self, frame_or_renderer: np.ndarray | OpenGLRenderer):"""Used internally by Manim to write a frame tothe FFMPEG input buffer.Parameters----------- frame : np.array+ frame_or_rendererPixel array of the frame."""if config.renderer == "opengl":@@ -379,7 +393,7 @@ class SceneFileWriter:if is_png_format() and not config["dry_run"]:self.output_image_from_array(frame)- def write_opengl_frame(self, renderer):+ def write_opengl_frame(self, renderer: OpenGLRenderer):if write_to_movie():self.writing_process.stdin.write(renderer.get_raw_frame_buffer_object_data(),@@ -411,14 +425,14 @@ class SceneFileWriter:image.save(f"{target_dir}{self.frame_count}{ext}")self.frame_count += 1- def save_final_image(self, image):+ def save_final_image(self, image: np.ndarray):"""The name is a misnomer. This method saves the imagepassed to it as an in the default image directory.Parameters----------- image : np.array+ imageThe pixel array of the image to save."""if config["dry_run"]:@@ -516,12 +530,12 @@ class SceneFileWriter:{"path": f"'{self.partial_movie_file_path}'"},)- def is_already_cached(self, hash_invocation):+ def is_already_cached(self, hash_invocation: str):"""Will check if a file named with `hash_invocation` exists.Parameters----------- hash_invocation : :class:`str`+ hash_invocationThe hash corresponding to an invocation to either `scene.play` or `scene.wait`.Returnsdiff --git a/manim/scene/three_d_scene.py b/manim/scene/three_d_scene.pyindex db49e663e..258cdce1c 100644--- a/manim/scene/three_d_scene.py+++ b/manim/scene/three_d_scene.py@@ -67,22 +67,22 @@ class ThreeDScene(Scene):Parameters----------- phi : int or float, optional+ phiThe polar angle i.e the angle between Z_AXIS and Camera through ORIGIN in radians.- theta : int or float, optional+ thetaThe azimuthal angle i.e the angle that spins the camera around the Z_AXIS.- focal_distance : int or float, optional+ focal_distanceThe focal_distance of the Camera.- gamma : int or float, optional+ gammaThe rotation of the camera about the vector from the ORIGIN to the Camera.- zoom : float, optional+ zoomThe zoom factor of the scene.- frame_center : list, tuple or np.array, optional+ frame_centerThe new center of the camera frame in cartesian coordinates."""@@ -100,17 +100,17 @@ class ThreeDScene(Scene):if frame_center is not None:self.renderer.camera._frame_center.move_to(frame_center)- def begin_ambient_camera_rotation(self, rate=0.02, about="theta"):+ def begin_ambient_camera_rotation(self, rate: float = 0.02, about: str = "theta"):"""This method begins an ambient rotation of the camera about the Z_AXIS,in the anticlockwise directionParameters----------- rate : int or float, optional+ rateThe rate at which the camera should rotate about the Z_AXIS.Negative rate means clockwise rotation.- about: (str)+ aboutone of 3 options: ["theta", "phi", "gamma"]. defaults to theta."""# TODO, use a ValueTracker for rate, so that it@@ -230,25 +230,25 @@ class ThreeDScene(Scene):Parameters----------- phi : int or float, optional+ phiThe polar angle i.e the angle between Z_AXIS and Camera through ORIGIN in radians.- theta : int or float, optional+ thetaThe azimuthal angle i.e the angle that spins the camera around the Z_AXIS.- focal_distance : int or float, optional+ focal_distanceThe radial focal_distance between ORIGIN and Camera.- gamma : int or float, optional+ gammaThe rotation of the camera about the vector from the ORIGIN to the Camera.- zoom : int or float, optional+ zoomThe zoom factor of the camera.- frame_center : list, tuple or np.array, optional+ frame_centerThe new center of the camera frame in cartesian coordinates.- added_anims : list, optional+ added_animsAny other animations to be played at the same time."""@@ -315,14 +315,14 @@ class ThreeDScene(Scene):if frame_center is not None and config.renderer != "opengl":self.remove(self.camera._frame_center)- def get_moving_mobjects(self, *animations):+ def get_moving_mobjects(self, *animations: Animation):"""This method returns a list of all of the Mobjects in the Scene thatare moving, that are also in the animations passed.Parameters----------- *animations : Animation+ *animationsThe animations whose mobjects will be checked."""moving_mobjects = super().get_moving_mobjects(*animations)@@ -333,7 +333,7 @@ class ThreeDScene(Scene):return self.mobjectsreturn moving_mobjects- def add_fixed_orientation_mobjects(self, *mobjects, **kwargs):+ def add_fixed_orientation_mobjects(self, *mobjects: Mobject, **kwargs):"""This method is used to prevent the rotation and tiltingof mobjects as the camera moves around. The mobject can@@ -343,7 +343,7 @@ class ThreeDScene(Scene):Parameters----------- *mobjects : Mobject+ *mobjectsThe Mobject(s) whose orientation must be fixed.**kwargs@@ -360,7 +360,7 @@ class ThreeDScene(Scene):mob.fix_orientation()self.add(mob)- def add_fixed_in_frame_mobjects(self, *mobjects):+ def add_fixed_in_frame_mobjects(self, *mobjects: Mobject):"""This method is used to prevent the rotation and movementof mobjects as the camera moves around. The mobject is@@ -369,7 +369,7 @@ class ThreeDScene(Scene):Parameters----------- *mobjects : Mobjects+ *mobjectsThe Mobjects whose orientation must be fixed."""if config.renderer != "opengl":@@ -382,7 +382,7 @@ class ThreeDScene(Scene):mob.fix_in_frame()self.add(mob)- def remove_fixed_orientation_mobjects(self, *mobjects):+ def remove_fixed_orientation_mobjects(self, *mobjects: Mobject):"""This method "unfixes" the orientation of the mobjectspassed, meaning they will no longer be at the same angle@@ -391,7 +391,7 @@ class ThreeDScene(Scene):Parameters----------- *mobjects : Mobjects+ *mobjectsThe Mobjects whose orientation must be unfixed."""if config.renderer != "opengl":@@ -402,7 +402,7 @@ class ThreeDScene(Scene):mob.unfix_orientation()self.remove(mob)- def remove_fixed_in_frame_mobjects(self, *mobjects):+ def remove_fixed_in_frame_mobjects(self, *mobjects: Mobject):"""This method undoes what add_fixed_in_frame_mobjects does.It allows the mobject to be affected by the movement of@@ -410,7 +410,7 @@ class ThreeDScene(Scene):Parameters----------- *mobjects : Mobjects+ *mobjectsThe Mobjects whose position and orientation must be unfixed."""if config.renderer != "opengl":diff --git a/manim/scene/vector_space_scene.py b/manim/scene/vector_space_scene.pyindex aa4df4997..f0bdd351b 100644--- a/manim/scene/vector_space_scene.py+++ b/manim/scene/vector_space_scene.py@@ -4,6 +4,8 @@ from __future__ import annotations__all__ = ["VectorScene", "LinearTransformationScene"]+from typing import Callable+import numpy as npfrom colour import Color@@ -46,13 +48,13 @@ class VectorScene(Scene):super().__init__(**kwargs)self.basis_vector_stroke_width = basis_vector_stroke_width- def add_plane(self, animate=False, **kwargs):+ def add_plane(self, animate: bool = False, **kwargs):"""Adds a NumberPlane object to the background.Parameters----------- animate : bool, optional+ animateWhether or not to animate the addition of the plane via Create.**kwargsAny valid keyword arguments accepted by NumberPlane.@@ -68,15 +70,15 @@ class VectorScene(Scene):self.add(plane)return plane- def add_axes(self, animate=False, color=WHITE, **kwargs):+ def add_axes(self, animate: bool = False, color: bool = WHITE, **kwargs):"""Adds a pair of Axes to the Scene.Parameters----------- animate : bool, optional+ animateWhether or not to animate the addition of the axes through Create.- color : bool, optional+ colorThe color of the axes. Defaults to WHITE."""axes = Axes(color=color, axis_config={"unit_size": 1})@@ -85,17 +87,17 @@ class VectorScene(Scene):self.add(axes)return axes- def lock_in_faded_grid(self, dimness=0.7, axes_dimness=0.5):+ def lock_in_faded_grid(self, dimness: float = 0.7, axes_dimness: float = 0.5):"""This method freezes the NumberPlane and Axes that were alreadyin the background, and adds new, manipulatable ones to the foreground.Parameters----------- dimness : int, float, optional+ dimnessThe required dimness of the NumberPlane- axes_dimness : int, float, optional+ axes_dimnessThe required dimness of the Axes."""plane = self.add_plane()@@ -109,13 +111,13 @@ class VectorScene(Scene):self.renderer.camera = Camera(self.renderer.get_frame())self.clear()- def get_vector(self, numerical_vector, **kwargs):+ def get_vector(self, numerical_vector: np.ndarray | list | tuple, **kwargs):"""Returns an arrow on the Plane given an input numerical vector.Parameters----------- numerical_vector : np.array, list, tuple+ numerical_vectorThe Vector to plot.**kwargsAny valid keyword argument of Arrow.@@ -132,22 +134,28 @@ class VectorScene(Scene):**kwargs,)- def add_vector(self, vector, color=YELLOW, animate=True, **kwargs):+ def add_vector(+ self,+ vector: Arrow | list | tuple | np.ndarray,+ color: str = YELLOW,+ animate: bool = True,+ **kwargs,+ ):"""Returns the Vector after adding it to the Plane.Parameters----------- vector : Arrow, list, tuple, np.array+ vectorIt can be a pre-made graphical vector, or thecoordinates of one.- color : str+ colorThe string of the hex color of the vector.This is only taken into consideration if'vector' is not an Arrow. Defaults to YELLOW.- animate : bool+ animateWhether or not to animate the addition of the vectorby using GrowArrow@@ -168,25 +176,18 @@ class VectorScene(Scene):self.add(vector)return vector- def write_vector_coordinates(self, vector, **kwargs):+ def write_vector_coordinates(self, vector: Arrow, **kwargs):"""Returns a column matrix indicating the vector coordinates,after writing them to the screen.Parameters----------- vector : :class:`.Arrow`+ vectorThe arrow representing the vector.**kwargs- Any valid keyword arguments of :meth:`~.geometry.Vector.coordinate_label`:-- integer_labels : :class:`bool`- Whether or not to round the coordinates to integers. Default: ``True``.- n_dim : :class:`int`- The number of dimensions of the vector. Default: ``2``.- color- The color of the label. Default: ``WHITE``.+ Any valid keyword arguments of :meth:`~.Vector.coordinate_label`:Returns-------@@ -197,16 +198,16 @@ class VectorScene(Scene):self.play(Write(coords))return coords- def get_basis_vectors(self, i_hat_color=X_COLOR, j_hat_color=Y_COLOR):+ def get_basis_vectors(self, i_hat_color: str = X_COLOR, j_hat_color: str = Y_COLOR):"""Returns a VGroup of the Basis Vectors (1,0) and (0,1)Parameters----------- i_hat_color : str+ i_hat_colorThe hex colour to use for the basis vector in the x direction- j_hat_color : str+ j_hat_colorThe hex colour to use for the basis vector in the y directionReturns@@ -252,32 +253,32 @@ class VectorScene(Scene):def get_vector_label(self,- vector,+ vector: Vector,label,- at_tip=False,- direction="left",- rotate=False,- color=None,- label_scale_factor=LARGE_BUFF - 0.2,+ at_tip: bool = False,+ direction: str = "left",+ rotate: bool = False,+ color: str | None = None,+ label_scale_factor: float = LARGE_BUFF - 0.2,):"""Returns naming labels for the passed vector.Parameters----------- vector : Vector+ vectorVector Object for which to get the label.- at_tip : bool+ at_tipWhether or not to place the label at the tip of the vector.- direction : {"left"}+ directionIf the label should be on the "left" or right of the vector.- rotate : bool+ rotateWhether or not to rotate it to align it with the vector.- color : str+ colorThe color to give the label.- label_scale_factor (Union[int,float])+ label_scale_factorHow much to scale the label by.Returns@@ -311,20 +312,22 @@ class VectorScene(Scene):label.shift((vector.get_end() - vector.get_start()) / 2)return label- def label_vector(self, vector, label, animate=True, **kwargs):+ def label_vector(+ self, vector: Vector, label: MathTex | str, animate: bool = True, **kwargs+ ):"""Shortcut method for creating, and animating the addition ofa label for the vector.Parameters----------- vector : Vector+ vectorThe vector for which the label must be added.- label : MathTex, str+ labelThe MathTex/string of the label.- animate : bool, optional+ animateWhether or not to animate the labelling w/ Write**kwargs@@ -361,7 +364,12 @@ class VectorScene(Scene):y_coord.set_color(Y_COLOR)return y_coord- def coords_to_vector(self, vector, coords_start=2 * RIGHT + 2 * UP, clean_up=True):+ def coords_to_vector(+ self,+ vector: np.ndarray | list | tuple,+ coords_start: np.ndarray | list | tuple = 2 * RIGHT + 2 * UP,+ clean_up: bool = True,+ ):"""This method writes the vector as a column matrix (henceforth called the label),takes the values in it one by one, and form the corresponding@@ -370,16 +378,16 @@ class VectorScene(Scene):Parameters----------- vector : np.ndarray, list, tuple+ vectorThe vector to show.- coords_start : np.ndarray,list,tuple, optional+ coords_startThe starting point of the location ofthe label of the vector that shows itnumerically.Defaults to 2 * RIGHT + 2 * UP or (2,2)- clean_up : bool, optional+ clean_upWhether or not to remove whateverthis method did after it's done.@@ -419,7 +427,12 @@ class VectorScene(Scene):self.clear()self.add(*starting_mobjects)- def vector_to_coords(self, vector, integer_labels=True, clean_up=True):+ def vector_to_coords(+ self,+ vector: np.ndarray | list | tuple,+ integer_labels: bool = True,+ clean_up: bool = True,+ ):"""This method displays vector as a Vector() based vector, and then showsthe corresponding lines that make up the x and y components of the vector.@@ -428,14 +441,14 @@ class VectorScene(Scene):Parameters----------- vector : np.ndarray, list, tuple+ vectorThe vector to show.- integer_label : bool, optional+ integer_labelsWhether or not to round the value displayed.in the vector's label to the nearest integer- clean_up : bool, optional+ clean_upWhether or not to remove whateverthis method did after it's done.@@ -477,7 +490,7 @@ class VectorScene(Scene):self.add(*starting_mobjects)return array, x_line, y_line- def show_ghost_movement(self, vector):+ def show_ghost_movement(self, vector: Arrow | list | tuple | np.ndarray):"""This method plays an animation that partially shows the entire plane movingin the direction of a particular vector. This is useful when you wish to@@ -486,7 +499,7 @@ class VectorScene(Scene):Parameters----------- vector : Arrow, list, tuple, np.ndarray+ vectorThe vector which indicates the direction of movement."""if isinstance(vector, Arrow):@@ -641,18 +654,18 @@ class LinearTransformationScene(VectorScene):self.i_hat, self.j_hat = self.basis_vectorsself.add(self.basis_vectors)- def add_special_mobjects(self, mob_list, *mobs_to_add):+ def add_special_mobjects(self, mob_list: list, *mobs_to_add: Mobject):"""Adds mobjects to a separate list that can be tracked,if these mobjects have some extra importance.Parameters----------- mob_list : list+ mob_listThe special list to which you want to addthese mobjects.- *mobs_to_add : Mobject+ *mobs_to_addThe mobjects to add."""@@ -661,44 +674,46 @@ class LinearTransformationScene(VectorScene):mob_list.append(mobject)self.add(mobject)- def add_background_mobject(self, *mobjects):+ def add_background_mobject(self, *mobjects: Mobject):"""Adds the mobjects to the special listself.background_mobjects.Parameters----------- *mobjects : Mobject+ *mobjectsThe mobjects to add to the list."""self.add_special_mobjects(self.background_mobjects, *mobjects)# TODO, this conflicts with Scene.add_fore- def add_foreground_mobject(self, *mobjects):+ def add_foreground_mobject(self, *mobjects: Mobject):"""Adds the mobjects to the special listself.foreground_mobjects.Parameters----------- *mobjects : Mobject+ *mobjectsThe mobjects to add to the list"""self.add_special_mobjects(self.foreground_mobjects, *mobjects)- def add_transformable_mobject(self, *mobjects):+ def add_transformable_mobject(self, *mobjects: Mobject):"""Adds the mobjects to the special listself.transformable_mobjects.Parameters----------- *mobjects : Mobject+ *mobjectsThe mobjects to add to the list."""self.add_special_mobjects(self.transformable_mobjects, *mobjects)- def add_moving_mobject(self, mobject, target_mobject=None):+ def add_moving_mobject(+ self, mobject: Mobject, target_mobject: Mobject | None = None+ ):"""Adds the mobject to the special listself.moving_mobject, and adds a property@@ -708,28 +723,30 @@ class LinearTransformationScene(VectorScene):Parameters----------- mobject : Mobject+ mobjectThe mobjects to add to the list- target_mobject : Mobject, optional+ target_mobjectWhat the moving_mobject goes to, etc."""mobject.target = target_mobjectself.add_special_mobjects(self.moving_mobjects, mobject)- def get_unit_square(self, color=YELLOW, opacity=0.3, stroke_width=3):+ def get_unit_square(+ self, color: str = YELLOW, opacity: float = 0.3, stroke_width: float = 3+ ):"""Returns a unit square for the current NumberPlane.Parameters----------- color : str, optional+ colorThe string of the hex color code of the color wanted.- opacity : float, int, optional+ opacityThe opacity of the square- stroke_width : int, float, optional+ stroke_widthThe stroke_width in pixels of the border of the squareReturns@@ -748,14 +765,14 @@ class LinearTransformationScene(VectorScene):square.move_to(self.plane.coords_to_point(0, 0), DL)return square- def add_unit_square(self, animate=False, **kwargs):+ def add_unit_square(self, animate: bool = False, **kwargs):"""Adds a unit square to the scene viaself.get_unit_square.Parameters----------- animate (bool)+ animateWhether or not to animate the additionwith DrawBorderThenFill.**kwargs@@ -778,18 +795,20 @@ class LinearTransformationScene(VectorScene):self.square = squarereturn self- def add_vector(self, vector, color=YELLOW, **kwargs):+ def add_vector(+ self, vector: Arrow | list | tuple | np.ndarray, color: str = YELLOW, **kwargs+ ):"""Adds a vector to the scene, and puts it in the speciallist self.moving_vectors.Parameters----------- vector : Arrow,list,tuple,np.ndarray+ vectorIt can be a pre-made graphical vector, or thecoordinates of one.- color : str+ colorThe string of the hex color of the vector.This is only taken into consideration if'vector' is not an Arrow. Defaults to YELLOW.@@ -806,7 +825,7 @@ class LinearTransformationScene(VectorScene):self.moving_vectors.append(vector)return vector- def write_vector_coordinates(self, vector, **kwargs):+ def write_vector_coordinates(self, vector: Arrow, **kwargs):"""Returns a column matrix indicating the vector coordinates,after writing them to the screen, and adding them to the@@ -814,7 +833,7 @@ class LinearTransformationScene(VectorScene):Parameters----------- vector : Arrow+ vectorThe arrow representing the vector.**kwargs@@ -830,7 +849,12 @@ class LinearTransformationScene(VectorScene):return coordsdef add_transformable_label(- self, vector, label, transformation_name="L", new_label=None, **kwargs+ self,+ vector: Vector,+ label: MathTex | str,+ transformation_name: str | MathTex = "L",+ new_label: str | MathTex | None = None,+ **kwargs,):"""Method for creating, and animating the addition of@@ -838,16 +862,16 @@ class LinearTransformationScene(VectorScene):Parameters----------- vector : Vector+ vectorThe vector for which the label must be added.- label : Union[:class:`~.MathTex`, :class:`str`]+ labelThe MathTex/string of the label.- transformation_name : Union[:class:`str`, :class:`~.MathTex`], optional+ transformation_nameThe name to give the transformation as a label.- new_label : Union[:class:`str`, :class:`~.MathTex`], optional+ new_labelWhat the label should display after a Linear Transformation**kwargs@@ -873,7 +897,12 @@ class LinearTransformationScene(VectorScene):self.transformable_labels.append(label_mob)return label_mob- def add_title(self, title, scale_factor=1.5, animate=False):+ def add_title(+ self,+ title: str | MathTex | Tex,+ scale_factor: float = 1.5,+ animate: bool = False,+ ):"""Adds a title, after scaling it, adding a background rectangle,moving it to the top and adding it to foreground_mobjects adding@@ -881,13 +910,13 @@ class LinearTransformationScene(VectorScene):Parameters----------- title : Union[:class:`str`, :class:`~.MathTex`, :class:`~.Tex`]+ titleWhat the title should be.- scale_factor : int, float, optional+ scale_factorHow much the title should be scaled by.- animate : bool+ animateWhether or not to animate the addition.Returns@@ -905,19 +934,21 @@ class LinearTransformationScene(VectorScene):self.title = titlereturn self- def get_matrix_transformation(self, matrix):+ def get_matrix_transformation(self, matrix: np.ndarray | list | tuple):"""Returns a function corresponding to the lineartransformation represented by the matrix passed.Parameters----------- matrix : np.ndarray, list, tuple+ matrixThe matrix."""return self.get_transposed_matrix_transformation(np.array(matrix).T)- def get_transposed_matrix_transformation(self, transposed_matrix):+ def get_transposed_matrix_transformation(+ self, transposed_matrix: np.ndarray | list | tuple+ ):"""Returns a function corresponding to the lineartransformation represented by the transposed@@ -925,7 +956,7 @@ class LinearTransformationScene(VectorScene):Parameters----------- matrix : np.ndarray, list, tuple+ transposed_matrixThe matrix."""transposed_matrix = np.array(transposed_matrix)@@ -937,7 +968,7 @@ class LinearTransformationScene(VectorScene):raise ValueError("Matrix has bad dimensions")return lambda point: np.dot(point, transposed_matrix)- def get_piece_movement(self, pieces):+ def get_piece_movement(self, pieces: list | tuple | np.ndarray):"""This method returns an animation that moves an arbitrarymobject in "pieces" to its corresponding .target value.@@ -946,7 +977,7 @@ class LinearTransformationScene(VectorScene):Parameters----------- pieces : list, tuple, np.array+ piecesThe pieces for which the movement must be shown.Returns@@ -960,7 +991,7 @@ class LinearTransformationScene(VectorScene):self.add(start.copy().fade(0.7))return Transform(start, target, lag_ratio=0)- def get_moving_mobject_movement(self, func):+ def get_moving_mobject_movement(self, func: Callable[[np.ndarray], np.ndarray]):"""This method returns an animation that moves a mobjectin "self.moving_mobjects" to its corresponding .target value.@@ -969,7 +1000,7 @@ class LinearTransformationScene(VectorScene):Parameters----------- func : function+ funcThe function that determines where the .target ofthe moving mobject goes.@@ -985,7 +1016,7 @@ class LinearTransformationScene(VectorScene):m.target.move_to(target_point)return self.get_piece_movement(self.moving_mobjects)- def get_vector_movement(self, func):+ def get_vector_movement(self, func: Callable[[np.ndarray], np.ndarray]):"""This method returns an animation that moves a mobjectin "self.moving_vectors" to its corresponding .target value.@@ -994,7 +1025,7 @@ class LinearTransformationScene(VectorScene):Parameters----------- func : function+ funcThe function that determines where the .target ofthe moving mobject goes.@@ -1026,7 +1057,7 @@ class LinearTransformationScene(VectorScene):)return self.get_piece_movement(self.transformable_labels)- def apply_matrix(self, matrix, **kwargs):+ def apply_matrix(self, matrix: np.ndarray | list | tuple, **kwargs):"""Applies the transformation represented by thegiven matrix to the number plane, and each vector/similar@@ -1034,14 +1065,14 @@ class LinearTransformationScene(VectorScene):Parameters----------- matrix : np.ndarray, list, tuple+ matrixThe matrix.**kwargsAny valid keyword argument of self.apply_transposed_matrix()"""self.apply_transposed_matrix(np.array(matrix).T, **kwargs)- def apply_inverse(self, matrix, **kwargs):+ def apply_inverse(self, matrix: np.ndarray | list | tuple, **kwargs):"""This method applies the linear transformationrepresented by the inverse of the passed matrix@@ -1049,14 +1080,16 @@ class LinearTransformationScene(VectorScene):Parameters----------- matrix : np.ndarray, list, tuple+ matrixThe matrix whose inverse is to be applied.**kwargsAny valid keyword argument of self.apply_matrix()"""self.apply_matrix(np.linalg.inv(matrix), **kwargs)- def apply_transposed_matrix(self, transposed_matrix, **kwargs):+ def apply_transposed_matrix(+ self, transposed_matrix: np.ndarray | list | tuple, **kwargs+ ):"""Applies the transformation represented by thegiven transposed matrix to the number plane,@@ -1064,7 +1097,7 @@ class LinearTransformationScene(VectorScene):Parameters----------- matrix : np.ndarray, list, tuple+ transposed_matrixThe matrix.**kwargsAny valid keyword argument of self.apply_function()@@ -1077,7 +1110,7 @@ class LinearTransformationScene(VectorScene):kwargs["path_arc"] = net_rotationself.apply_function(func, **kwargs)- def apply_inverse_transpose(self, t_matrix, **kwargs):+ def apply_inverse_transpose(self, t_matrix: np.ndarray | list | tuple, **kwargs):"""Applies the inverse of the transformation representedby the given transposed matrix to the number plane and each@@ -1085,7 +1118,7 @@ class LinearTransformationScene(VectorScene):Parameters----------- matrix : np.ndarray, list, tuple+ t_matrixThe matrix.**kwargsAny valid keyword argument of self.apply_transposed_matrix()@@ -1093,7 +1126,9 @@ class LinearTransformationScene(VectorScene):t_inv = np.linalg.inv(np.array(t_matrix).T).Tself.apply_transposed_matrix(t_inv, **kwargs)- def apply_nonlinear_transformation(self, function, **kwargs):+ def apply_nonlinear_transformation(+ self, function: Callable[[np.ndarray], np.ndarray], **kwargs+ ):"""Applies the non-linear transformation representedby the given function to the number plane and each@@ -1101,7 +1136,7 @@ class LinearTransformationScene(VectorScene):Parameters----------- function : Function+ functionThe function.**kwargsAny valid keyword argument of self.apply_function()@@ -1109,7 +1144,12 @@ class LinearTransformationScene(VectorScene):self.plane.prepare_for_nonlinear_transform()self.apply_function(function, **kwargs)- def apply_function(self, function, added_anims=[], **kwargs):+ def apply_function(+ self,+ function: Callable[[np.ndarray], np.ndarray],+ added_anims: list = [],+ **kwargs,+ ):"""Applies the given function to each of the mobjects inself.transformable_mobjects, and plays the animation showing@@ -1117,11 +1157,11 @@ class LinearTransformationScene(VectorScene):Parameters----------- function : Function+ functionThe function that affects each pointof each mobject in self.transformable_mobjects.- added_anims : list, optional+ added_animsAny other animations that need to be playedsimultaneously with this.diff --git a/manim/scene/zoomed_scene.py b/manim/scene/zoomed_scene.pyindex 06bc2213e..361c4eaf5 100644--- a/manim/scene/zoomed_scene.py+++ b/manim/scene/zoomed_scene.py@@ -132,14 +132,14 @@ class ZoomedScene(MovingCameraScene):self.zoomed_camera = zoomed_cameraself.zoomed_display = zoomed_display- def activate_zooming(self, animate=False):+ def activate_zooming(self, animate: bool = False):"""This method is used to activate the zooming forthe zoomed_camera.Parameters----------- animate : bool, optional+ animateWhether or not to animate the activationof the zoomed camera."""@@ -153,13 +153,13 @@ class ZoomedScene(MovingCameraScene):self.zoomed_display,)- def get_zoom_in_animation(self, run_time=2, **kwargs):+ def get_zoom_in_animation(self, run_time: float = 2, **kwargs):"""Returns the animation of camera zooming in.Parameters----------- run_time : int or float, optional+ run_timeThe run_time of the animation of the camera zooming in.**kwargsAny valid keyword arguments of ApplyMethod()diff --git a/manim/utils/bezier.py b/manim/utils/bezier.pyindex adf40bba0..79d93f764 100644--- a/manim/utils/bezier.py+++ b/manim/utils/bezier.py@@ -38,7 +38,7 @@ def bezier(Parameters----------- points : np.ndarray+ pointspoints defining the desired bezier curve.Returns@@ -78,11 +78,11 @@ def partial_bezier_points(points: np.ndarray, a: float, b: float) -> np.ndarray:Parameters----------- points : np.ndarray+ pointsset of points defining the bezier curve.- a : float+ alower bound of the desired partial bezier curve.- b : float+ bupper bound of the desired partial bezier curve.Returns@@ -353,7 +353,7 @@ def get_smooth_handle_points(Parameters----------- points : np.ndarray+ pointsAnchors.Returnsdiff --git a/manim/utils/caching.py b/manim/utils/caching.pyindex 4e776d977..cabecd656 100644--- a/manim/utils/caching.py+++ b/manim/utils/caching.py@@ -1,10 +1,12 @@from __future__ import annotations+from typing import Callable+from .. import config, loggerfrom ..utils.hashing import get_hash_from_play_call-def handle_caching_play(func):+def handle_caching_play(func: Callable[..., None]):"""Decorator that returns a wrapped version of func that will computethe hash of the play invocation.@@ -14,7 +16,7 @@ def handle_caching_play(func):Parameters----------- func : Callable[[...], None]+ funcThe play like function that has to be written to the video file stream.Take the same parameters as `scene.play`."""diff --git a/manim/utils/family.py b/manim/utils/family.pyindex d4f31fbb3..3669ed203 100644--- a/manim/utils/family.py+++ b/manim/utils/family.py@@ -1,15 +1,16 @@from __future__ import annotationsimport itertools as it+from typing import Iterablefrom ..mobject.mobject import Mobjectfrom ..utils.iterables import remove_list_redundanciesdef extract_mobject_family_members(- mobjects,+ mobjects: Iterable[Mobject],use_z_index=False,- only_those_with_points=False,+ only_those_with_points: bool = False,):"""Returns a list of the types of mobjects and their family members present.A "family" in this context refers to a mobject, its submobjects, and their@@ -17,9 +18,9 @@ def extract_mobject_family_members(Parameters----------- mobjects : Mobject+ mobjectsThe Mobjects currently in the Scene- only_those_with_points : bool, optional+ only_those_with_pointsWhether or not to only do this forthose mobjects that have points. By default Falsediff --git a/manim/utils/file_ops.py b/manim/utils/file_ops.pyindex 6a5a7f1f7..1bbb04821 100644--- a/manim/utils/file_ops.py+++ b/manim/utils/file_ops.py@@ -175,12 +175,12 @@ def seek_full_path_from_defaults(raise OSError(error)-def modify_atime(file_path) -> None:+def modify_atime(file_path: str) -> None:"""Will manually change the accessed time (called `atime`) of the file, as on a lot of OS the accessed time refresh is disabled by default.Parameters----------- file_path : :class:`str`+ file_pathThe path of the file."""os.utime(file_path, times=(time.time(), os.path.getmtime(file_path)))@@ -248,12 +248,12 @@ def get_template_path() -> Path:return Path.resolve(Path(__file__).parent.parent / "templates")-def add_import_statement(file):+def add_import_statement(file: Path):"""Prepends an import statement in a fileParameters----------- file : :class:`Path`+ file"""with file.open("r+") as f:import_line = "from manim import *"@@ -269,9 +269,9 @@ def copy_template_files(Parameters----------- project_dir : :class:`Path`+ project_dirPath to project directory.- template_name : :class:`str`+ template_nameName of template."""template_cfg_path = Path.resolve(diff --git a/manim/utils/hashing.py b/manim/utils/hashing.pyindex f84f2770d..60e4422f1 100644--- a/manim/utils/hashing.py+++ b/manim/utils/hashing.py@@ -14,8 +14,15 @@ from typing import Anyimport numpy as np+from manim.animation.animation import Animation+from manim.camera.camera import Camera+from manim.mobject.mobject import Mobject+from .. import config, logger+if typing.TYPE_CHECKING:+ from manim.scene.scene import Scene+# Sometimes there are elements that are not suitable for hashing (too long or# run-dependent). This is used to filter them out.KEYS_TO_FILTER_OUT = {@@ -50,14 +57,14 @@ class _Memoizer:cls._already_processed.clear()@classmethod- def check_already_processed_decorator(cls: _Memoizer, is_method=False):+ def check_already_processed_decorator(cls: _Memoizer, is_method: bool = False):"""Decorator to handle the arguments that goes through the decorated function.Returns _ALREADY_PROCESSED_PLACEHOLDER if the obj has been processed, or letsthe decorated function call go ahead.Parameters----------- is_method : bool, optional+ is_methodWhether the function passed is a method, by default False."""@@ -81,7 +88,7 @@ class _Memoizer:Parameters----------- obj : Any+ objThe object to check.Returns@@ -98,7 +105,7 @@ class _Memoizer:Parameters----------- obj : Any+ objThe object to mark as processed."""cls._handle_already_processed(obj, lambda x: x)@@ -164,7 +171,7 @@ class _Memoizer:class _CustomEncoder(json.JSONEncoder):- def default(self, obj):+ def default(self, obj: Any):"""This method is used to serialize objects to JSON format.@@ -178,7 +185,7 @@ class _CustomEncoder(json.JSONEncoder):Parameters----------- obj : Any+ objArbitrary object to convertReturns@@ -225,7 +232,7 @@ class _CustomEncoder(json.JSONEncoder):# Serialize it with only the type of the object. You can change this to whatever string when debugging the serialization process.return str(type(obj))- def _cleaned_iterable(self, iterable):+ def _cleaned_iterable(self, iterable: typing.Iterable[Any]):"""Check for circular reference at each iterable that will go through the JSONEncoder, as well as key of the wrong format.If a key with a bad format is found (i.e not a int, string, or float), it gets replaced byt its hash using the same process implemented here.@@ -233,7 +240,7 @@ class _CustomEncoder(json.JSONEncoder):Parameters----------- iterable : Iterable[Any]+ iterableThe iterable to check."""@@ -278,12 +285,12 @@ class _CustomEncoder(json.JSONEncoder):elif isinstance(iterable, dict):return _iter_check_dict(iterable)- def encode(self, obj):+ def encode(self, obj: Any):"""Overriding of :meth:`JSONEncoder.encode`, to make our own process.Parameters----------- obj: Any+ objThe object to encode in JSON.Returns@@ -297,12 +304,12 @@ class _CustomEncoder(json.JSONEncoder):return super().encode(obj)-def get_json(obj):+def get_json(obj: dict):"""Recursively serialize `object` to JSON using the :class:`CustomEncoder` class.Parameters----------- dict_config : :class:`dict`+ objThe dict to flattenReturns@@ -314,25 +321,25 @@ def get_json(obj):def get_hash_from_play_call(- scene_object,- camera_object,- animations_list,- current_mobjects_list,+ scene_object: Scene,+ camera_object: Camera,+ animations_list: typing.Iterable[Animation],+ current_mobjects_list: typing.Iterable[Mobject],) -> str:"""Take the list of animations and a list of mobjects and output their hashes. This is meant to be used for `scene.play` function.Parameters------------ scene_object : :class:`~.Scene`+ scene_objectThe scene object.- camera_object : :class:`~.Camera`+ camera_objectThe camera object used in the scene.- animations_list : Iterable[:class:`~.Animation`]+ animations_listThe list of animations.- current_mobjects_list : Iterable[:class:`~.Mobject`]+ current_mobjects_listThe list of mobjects.Returnsdiff --git a/manim/utils/space_ops.py b/manim/utils/space_ops.pyindex 3932e5bd7..fe5fb8f13 100644--- a/manim/utils/space_ops.py+++ b/manim/utils/space_ops.py@@ -114,7 +114,7 @@ def quaternion_from_angle_axis(The angle for the quaternion.axisThe axis for the quaternion- axis_normalized : bool, optional+ axis_normalizedChecks whether the axis is normalized, by default FalseReturns@@ -267,7 +267,7 @@ def rotation_about_z(angle: float) -> np.ndarray:Parameters----------- angle : float+ angleAngle for the rotation matrix.Returnsdiff --git a/manim/utils/testing/frames_comparison.py b/manim/utils/testing/frames_comparison.pyindex 775219a87..e20e1a2a5 100644--- a/manim/utils/testing/frames_comparison.py+++ b/manim/utils/testing/frames_comparison.py@@ -45,10 +45,6 @@ def frames_comparison(Parameters----------- test_name- The name of the test.- module_name- The module which the test belongs to.last_framewhether the test should test the last frame, by default True.renderer_class@@ -161,7 +157,7 @@ def _make_test_comparing_frames(file_path: Path,base_scene: type[Scene],construct: Callable[[Scene], None],- renderer_class, # Renderer type, there is no superclass renderer yet .....+ renderer_class: type, # Renderer type, there is no superclass renderer yet .....is_set_test_data_test: bool,last_frame: bool,show_diff: bool,@@ -171,15 +167,15 @@ def _make_test_comparing_frames(Parameters----------- file_path : Path+ file_pathThe path of the control frames.- base_scene : Type[Scene]+ base_sceneThe base scene class.- construct : Callable[[Scene], None]+ constructThe construct method (= the test function)- renderer_class : [type]+ renderer_classThe renderer base class.- show_diff : bool+ show_diffwhether to visually show_diff (see --show_diff)Returnsdiff --git a/manim/utils/tex.py b/manim/utils/tex.pyindex 6e881ecfa..d8751e091 100644--- a/manim/utils/tex.py+++ b/manim/utils/tex.py@@ -18,17 +18,17 @@ class TexTemplate:Parameters----------- tex_compiler : Optional[:class:`str`], optional+ tex_compilerThe TeX compiler to be used, e.g. ``latex``, ``pdflatex`` or ``lualatex``- output_format : Optional[:class:`str`], optional+ output_formatThe output format resulting from compilation, e.g. ``.dvi`` or ``.pdf``- documentclass : Optional[:class:`str`], optional+ documentclassThe command defining the documentclass, e.g. ``\\documentclass[preview]{standalone}``- preamble : Optional[:class:`str`], optional+ preambleThe document's preamble, i.e. the part between ``\\documentclass`` and ``\\begin{document}``- placeholder_text : Optional[:class:`str`], optional+ placeholder_textText in the document that will be replaced by the expression to be rendered- post_doc_commands : Optional[:class:`str`], optional+ post_doc_commandsText (definitions, commands) to be inserted at right after ``\\begin{document}``, e.g. ``\\boldmath``Attributes@@ -60,12 +60,12 @@ class TexTemplate:def __init__(self,- tex_compiler=None,- output_format=None,- documentclass=None,- preamble=None,- placeholder_text=None,- post_doc_commands=None,+ tex_compiler: str | None = None,+ output_format: str | None = None,+ documentclass: str | None = None,+ preamble: str | None = None,+ placeholder_text: str | None = None,+ post_doc_commands: str | None = None,**kwargs,):self.tex_compiler = (@@ -124,14 +124,14 @@ class TexTemplate:+ "\n")- def add_to_preamble(self, txt, prepend=False):+ def add_to_preamble(self, txt: str, prepend: bool = False):"""Adds stuff to the TeX template's preamble (e.g. definitions, packages). Text can be inserted at the beginning or at the end of the preamble.Parameters----------- txt : :class:`string`+ txtString containing the text to be added, e.g. ``\\usepackage{hyperref}``- prepend : Optional[:class:`bool`], optional+ prependWhether the text should be added at the beginning of the preamble, i.e. right after ``\\documentclass``. Default is to add it at the end of the preamble, i.e. right before ``\\begin{document}``"""if prepend:@@ -140,23 +140,23 @@ class TexTemplate:self.preamble += "\n" + txtself._rebuild()- def add_to_document(self, txt):+ def add_to_document(self, txt: str):"""Adds txt to the TeX template just after \\begin{document}, e.g. ``\\boldmath``Parameters----------- txt : :class:`str`+ txtString containing the text to be added."""self.post_doc_commands += "\n" + txt + "\n"self._rebuild()- def get_texcode_for_expression(self, expression):+ def get_texcode_for_expression(self, expression: str):"""Inserts expression verbatim into TeX template.Parameters----------- expression : :class:`str`+ expressionThe string containing the expression to be typeset, e.g. ``$\\sqrt{2}$``Returns@@ -166,13 +166,13 @@ class TexTemplate:"""return self.body.replace(self.placeholder_text, expression)- def _texcode_for_environment(self, environment):+ def _texcode_for_environment(self, environment: str):"""Processes the tex_environment string to return the correct ``\\begin{environment}[extra]{extra}`` and``\\end{environment}`` stringsParameters----------- environment : :class:`str`+ environmentThe tex_environment as a string. Acceptable formats include:``{align*}``, ``align*``, ``{tabular}[t]{cccl}``, ``tabular}{cccl``, ``\\begin{tabular}[t]{cccl}``.@@ -204,14 +204,14 @@ class TexTemplate:return begin, end- def get_texcode_for_expression_in_env(self, expression, environment):+ def get_texcode_for_expression_in_env(self, expression: str, environment: str):r"""Inserts expression into TeX template wrapped in \begin{environment} and \end{environment}Parameters----------- expression : :class:`str`+ expressionThe string containing the expression to be typeset, e.g. ``$\\sqrt{2}$``- environment : :class:`str`+ environmentThe string containing the environment in which the expression should be typeset, e.g. ``align*``Returns@@ -231,25 +231,10 @@ class TexTemplateFromFile(TexTemplate):Parameters----------- tex_compiler : Optional[:class:`str`], optional- The TeX compiler to be used, e.g. ``latex``, ``pdflatex`` or ``lualatex``- output_format : Optional[:class:`str`], optional- The output format resulting from compilation, e.g. ``.dvi`` or ``.pdf``- documentclass : Optional[:class:`str`], optional- The command defining the documentclass, e.g. ``\\documentclass[preview]{standalone}``- preamble : Optional[:class:`str`], optional- The document's preamble, i.e. the part between ``\\documentclass`` and ``\\begin{document}``- placeholder_text : Optional[:class:`str`], optional- Text in the document that will be replaced by the expression to be rendered- post_doc_commands : Optional[:class:`str`], optional- Text (definitions, commands) to be inserted at right after ``\\begin{document}``, e.g. ``\\boldmath``- kwargs : :class:`str`- The kwargs specified can only be strings.-- Other Parameters- ----------------tex_filenamePath to a valid TeX template file+ kwargs+ Arguments for :class:`~.TexTemplate`.Attributes----------diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.pyindex d53acbe0a..5423c80c8 100644--- a/manim/utils/tex_file_writing.py+++ b/manim/utils/tex_file_writing.py@@ -14,6 +14,8 @@ import reimport unicodedatafrom pathlib import Path+from manim.utils.tex import TexTemplate+from .. import config, logger@@ -25,16 +27,20 @@ def tex_hash(expression):return hasher.hexdigest()[:16]-def tex_to_svg_file(expression, environment=None, tex_template=None):+def tex_to_svg_file(+ expression: str,+ environment: str | None = None,+ tex_template: TexTemplate | None = None,+):"""Takes a tex expression and returns the svg version of the compiled texParameters----------- expression : :class:`str`+ expressionString containing the TeX expression to be rendered, e.g. ``\\sqrt{2}`` or ``foo``- environment : Optional[:class:`str`], optional+ environmentThe string containing the environment in which the expression should be typeset, e.g. ``align*``- tex_template : Optional[:class:`~.TexTemplate`], optional+ tex_templateTemplate class used to typesetting. If not set, use default template set via `config["tex_template"]`Returns@@ -53,17 +59,21 @@ def tex_to_svg_file(expression, environment=None, tex_template=None):return convert_to_svg(dvi_file, tex_template.output_format)-def generate_tex_file(expression, environment=None, tex_template=None):+def generate_tex_file(+ expression: str,+ environment: str | None = None,+ tex_template: TexTemplate | None = None,+):"""Takes a tex expression (and an optional tex environment),and returns a fully formed tex file ready for compilation.Parameters----------- expression : :class:`str`+ expressionString containing the TeX expression to be rendered, e.g. ``\\sqrt{2}`` or ``foo``- environment : Optional[:class:`str`], optional+ environmentThe string containing the environment in which the expression should be typeset, e.g. ``align*``- tex_template : Optional[:class:`~.TexTemplate`], optional+ tex_templateTemplate class used to typesetting. If not set, use default template set via `config["tex_template"]`Returns@@ -196,16 +206,16 @@ def compile_tex(tex_file: Path, tex_compiler: str, output_format: str) -> Path:return result-def convert_to_svg(dvi_file, extension, page=1):+def convert_to_svg(dvi_file: Path, extension: str, page: int = 1):"""Converts a .dvi, .xdv, or .pdf file into an svg using dvisvgm.Parameters----------- dvi_file : :class:`Path`+ dvi_fileFile name of the input file to be converted.- extension : :class:`str`+ extensionString containing the file extension and thus indicating the file type, e.g. ``.dvi`` or ``.pdf``- page : Optional[:class:`int`], optional+ pagePage to be converted if input file is multi-page.Returnsdiff --git a/scripts/template_docsting_with_example.py b/scripts/template_docsting_with_example.pyindex 4a8621b5e..ce2466dbd 100644--- a/scripts/template_docsting_with_example.py+++ b/scripts/template_docsting_with_example.py@@ -13,7 +13,7 @@ class SomeClass:Parameters----------- scale_factor : :class:`float`+ scale_factorThe factor used for scaling.Returnsdiff --git a/tests/helpers/graphical_units.py b/tests/helpers/graphical_units.pyindex f6568d6ff..b202217b0 100644--- a/tests/helpers/graphical_units.py+++ b/tests/helpers/graphical_units.py@@ -9,17 +9,18 @@ from pathlib import Pathimport numpy as npfrom manim import config, logger+from manim.scene.scene import Scene-def set_test_scene(scene_object, module_name):+def set_test_scene(scene_object: type[Scene], module_name: str):"""Function used to set up the test data for a new feature. This will basically set up a pre-rendered frame for a scene. This is meant to be used onlywhen setting up tests. Please refer to the wiki.Parameters----------- scene_object : :class:`~.Scene`+ scene_objectThe scene with which we want to set up a new test.- module_name : :class:`str`+ module_nameThe name of the module in which the functionality tested is contained. For example, ``Write`` is contained in the module ``creation``. This will be used in the folder architectureof ``/tests_data``.diff --git a/tests/utils/GraphicalUnitTester.py b/tests/utils/GraphicalUnitTester.pyindex 18fe373c5..02128221c 100644--- a/tests/utils/GraphicalUnitTester.py+++ b/tests/utils/GraphicalUnitTester.py@@ -8,6 +8,7 @@ import numpy as npfrom manim import config, tempconfigfrom manim.renderer.opengl_renderer import OpenGLRenderer+from manim.scene.scene import Sceneclass GraphicalUnitTester:@@ -15,11 +16,9 @@ class GraphicalUnitTester:Parameters----------- scene_class : :class:`~.Scene`+ scene_classThe scene to be tested- config_scene : :class:`dict`- The configuration of the scene- module_tested : :class:`str`+ module_testedThe name of the module tested. i.e if we are testing functions of creation.py, the module will be "creation"Attributes@@ -32,7 +31,9 @@ class GraphicalUnitTester:The scene tested"""- def __init__(self, scene_class, module_tested, tmpdir, rgb_atol=0):+ def __init__(+ self, scene_class: type[Scene], module_tested: str, tmpdir, rgb_atol=0+ ):# Disable the the logs, (--quiet is broken) TODOlogging.disable(logging.CRITICAL)tests_directory = Path(__file__).absolute().parent.parentdiff --git a/tests/utils/testing_utils.py b/tests/utils/testing_utils.pyindex 8c4729742..f87dda4d7 100644--- a/tests/utils/testing_utils.py+++ b/tests/utils/testing_utils.py@@ -4,12 +4,12 @@ import inspectimport sys-def get_scenes_to_test(module_name):+def get_scenes_to_test(module_name: str):"""Get all Test classes of the module from which it is called. Used to fetch all the SceneTest of the module.Parameters----------- module_name : :class:`str`+ module_nameThe name of the module tested.Returns