A community-maintained Python framework for creating mathematical animations.
Remove old str.format() syntax and change to f-Strings (#867)
Philipp Imhof1b57ef38a0f6
diff --git a/manim/animation/numbers.py b/manim/animation/numbers.pyindex b0285d48a..30209daf5 100644--- a/manim/animation/numbers.py+++ b/manim/animation/numbers.py@@ -17,7 +17,7 @@ class ChangingDecimal(Animation):decimal_mob: DecimalNumber,number_update_func: typing.Callable[[float], float],suspend_mobject_updating: typing.Optional[bool] = False,- **kwargs+ **kwargs,) -> None:self.check_validity_of_input(decimal_mob)self.yell_about_depricated_configuration(**kwargs)@@ -36,14 +36,12 @@ class ChangingDecimal(Animation):for attr in ["tracked_mobject", "position_update_func"]:if attr in kwargs:warnings.warn(- """- Don't use {} for ChangingDecimal,+ f"""+ Don't use {attr} for ChangingDecimal,that functionality has been depricatedand you should use a mobject updaterinstead- """.format(- attr- )+ """)def interpolate_mobject(self, alpha: float) -> None:diff --git a/manim/animation/transform.py b/manim/animation/transform.pyindex 263d4a0ce..da5494919 100644--- a/manim/animation/transform.py+++ b/manim/animation/transform.py@@ -47,7 +47,7 @@ class Transform(Animation):path_arc: float = 0,path_arc_axis: np.ndarray = OUT,replace_mobject_with_target_in_scene: bool = False,- **kwargs+ **kwargs,) -> None:self.path_arc = path_arcself.path_func = path_func@@ -87,8 +87,9 @@ class Transform(Animation):def check_target_mobject_validity(self) -> None:if self.target_mobject is None:- message = "{}.create_target not properly implemented"- raise NotImplementedError(message.format(self.__class__.__name__))+ raise NotImplementedError(+ f"{self.__class__.__name__}.create_target not properly implemented"+ )def clean_up_from_scene(self, scene: "Scene") -> None:super().clean_up_from_scene(scene)@@ -159,7 +160,7 @@ class ClockwiseTransform(Transform):mobject: Mobject,target_mobject: Mobject,path_arc: float = -np.pi,- **kwargs+ **kwargs,) -> None:super().__init__(mobject, target_mobject, path_arc=path_arc, **kwargs)@@ -170,7 +171,7 @@ class CounterclockwiseTransform(Transform):mobject: Mobject,target_mobject: Mobject,path_arc: float = np.pi,- **kwargs+ **kwargs,) -> None:super().__init__(mobject, target_mobject, path_arc=path_arc, **kwargs)@@ -252,7 +253,7 @@ class ApplyPointwiseFunction(ApplyMethod):function: types.MethodType,mobject: Mobject,run_time: float = DEFAULT_POINTWISE_FUNCTION_RUN_TIME,- **kwargs+ **kwargs,) -> None:super().__init__(mobject.apply_function, function, run_time=run_time, **kwargs)@@ -362,7 +363,7 @@ class TransformAnimations(Transform):start_anim: Animation,end_anim: Animation,rate_func: typing.Callable = squish_rate_func(smooth),- **kwargs+ **kwargs,) -> None:self.start_anim = start_animself.end_anim = end_animdiff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.pyindex 17636e537..190150ce2 100644--- a/manim/mobject/mobject.py+++ b/manim/mobject/mobject.py@@ -1254,9 +1254,10 @@ class Mobject(Container):# Errorsdef throw_error_if_no_points(self):if self.has_no_points():- message = "Cannot call Mobject.{} " + "for a Mobject with no points"caller_name = sys._getframe(1).f_code.co_name- raise Exception(message.format(caller_name))+ raise Exception(+ f"Cannot call Mobject.{caller_name} for a Mobject with no points"+ )# About z-indexdef set_z_index(self, z_index_value):diff --git a/manim/mobject/svg/code_mobject.py b/manim/mobject/svg/code_mobject.pyindex d33580983..983995a4e 100644--- a/manim/mobject/svg/code_mobject.py+++ b/manim/mobject/svg/code_mobject.py@@ -153,14 +153,14 @@ class Code(VGroup):style="vim",language=None,generate_html_file=False,- **kwargs+ **kwargs,):VGroup.__init__(self,stroke_width=stroke_width,background_stroke_color=background_stroke_color,background_stroke_width=background_stroke_width,- **kwargs+ **kwargs,)self.tab_width = tab_widthself.line_spacing = line_spacing@@ -247,7 +247,7 @@ class Code(VGroup):self.background_mobject,Dot(fill_opacity=0, stroke_opacity=0),self.code,- **kwargs+ **kwargs,)self.move_to(np.array([0, 0, 0]))@@ -263,8 +263,9 @@ class Code(VGroup):if os.path.exists(path):self.file_path = pathreturn- error = "From: {}, could not find {} at either of these locations: {}".format(- os.getcwd(), self.file_name, possible_paths+ error = (+ f"From: {os.getcwd()}, could not find {self.file_name} at either "+ + "of these locations: {possible_paths}")raise IOError(error)@@ -286,7 +287,7 @@ class Code(VGroup):alignment="right",font=self.font,disable_ligatures=True,- stroke_width=self.stroke_width+ stroke_width=self.stroke_width,).scale(self.scale_factor)for i in line_numbers:i.set_color(self.default_color)@@ -312,7 +313,7 @@ class Code(VGroup):tab_width=self.tab_width,font=self.font,disable_ligatures=True,- stroke_width=self.stroke_width+ stroke_width=self.stroke_width,).scale(self.scale_factor)for line_no in range(code.__len__()):line = code.chars[line_no]diff --git a/manim/mobject/svg/svg_mobject.py b/manim/mobject/svg/svg_mobject.pyindex b5cf62839..6fbf29214 100644--- a/manim/mobject/svg/svg_mobject.py+++ b/manim/mobject/svg/svg_mobject.py@@ -79,7 +79,7 @@ class SVGMobject(VMobject):unpack_groups=True, # if False, creates a hierarchy of VGroupsstroke_width=DEFAULT_STROKE_WIDTH,fill_opacity=1.0,- **kwargs+ **kwargs,):self.file_name = file_name or self.file_nameself.ensure_valid_file()@@ -120,9 +120,7 @@ class SVGMobject(VMobject):if os.path.exists(path):self.file_path = pathreturn- error = "From: {}, could not find {} at either of these locations: {}".format(- os.getcwd(), self.file_name, possible_paths- )+ error = f"From: {os.getcwd()}, could not find {self.file_name} at either of these locations: {possible_paths}"raise IOError(error)def generate_points(self):diff --git a/manim/mobject/svg/tex_mobject.py b/manim/mobject/svg/tex_mobject.pyindex 7eb65746f..50b05b4ed 100644--- a/manim/mobject/svg/tex_mobject.py+++ b/manim/mobject/svg/tex_mobject.py@@ -534,7 +534,7 @@ class BulletedList(Tex):elif isinstance(arg, int):part = self.submobjects[arg]else:- raise TypeError("Expected int or string, got {0}".format(arg))+ raise TypeError(f"Expected int or string, got {arg}")for other_part in self.submobjects:if other_part is part:other_part.set_fill(opacity=1)diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.pyindex a74d7e4ea..2e45088dc 100644--- a/manim/mobject/types/vectorized_mobject.py+++ b/manim/mobject/types/vectorized_mobject.py@@ -73,7 +73,7 @@ class VMobject(Mobject):# varying zoom levels?tolerance_for_point_equality=1e-6,n_points_per_cubic_curve=4,- **kwargs+ **kwargs,):self.fill_color = fill_colorself.fill_opacity = fill_opacity@@ -495,7 +495,7 @@ class VMobject(Mobject):handle2, new_anchor = pointselse:name = sys._getframe(0).f_code.co_name- raise ValueError("Only call {} with 1 or 2 points".format(name))+ raise ValueError(f"Only call {name} with 1 or 2 points")if self.has_new_path_started():self.add_line_to(new_anchor)@@ -1431,7 +1431,7 @@ class VectorizedPoint(VMobject):stroke_width=0,artificial_width=0.01,artificial_height=0.01,- **kwargs+ **kwargs,):self.artificial_width = artificial_widthself.artificial_height = artificial_height@@ -1440,7 +1440,7 @@ class VectorizedPoint(VMobject):color=color,fill_opacity=fill_opacity,stroke_width=stroke_width,- **kwargs+ **kwargs,)self.set_points(np.array([location]))diff --git a/manim/scene/scene.py b/manim/scene/scene.pyindex 04358b028..f6c1c44c2 100644--- a/manim/scene/scene.py+++ b/manim/scene/scene.py@@ -703,20 +703,20 @@ class Scene(Container):if stop_condition is not None:time_progression = self.get_time_progression(duration,- "Waiting for {}".format(stop_condition.__name__),+ f"Waiting for {stop_condition.__name__}",n_iterations=-1, # So it doesn't show % progressoverride_skip_animations=True,)else:time_progression = self.get_time_progression(- duration, "Waiting {}".format(self.renderer.num_plays)+ duration, f"Waiting {self.renderer.num_plays}")else:time_progression = self.get_time_progression(duration,"".join([- "Animation {}: ".format(self.renderer.num_plays),+ f"Animation {self.renderer.num_plays}: ",str(animations[0]),(", etc." if len(animations) > 1 else ""),]diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.pyindex a8bfe4019..8ff758853 100644--- a/manim/scene/scene_file_writer.py+++ b/manim/scene/scene_file_writer.py@@ -124,10 +124,7 @@ class SceneFileWriter(object):returnnew_partial_movie_file = os.path.join(self.partial_movie_directory,- "{}{}".format(- hash_animation,- config["movie_file_extension"],- ),+ f"{hash_animation}{config['movie_file_extension']}",)self.partial_movie_files.append(new_partial_movie_file)@@ -158,7 +155,7 @@ class SceneFileWriter(object):"""pixel_height = config["pixel_height"]frame_rate = config["frame_rate"]- return "{}p{}".format(pixel_height, frame_rate)+ return f"{pixel_height}p{frame_rate}"# Sounddef init_audio(self):@@ -399,7 +396,7 @@ class SceneFileWriter(object):return Falsepath = os.path.join(self.partial_movie_directory,- "{}{}".format(hash_invocation, config["movie_file_extension"]),+ f"{hash_invocation}{config['movie_file_extension']}",)return os.path.exists(path)@@ -435,7 +432,7 @@ class SceneFileWriter(object):for pf_path in partial_movie_files:if os.name == "nt":pf_path = pf_path.replace("\\", "/")- fp.write("file 'file:{}'\n".format(pf_path))+ fp.write(f"file 'file:{pf_path}'\n")movie_file_path = self.movie_file_pathcommands = [FFMPEG_BIN,diff --git a/manim/utils/caching.py b/manim/utils/caching.pyindex 72a3b7ac5..6902fcb0c 100644--- a/manim/utils/caching.py+++ b/manim/utils/caching.py@@ -42,7 +42,7 @@ def handle_caching_play(func):)self.skip_animations = Trueelse:- hash_play = "uncached_{:05}".format(self.num_plays)+ hash_play = f"uncached_{self.num_plays:05}"self.animations_hashes.append(hash_play)self.file_writer.add_partial_movie_file(hash_play)logger.debug(diff --git a/manim/utils/file_ops.py b/manim/utils/file_ops.pyindex 2296a6bf0..6b450cb42 100644--- a/manim/utils/file_ops.py+++ b/manim/utils/file_ops.py@@ -37,9 +37,7 @@ def seek_full_path_from_defaults(file_name, default_dir, extensions):for path in possible_paths:if os.path.exists(path):return path- error = "From: {}, could not find {} at either of these locations: {}".format(- os.getcwd(), file_name, possible_paths- )+ error = f"From: {os.getcwd()}, could not find {file_name} at either of these locations: {possible_paths}"raise IOError(error)diff --git a/manim/utils/tex.py b/manim/utils/tex.pyindex 8301a6c16..fd31fcd57 100644--- a/manim/utils/tex.py+++ b/manim/utils/tex.py@@ -78,7 +78,7 @@ class TexTemplate:preamble=None,placeholder_text=None,post_doc_commands=None,- **kwargs+ **kwargs,):self.tex_compiler = (tex_compiler@@ -224,9 +224,7 @@ class TexTemplate:LaTeX code based on template, containing the given expression inside its environment, ready for typesetting"""begin, end = self._texcode_for_environment(environment)- return self.body.replace(- self.placeholder_text, "{0}\n{1}\n{2}".format(begin, expression, end)- )+ return self.body.replace(self.placeholder_text, f"{begin}\n{expression}\n{end}")class TexTemplateFromFile(TexTemplate):diff --git a/manim/utils/tex_file_writing.py b/manim/utils/tex_file_writing.pyindex 80b311be2..3ca111248 100644--- a/manim/utils/tex_file_writing.py+++ b/manim/utils/tex_file_writing.py@@ -126,8 +126,8 @@ def tex_compilation_command(tex_compiler, output_format, tex_file, tex_dir):outflag,"-interaction=batchmode","-halt-on-error",- '-output-directory="{}"'.format(tex_dir),- '"{}"'.format(tex_file),+ f'-output-directory="{tex_dir}"',+ f'"{tex_file}"',">",os.devnull,]@@ -197,7 +197,7 @@ def convert_to_svg(dvi_file, extension, page=1):"dvisvgm","--pdf" if extension == ".pdf" else "","-p " + str(page),- '"{}"'.format(dvi_file),+ f'"{dvi_file}"',"-n","-v 0","-o " + f'"{result}"',diff --git a/tests/utils/GraphicalUnitTester.py b/tests/utils/GraphicalUnitTester.pyindex 3c191320a..08c8f7802 100644--- a/tests/utils/GraphicalUnitTester.py+++ b/tests/utils/GraphicalUnitTester.py@@ -76,7 +76,7 @@ class GraphicalUnitTester:The pre-rendered frame."""frame_data_path = os.path.join(- os.path.join(self.path_control_data, "{}.npz".format(str(self.scene)))+ os.path.join(self.path_control_data, f"{self.scene}.npz"))return np.load(frame_data_path)["frame_data"]