Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Use ruff instead of flake8-simplify (#3873)

adeshpandef463423abe2b
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 3910fd7ed..4f6a3fe89 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -63,7 +63,7 @@ autodoc_type_aliases = {
alias_name: f"~manim.{module}.{alias_name}"
for module, module_dict in ALIAS_DOCS_DICT.items()
for category_dict in module_dict.values()
- for alias_name in category_dict.keys()
+ for alias_name in category_dict
}
autoclass_content = "both"
diff --git a/manim/_config/utils.py b/manim/_config/utils.py
index c70c1fb94..4e08245c9 100644
--- a/manim/_config/utils.py
+++ b/manim/_config/utils.py
@@ -654,10 +654,7 @@ class ManimConfig(MutableMapping):
# plugins
plugins = parser["CLI"].get("plugins", fallback="", raw=True)
- if plugins == "":
- plugins = []
- else:
- plugins = plugins.split(",")
+ plugins = [] if plugins == "" else plugins.split(",")
self.plugins = plugins
# the next two must be set AFTER digesting pixel_width and pixel_height
self["frame_height"] = parser["CLI"].getfloat("frame_height", 8.0)
diff --git a/manim/animation/creation.py b/manim/animation/creation.py
index e6f7199bf..124d3295f 100644
--- a/manim/animation/creation.py
+++ b/manim/animation/creation.py
@@ -351,10 +351,7 @@ class Write(DrawBorderThenFill):
) -> tuple[float, float]:
length = len(vmobject.family_members_with_points())
if run_time is None:
- if length < 15:
- run_time = 1
- else:
- run_time = 2
+ run_time = 1 if length < 15 else 2
if lag_ratio is None:
lag_ratio = min(4.0 / max(1.0, length), 0.2)
return run_time, lag_ratio
diff --git a/manim/animation/fading.py b/manim/animation/fading.py
index 1e98b2c29..c09d8bac6 100644
--- a/manim/animation/fading.py
+++ b/manim/animation/fading.py
@@ -57,10 +57,7 @@ class _Fade(Transform):
) -> None:
if not mobjects:
raise ValueError("At least one mobject must be passed.")
- if len(mobjects) == 1:
- mobject = mobjects[0]
- else:
- mobject = Group(*mobjects)
+ mobject = mobjects[0] if len(mobjects) == 1 else Group(*mobjects)
self.point_target = False
if shift is None:
diff --git a/manim/animation/specialized.py b/manim/animation/specialized.py
index 99320f36d..e5f9e96d9 100644
--- a/manim/animation/specialized.py
+++ b/manim/animation/specialized.py
@@ -70,10 +70,7 @@ class Broadcast(LaggedStart):
anims = []
# Works by saving the mob that is passed into the animation, scaling it to 0 (or the initial_width) and then restoring the original mob.
- if mobject.fill_opacity:
- fill_o = True
- else:
- fill_o = False
+ fill_o = bool(mobject.fill_opacity)
for _ in range(self.n_mobs):
mob = mobject.copy()
diff --git a/manim/cli/cfg/group.py b/manim/cli/cfg/group.py
index 346205d89..24b98a835 100644
--- a/manim/cli/cfg/group.py
+++ b/manim/cli/cfg/group.py
@@ -8,6 +8,7 @@ group.
from __future__ import annotations
+import contextlib
from ast import literal_eval
from pathlib import Path
@@ -51,10 +52,8 @@ def value_from_string(value: str) -> str | int | bool:
Union[:class:`str`, :class:`int`, :class:`bool`]
Returns the literal of appropriate datatype.
"""
- try:
+ with contextlib.suppress(SyntaxError, ValueError):
value = literal_eval(value)
- except (SyntaxError, ValueError):
- pass
return value
diff --git a/manim/mobject/geometry/line.py b/manim/mobject/geometry/line.py
index 50d63c119..7009dd5b3 100644
--- a/manim/mobject/geometry/line.py
+++ b/manim/mobject/geometry/line.py
@@ -98,10 +98,7 @@ class Line(TipableVMobject):
if buff == 0:
return
#
- if self.path_arc == 0:
- length = self.get_length()
- else:
- length = self.get_arc_length()
+ length = self.get_length() if self.path_arc == 0 else self.get_arc_length()
#
if length < 2 * buff:
return
diff --git a/manim/mobject/geometry/polygram.py b/manim/mobject/geometry/polygram.py
index de48c2899..0a9edbadd 100644
--- a/manim/mobject/geometry/polygram.py
+++ b/manim/mobject/geometry/polygram.py
@@ -757,9 +757,6 @@ class Cutout(VMobject, metaclass=ConvertToOpenGL):
def __init__(self, main_shape: VMobject, *mobjects: VMobject, **kwargs) -> None:
super().__init__(**kwargs)
self.append_points(main_shape.points)
- if main_shape.get_direction() == "CW":
- sub_direction = "CCW"
- else:
- sub_direction = "CW"
+ sub_direction = "CCW" if main_shape.get_direction() == "CW" else "CW"
for mobject in mobjects:
self.append_points(mobject.force_direction(sub_direction).points)
diff --git a/manim/mobject/graph.py b/manim/mobject/graph.py
index 8afcf0301..3c9893612 100644
--- a/manim/mobject/graph.py
+++ b/manim/mobject/graph.py
@@ -338,10 +338,7 @@ def _tree_layout(
parent = {u: root_vertex for u in children[root_vertex]}
pos = {}
obstruction = [0.0] * len(T)
- if orientation == "down":
- o = -1
- else:
- o = 1
+ o = -1 if orientation == "down" else 1
def slide(v, dx):
"""
@@ -404,15 +401,9 @@ def _tree_layout(
if isinstance(scale, (float, int)) and (width > 0 or height > 0):
sf = 2 * scale / max(width, height)
elif isinstance(scale, tuple):
- if scale[0] is not None and width > 0:
- sw = 2 * scale[0] / width
- else:
- sw = 1
+ sw = 2 * scale[0] / width if scale[0] is not None and width > 0 else 1
- if scale[1] is not None and height > 0:
- sh = 2 * scale[1] / height
- else:
- sh = 1
+ sh = 2 * scale[1] / height if scale[1] is not None and height > 0 else 1
sf = np.array([sw, sh, 0])
else:
@@ -851,7 +842,7 @@ class GenericGraph(VMobject, metaclass=ConvertToOpenGL):
label_fill_color=label_fill_color,
vertex_type=vertex_type,
vertex_config=vertex_config[v],
- vertex_mobject=vertex_mobjects[v] if v in vertex_mobjects else None,
+ vertex_mobject=vertex_mobjects.get(v),
)
for v in vertices
]
diff --git a/manim/mobject/graphing/probability.py b/manim/mobject/graphing/probability.py
index 0f98620dc..42197b8ff 100644
--- a/manim/mobject/graphing/probability.py
+++ b/manim/mobject/graphing/probability.py
@@ -339,10 +339,7 @@ class BarChart(Axes):
for i, (value, bar_name) in enumerate(zip(val_range, self.bar_names)):
# to accommodate negative bars, the label may need to be
# below or above the x_axis depending on the value of the bar
- if self.values[i] < 0:
- direction = UP
- else:
- direction = DOWN
+ direction = UP if self.values[i] < 0 else DOWN
bar_name_label = self.x_axis.label_constructor(bar_name)
bar_name_label.font_size = self.x_axis.font_size
diff --git a/manim/mobject/mobject.py b/manim/mobject/mobject.py
index 75f4ed830..09c4358e8 100644
--- a/manim/mobject/mobject.py
+++ b/manim/mobject/mobject.py
@@ -1579,9 +1579,7 @@ class Mobject:
return True
if self.get_bottom()[1] > config["frame_y_radius"]:
return True
- if self.get_top()[1] < -config["frame_y_radius"]:
- return True
- return False
+ return self.get_top()[1] < -config["frame_y_radius"]
def stretch_about_point(self, factor: float, dim: int, point: Point3D) -> Self:
return self.stretch(factor, dim, about_point=point)
@@ -1996,7 +1994,7 @@ class Mobject:
# If we do not have points (but do have submobjects)
# use only the points from those.
- if len(self.points) == 0:
+ if len(self.points) == 0: # noqa: SIM108
rv = None
else:
# Otherwise, be sure to include our own points
@@ -2005,10 +2003,7 @@ class Mobject:
# smallest dimension they have and compare it to the return value.
for mobj in self.submobjects:
value = mobj.reduce_across_dimension(reduce_func, dim)
- if rv is None:
- rv = value
- else:
- rv = reduce_func([value, rv])
+ rv = value if rv is None else reduce_func([value, rv])
return rv
def nonempty_submobjects(self) -> list[Self]:
diff --git a/manim/mobject/opengl/opengl_geometry.py b/manim/mobject/opengl/opengl_geometry.py
index 2ec0bbe4d..646594a29 100644
--- a/manim/mobject/opengl/opengl_geometry.py
+++ b/manim/mobject/opengl/opengl_geometry.py
@@ -463,10 +463,7 @@ class OpenGLLine(OpenGLTipableVMobject):
if buff == 0:
return
#
- if self.path_arc == 0:
- length = self.get_length()
- else:
- length = self.get_arc_length()
+ length = self.get_length() if self.path_arc == 0 else self.get_arc_length()
#
if length < 2 * buff:
return
diff --git a/manim/mobject/opengl/opengl_mobject.py b/manim/mobject/opengl/opengl_mobject.py
index c907c4c2e..135b6cb6e 100644
--- a/manim/mobject/opengl/opengl_mobject.py
+++ b/manim/mobject/opengl/opengl_mobject.py
@@ -1868,9 +1868,7 @@ class OpenGLMobject:
return True
if self.get_bottom()[1] > config.frame_y_radius:
return True
- if self.get_top()[1] < -config.frame_y_radius:
- return True
- return False
+ return self.get_top()[1] < -config.frame_y_radius
def stretch_about_point(self, factor: float, dim: int, point: Point3D) -> Self:
return self.stretch(factor, dim, about_point=point)
@@ -2569,10 +2567,7 @@ class OpenGLMobject:
if key not in mobject1.data or key not in mobject2.data:
continue
- if key in ("points", "bounding_box"):
- func = path_func
- else:
- func = interpolate
+ func = path_func if key in ("points", "bounding_box") else interpolate
self.data[key][:] = func(mobject1.data[key], mobject2.data[key], alpha)
diff --git a/manim/mobject/opengl/opengl_vectorized_mobject.py b/manim/mobject/opengl/opengl_vectorized_mobject.py
index 8037760c4..82c863779 100644
--- a/manim/mobject/opengl/opengl_vectorized_mobject.py
+++ b/manim/mobject/opengl/opengl_vectorized_mobject.py
@@ -1874,10 +1874,7 @@ class OpenGLDashedVMobject(OpenGLVMobject):
if num_dashes > 0:
# Assuming total length is 1
dash_len = r / n
- if vmobject.is_closed():
- void_len = (1 - r) / n
- else:
- void_len = (1 - r) / (n - 1)
+ void_len = (1 - r) / n if vmobject.is_closed() else (1 - r) / (n - 1)
self.add(
*(
diff --git a/manim/mobject/text/numbers.py b/manim/mobject/text/numbers.py
index 6a0eb45a8..05854dfb4 100644
--- a/manim/mobject/text/numbers.py
+++ b/manim/mobject/text/numbers.py
@@ -210,10 +210,7 @@ class DecimalNumber(VMobject, metaclass=ConvertToOpenGL):
rounded_num = np.round(number, self.num_decimal_places)
if num_string.startswith("-") and rounded_num == 0:
- if self.include_sign:
- num_string = "+" + num_string[1:]
- else:
- num_string = num_string[1:]
+ num_string = "+" + num_string[1:] if self.include_sign else num_string[1:]
return num_string
diff --git a/manim/mobject/three_d/three_dimensions.py b/manim/mobject/three_d/three_dimensions.py
index bcdde3e18..86238551f 100644
--- a/manim/mobject/three_d/three_dimensions.py
+++ b/manim/mobject/three_d/three_dimensions.py
@@ -667,10 +667,7 @@ class Cone(Surface):
x, y, z = self.direction
r = np.sqrt(x**2 + y**2 + z**2)
- if r > 0:
- theta = np.arccos(z / r)
- else:
- theta = 0
+ theta = np.arccos(z / r) if r > 0 else 0
if x == 0:
if y == 0: # along the z axis
@@ -835,10 +832,7 @@ class Cylinder(Surface):
x, y, z = self.direction
r = np.sqrt(x**2 + y**2 + z**2)
- if r > 0:
- theta = np.arccos(z / r)
- else:
- theta = 0
+ theta = np.arccos(z / r) if r > 0 else 0
if x == 0:
if y == 0: # along the z axis
diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.py
index 86b5cd138..5346d5e7b 100644
--- a/manim/mobject/types/vectorized_mobject.py
+++ b/manim/mobject/types/vectorized_mobject.py
@@ -1200,9 +1200,7 @@ class VMobject(Mobject):
atol = self.tolerance_for_point_equality
if abs(p0[0] - p1[0]) > atol + rtol * abs(p1[0]):
return False
- if abs(p0[1] - p1[1]) > atol + rtol * abs(p1[1]):
- return False
- return True
+ return abs(p0[1] - p1[1]) <= atol + rtol * abs(p1[1])
# Information about line
def get_cubic_bezier_tuples_from_points(
@@ -2709,15 +2707,12 @@ class DashedVMobject(VMobject, metaclass=ConvertToOpenGL):
if vmobject.is_closed():
void_len = (1 - r) / n
else:
- if n == 1:
- void_len = 1 - r
- else:
- void_len = (1 - r) / (n - 1)
+ void_len = 1 - r if n == 1 else (1 - r) / (n - 1)
period = dash_len + void_len
phase_shift = (dash_offset % 1) * period
- if vmobject.is_closed():
+ if vmobject.is_closed(): # noqa: SIM108
# closed curves have equal amount of dashes and voids
pattern_len = 1
else:
diff --git a/manim/opengl/__init__.py b/manim/opengl/__init__.py
index 83f6a4ccd..e5bad5cd2 100644
--- a/manim/opengl/__init__.py
+++ b/manim/opengl/__init__.py
@@ -1,9 +1,9 @@
from __future__ import annotations
-try:
+import contextlib
+
+with contextlib.suppress(ImportError):
from dearpygui import dearpygui as dpg
-except ImportError:
- pass
from manim.mobject.opengl.dot_cloud import *
diff --git a/manim/renderer/opengl_renderer.py b/manim/renderer/opengl_renderer.py
index 8347f8a49..453fa4906 100644
--- a/manim/renderer/opengl_renderer.py
+++ b/manim/renderer/opengl_renderer.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import contextlib
import itertools as it
import time
from functools import cached_property
@@ -336,10 +337,8 @@ class OpenGLRenderer:
shader_wrapper.uniforms.items(),
self.perspective_uniforms.items(),
):
- try:
+ with contextlib.suppress(KeyError):
shader.set_uniform(name, value)
- except KeyError:
- pass
try:
shader.set_uniform(
"u_view_matrix", self.scene.camera.formatted_view_matrix
diff --git a/manim/renderer/shader.py b/manim/renderer/shader.py
index 85b9dad14..a098ed30c 100644
--- a/manim/renderer/shader.py
+++ b/manim/renderer/shader.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import contextlib
import inspect
import re
import textwrap
@@ -382,10 +383,8 @@ class Shader:
shader_program_cache[self.name] = self.shader_program
def set_uniform(self, name, value):
- try:
+ with contextlib.suppress(KeyError):
self.shader_program[name] = value
- except KeyError:
- pass
class FullScreenQuad(Mesh):
diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.py
index 9a2d5eb60..bc7b715c4 100644
--- a/manim/scene/scene_file_writer.py
+++ b/manim/scene/scene_file_writer.py
@@ -94,10 +94,7 @@ class SceneFileWriter:
if config["dry_run"]: # in dry-run mode there is no output
return
- if config["input_file"]:
- module_name = config.get_dir("input_file").stem
- else:
- module_name = ""
+ module_name = config.get_dir("input_file").stem if config["input_file"] else ""
if SceneFileWriter.force_output_as_scene_name:
self.output_name = Path(scene_name)
diff --git a/manim/utils/bezier.py b/manim/utils/bezier.py
index 5a4049b65..5d5a3bad8 100644
--- a/manim/utils/bezier.py
+++ b/manim/utils/bezier.py
@@ -1825,9 +1825,7 @@ def is_closed(points: Point3D_Array) -> bool:
return False
if abs(end[1] - start[1]) > tolerance[1]:
return False
- if abs(end[2] - start[2]) > tolerance[2]:
- return False
- return True
+ return abs(end[2] - start[2]) <= tolerance[2]
def proportions_along_bezier_curve_for_point(
diff --git a/manim/utils/docbuild/autoaliasattr_directive.py b/manim/utils/docbuild/autoaliasattr_directive.py
index ba42bd1ec..5735dc979 100644
--- a/manim/utils/docbuild/autoaliasattr_directive.py
+++ b/manim/utils/docbuild/autoaliasattr_directive.py
@@ -21,7 +21,7 @@ ALIAS_LIST = [
alias_name
for module_dict in ALIAS_DOCS_DICT.values()
for category_dict in module_dict.values()
- for alias_name in category_dict.keys()
+ for alias_name in category_dict
]
diff --git a/manim/utils/docbuild/autocolor_directive.py b/manim/utils/docbuild/autocolor_directive.py
index 574aaedf7..3a699f54d 100644
--- a/manim/utils/docbuild/autocolor_directive.py
+++ b/manim/utils/docbuild/autocolor_directive.py
@@ -69,10 +69,7 @@ class ManimColorModuleDocumenter(Directive):
luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
# Choose the font color based on the background luminance
- if luminance > 0.5:
- font_color = "black"
- else:
- font_color = "white"
+ font_color = "black" if luminance > 0.5 else "white"
color_elements.append((member_name, member_obj.to_hex(), font_color))
diff --git a/manim/utils/docbuild/manim_directive.py b/manim/utils/docbuild/manim_directive.py
index cd277970e..7ca7d6864 100644
--- a/manim/utils/docbuild/manim_directive.py
+++ b/manim/utils/docbuild/manim_directive.py
@@ -225,11 +225,7 @@ class ManimDirective(Directive):
+ self.options.get("ref_functions", [])
+ self.options.get("ref_methods", [])
)
- if ref_content:
- ref_block = "References: " + " ".join(ref_content)
-
- else:
- ref_block = ""
+ ref_block = "References: " + " ".join(ref_content) if ref_content else ""
if "quality" in self.options:
quality = f'{self.options["quality"]}_quality'
diff --git a/manim/utils/space_ops.py b/manim/utils/space_ops.py
index 197621fce..955256f10 100644
--- a/manim/utils/space_ops.py
+++ b/manim/utils/space_ops.py
@@ -476,10 +476,7 @@ def regular_vertices(
"""
if start_angle is None:
- if n % 2 == 0:
- start_angle = 0
- else:
- start_angle = TAU / 4
+ start_angle = 0 if n % 2 == 0 else TAU / 4
start_vector = rotate_vector(RIGHT * radius, start_angle)
vertices = compass_directions(n, start_vector)
diff --git a/pyproject.toml b/pyproject.toml
index 45962eea9..a71085ae8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -68,7 +68,6 @@ flake8-bugbear = "^23.11.28"
flake8-builtins = "^2.2.0"
flake8-comprehensions = "^3.7.0"
flake8-docstrings = "^1.7.0"
-flake8-simplify = "^0.14.1"
furo = "^2023.09.10"
gitpython = "^3"
isort = "^5.12.0"
@@ -138,6 +137,7 @@ select = [
"F",
"I",
"PT",
+ "SIM",
"UP",
]
diff --git a/scripts/dev_changelog.py b/scripts/dev_changelog.py
index 35e77dd79..a4a18b934 100755
--- a/scripts/dev_changelog.py
+++ b/scripts/dev_changelog.py
@@ -110,7 +110,7 @@ def process_pullrequests(lst, cur, github_repo, pr_nums):
authors.add(pr.user)
reviewers = reviewers.union(rev.user for rev in pr.get_reviews())
pr_labels = [label.name for label in pr.labels]
- for label in PR_LABELS.keys():
+ for label in PR_LABELS:
if label in pr_labels:
pr_by_labels[label].append(pr)
break # ensure that PR is only added in one category
@@ -291,7 +291,7 @@ def main(token, prior, tag, additional, outfile):
)
pr_by_labels = contributions["PRs"]
- for label in PR_LABELS.keys():
+ for label in PR_LABELS:
pr_of_label = pr_by_labels[label]
if pr_of_label: