A community-maintained Python framework for creating mathematical animations.
Change flake8-comprehensions and flake8-bugbear to ruff (#3882)
Aarush Deshpanded6dac76fa307
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex e84a0a390..6f5cf011c 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -32,9 +32,7 @@ repos:- id: flake8additional_dependencies:[- flake8-bugbear==21.4.3,flake8-builtins==1.5.3,- flake8-comprehensions>=3.6.1,flake8-docstrings==1.6.0,flake8-pytest-style==1.5.0,flake8-rst-docstrings==0.2.3,diff --git a/manim/_config/utils.py b/manim/_config/utils.pyindex 4e08245c9..85a73bf37 100644--- a/manim/_config/utils.py+++ b/manim/_config/utils.py@@ -643,14 +643,14 @@ class ManimConfig(MutableMapping):gui_location = tuple(map(int, re.split(r"[;,\-]", parser["CLI"]["gui_location"])),)- setattr(self, "gui_location", gui_location)+ self.gui_location = gui_locationwindow_size = parser["CLI"]["window_size"] # if not "default", get a tuple of the positionif window_size != "default":window_size = tuple(map(int, re.split(r"[;,\-]", window_size)))- setattr(self, "window_size", window_size)+ self.window_size = window_size# pluginsplugins = parser["CLI"].get("plugins", fallback="", raw=True)@@ -671,7 +671,7 @@ class ManimConfig(MutableMapping):val = parser["CLI"].get("progress_bar")if val:- setattr(self, "progress_bar", val)+ self.progress_bar = valval = parser["ffmpeg"].get("loglevel")if val:@@ -681,11 +681,11 @@ class ManimConfig(MutableMapping):val = parser["jupyter"].getboolean("media_embed")except ValueError:val = None- setattr(self, "media_embed", val)+ self.media_embed = valval = parser["jupyter"].get("media_width")if val:- setattr(self, "media_width", val)+ self.media_width = valval = parser["CLI"].get("quality", fallback="", raw=True)if val:@@ -836,15 +836,12 @@ class ManimConfig(MutableMapping):if args.tex_template:self.tex_template = TexTemplate.from_file(args.tex_template)- if (- self.renderer == RendererType.OPENGL- and getattr(args, "write_to_movie") is None- ):+ if self.renderer == RendererType.OPENGL and args.write_to_movie is None:# --write_to_movie was not passed on the command line, so don't generate video.self["write_to_movie"] = False# Handle --gui_location flag.- if getattr(args, "gui_location") is not None:+ if args.gui_location is not None:self.gui_location = args.gui_locationreturn selfdiff --git a/manim/cli/cfg/group.py b/manim/cli/cfg/group.pyindex 24b98a835..113818e24 100644--- a/manim/cli/cfg/group.py+++ b/manim/cli/cfg/group.py@@ -196,7 +196,7 @@ To save your config please save that file and place it in your current working d"""Not enough values in input.You may have added a new entry to default.cfg, in which case you will have tomodify write_cfg_subcmd_input to account for it.""",- )+ ) from Noneif temp:while temp and not _is_expected_datatype(temp,diff --git a/manim/cli/default_group.py b/manim/cli/default_group.pyindex f4c8c33db..03b2e5b2f 100644--- a/manim/cli/default_group.py+++ b/manim/cli/default_group.py@@ -67,6 +67,7 @@ class DefaultGroup(cloup.Group):warnings.warn("Use default param of DefaultGroup or set_default_command() instead",DeprecationWarning,+ stacklevel=1,)def _decorator(f):diff --git a/manim/mobject/geometry/arc.py b/manim/mobject/geometry/arc.pyindex dd532b07b..c5c4e31e5 100644--- a/manim/mobject/geometry/arc.py+++ b/manim/mobject/geometry/arc.py@@ -400,7 +400,9 @@ class Arc(TipableVMobject):return line_intersection(line1=(a1, a1 + n1), line2=(a2, a2 + n2))except Exception:if warning:- warnings.warn("Can't find Arc center, using ORIGIN instead")+ warnings.warn(+ "Can't find Arc center, using ORIGIN instead", stacklevel=1+ )self._failed_to_get_center = Truereturn np.array(ORIGIN)diff --git a/manim/mobject/geometry/boolean_ops.py b/manim/mobject/geometry/boolean_ops.pyindex ef5bd4fa5..baef2c3fa 100644--- a/manim/mobject/geometry/boolean_ops.py+++ b/manim/mobject/geometry/boolean_ops.py@@ -90,7 +90,7 @@ class _BooleanOps(VMobject, metaclass=ConvertToOpenGL):quads = vmobject.get_bezier_tuples_from_points(subpath)start = subpath[0]path.moveTo(*start[:2])- for p0, p1, p2 in quads:+ for _p0, p1, p2 in quads:path.quadTo(*p1[:2], *p2[:2])if vmobject.consider_points_equals(subpath[0], subpath[-1]):path.close()@@ -100,7 +100,7 @@ class _BooleanOps(VMobject, metaclass=ConvertToOpenGL):quads = vmobject.gen_cubic_bezier_tuples_from_points(subpath)start = subpath[0]path.moveTo(*start[:2])- for p0, p1, p2, p3 in quads:+ for _p0, p1, p2, p3 in quads:path.cubicTo(*p1[:2], *p2[:2], *p3[:2])if vmobject.consider_points_equals_2d(subpath[0], subpath[-1]):diff --git a/manim/mobject/graph.py b/manim/mobject/graph.pyindex 3c9893612..9cca91f03 100644--- a/manim/mobject/graph.py+++ b/manim/mobject/graph.py@@ -469,11 +469,11 @@ def _determine_graph_layout(return cast(LayoutFunction, layout)(nx_graph, scale=layout_scale, **layout_config)- except TypeError:+ except TypeError as e:raise ValueError(f"The layout '{layout}' is neither a recognized layout, a layout function,""nor a vertex placement dictionary.",- )+ ) from eclass GenericGraph(VMobject, metaclass=ConvertToOpenGL):diff --git a/manim/mobject/opengl/opengl_point_cloud_mobject.py b/manim/mobject/opengl/opengl_point_cloud_mobject.pyindex 0b5a940a7..d8e374c5d 100644--- a/manim/mobject/opengl/opengl_point_cloud_mobject.py+++ b/manim/mobject/opengl/opengl_point_cloud_mobject.py@@ -71,7 +71,7 @@ class OpenGLPMobject(OpenGLMobject):for mob in self.family_members_with_points():num_points = mob.get_num_points()- def thin_func():+ def thin_func(num_points=num_points):return np.arange(0, num_points, factor)if len(mob.points) == len(mob.rgbas):diff --git a/manim/mobject/svg/brace.py b/manim/mobject/svg/brace.pyindex 600e841f6..ae7ee6a2a 100644--- a/manim/mobject/svg/brace.py+++ b/manim/mobject/svg/brace.py@@ -249,7 +249,7 @@ class BraceLabel(VMobject, metaclass=ConvertToOpenGL):self.brace = Brace(obj, brace_direction, buff, **brace_config)if isinstance(text, (tuple, list)):- self.label = self.label_constructor(font_size=font_size, *text, **kwargs)+ self.label = self.label_constructor(*text, font_size=font_size, **kwargs)else:self.label = self.label_constructor(str(text), font_size=font_size)diff --git a/manim/mobject/text/text_mobject.py b/manim/mobject/text/text_mobject.pyindex 6f7b4d9d9..5ba434000 100644--- a/manim/mobject/text/text_mobject.py+++ b/manim/mobject/text/text_mobject.py@@ -1453,7 +1453,9 @@ class MarkupText(SVGMobject):"end_offset": end_offset,},)- self.text = re.sub("<gradient[^>]+>(.+?)</gradient>", r"\1", self.text, 0, re.S)+ self.text = re.sub(+ "<gradient[^>]+>(.+?)</gradient>", r"\1", self.text, count=0, flags=re.S+ )return gradientmapdef _parse_color(self, col):@@ -1495,7 +1497,9 @@ class MarkupText(SVGMobject):"end_offset": end_offset,},)- self.text = re.sub("<color[^>]+>(.+?)</color>", r"\1", self.text, 0, re.S)+ self.text = re.sub(+ "<color[^>]+>(.+?)</color>", r"\1", self.text, count=0, flags=re.S+ )return colormapdef __repr__(self):diff --git a/manim/mobject/types/point_cloud_mobject.py b/manim/mobject/types/point_cloud_mobject.pyindex 4f43dbf59..288ade804 100644--- a/manim/mobject/types/point_cloud_mobject.py+++ b/manim/mobject/types/point_cloud_mobject.py@@ -148,7 +148,7 @@ class PMobject(Mobject, metaclass=ConvertToOpenGL):for mob in self.family_members_with_points():num_points = self.get_num_points()mob.apply_over_attr_arrays(- lambda arr: arr[np.arange(0, num_points, factor)],+ lambda arr, n=num_points: arr[np.arange(0, n, factor)],)return self@@ -158,7 +158,7 @@ class PMobject(Mobject, metaclass=ConvertToOpenGL):"""for mob in self.family_members_with_points():indices = np.argsort(np.apply_along_axis(function, 1, mob.points))- mob.apply_over_attr_arrays(lambda arr: arr[indices])+ mob.apply_over_attr_arrays(lambda arr, idx=indices: arr[idx])return selfdef fade_to(self, color, alpha, family=True):diff --git a/manim/scene/scene.py b/manim/scene/scene.pyindex 3f80c9186..6684e629c 100644--- a/manim/scene/scene.py+++ b/manim/scene/scene.py@@ -899,16 +899,16 @@ class Scene:for arg in arg_anims:try:animations.append(prepare_animation(arg))- except TypeError:+ except TypeError as e:if inspect.ismethod(arg):raise TypeError("Passing Mobject methods to Scene.play is no longer"" supported. Use Mobject.animate instead.",- )+ ) from eelse:raise TypeError(f"Unexpected argument {arg} passed to Scene.play().",- )+ ) from efor animation in animations:for k, v in kwargs.items():diff --git a/manim/scene/three_d_scene.py b/manim/scene/three_d_scene.pyindex 919f3cb2c..8abbdb7cd 100644--- a/manim/scene/three_d_scene.py+++ b/manim/scene/three_d_scene.py@@ -135,8 +135,8 @@ class ThreeDScene(Scene):}cam.add_updater(lambda m, dt: methods[about](rate * dt))self.add(self.camera)- except Exception:- raise ValueError("Invalid ambient rotation angle.")+ except Exception as e:+ raise ValueError("Invalid ambient rotation angle.") from edef stop_ambient_camera_rotation(self, about="theta"):"""@@ -155,8 +155,8 @@ class ThreeDScene(Scene):self.remove(x)elif config.renderer == RendererType.OPENGL:self.camera.clear_updaters()- except Exception:- raise ValueError("Invalid ambient rotation angle.")+ except Exception as e:+ raise ValueError("Invalid ambient rotation angle.") from edef begin_3dillusion_camera_rotation(self,diff --git a/manim/utils/hashing.py b/manim/utils/hashing.pyindex 9557ba18f..92b519150 100644--- a/manim/utils/hashing.py+++ b/manim/utils/hashing.py@@ -223,7 +223,7 @@ class _CustomEncoder(json.JSONEncoder):# We return the repr and not a list to avoid the JsonEncoder to iterate over it.return repr(obj)elif hasattr(obj, "__dict__"):- temp = getattr(obj, "__dict__")+ temp = obj.__dict__# MappingProxy is scene-caching nightmare. It contains all of the object methods and attributes. We skip it as the mechanism will at some point process the object, but instantiated.# Indeed, there is certainly no case where scene-caching will receive only a non instancied object, as this is never used in the library or encouraged to be used user-side.if isinstance(temp, MappingProxyType):diff --git a/manim/utils/testing/_frames_testers.py b/manim/utils/testing/_frames_testers.pyindex a0ca9ddd9..bef618493 100644--- a/manim/utils/testing/_frames_testers.py+++ b/manim/utils/testing/_frames_testers.py@@ -64,7 +64,8 @@ class _FramesTester:warnings.warn(f"Mismatch of {number_of_mismatches} pixel values in frame {frame_number} "f"against control data in {self._file_path}. Below error threshold, "- "continuing..."+ "continuing...",+ stacklevel=1,)returndiff --git a/manim/utils/testing/_test_class_makers.py b/manim/utils/testing/_test_class_makers.pyindex ac5886d49..fe127be1c 100644--- a/manim/utils/testing/_test_class_makers.py+++ b/manim/utils/testing/_test_class_makers.py@@ -15,7 +15,7 @@ def _make_test_scene_class() -> type[Scene]:class _TestedScene(base_scene):def __init__(self, *args, **kwargs):- super().__init__(renderer=test_renderer, *args, **kwargs)+ super().__init__(*args, renderer=test_renderer, **kwargs)def construct(self):construct_test(self)diff --git a/manim/utils/testing/frames_comparison.py b/manim/utils/testing/frames_comparison.pyindex e3814ea69..7a32a9d35 100644--- a/manim/utils/testing/frames_comparison.py+++ b/manim/utils/testing/frames_comparison.py@@ -150,7 +150,7 @@ def frames_comparison(# Reach a bit into pytest internals to hoist the marks from our wrapped# function.- setattr(wrapper, "pytestmark", [])+ wrapper.pytestmark = []new_marks = getattr(tested_scene_construct, "pytestmark", [])wrapper.pytestmark = new_marksreturn wrapperdiff --git a/manim/utils/tex.py b/manim/utils/tex.pyindex f642abad7..2103f2034 100644--- a/manim/utils/tex.py+++ b/manim/utils/tex.py@@ -191,7 +191,7 @@ def _texcode_for_environment(environment: str) -> tuple[str, str]:begin += "}"# While the \end command terminates at the first closing brace- split_at_brace = re.split("}", environment, 1)+ split_at_brace = re.split("}", environment, maxsplit=1)end = r"\end{" + split_at_brace[0] + "}"return begin, enddiff --git a/pyproject.toml b/pyproject.tomlindex a71085ae8..4b4a250ff 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -64,9 +64,7 @@ gui = ["dearpygui"][tool.poetry.group.dev.dependencies]black = ">=23.11,<25.0"flake8 = "^6.1.0"-flake8-bugbear = "^23.11.28"flake8-builtins = "^2.2.0"-flake8-comprehensions = "^3.7.0"flake8-docstrings = "^1.7.0"furo = "^2023.09.10"gitpython = "^3"@@ -133,6 +131,8 @@ fix = true[tool.ruff.lint]select = [+ "B",+ "C4","E","F","I",@@ -142,6 +142,11 @@ select = []ignore = [+ # mutable argument defaults (too many changes)+ "B006",+ # No function calls in defaults+ # ignored because np.array() and straight_path()+ "B008",# due to the import * used in manim"F403","F405",@@ -161,6 +166,8 @@ dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"[tool.ruff.lint.per-file-ignores]"tests/*" = [+ # unused expression+ "B018",# unused variable"F841",# from __future__ import annotations