Skip to content

Change flake8-comprehensions and flake8-bugbear to ruff #3882

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ repos:
- id: flake8
additional_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,
Expand Down
17 changes: 7 additions & 10 deletions manim/_config/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -643,14 +643,14 @@ def digest_parser(self, parser: configparser.ConfigParser) -> Self:
gui_location = tuple(
map(int, re.split(r"[;,\-]", parser["CLI"]["gui_location"])),
)
setattr(self, "gui_location", gui_location)
self.gui_location = gui_location

window_size = parser["CLI"][
"window_size"
] # if not "default", get a tuple of the position
if window_size != "default":
window_size = tuple(map(int, re.split(r"[;,\-]", window_size)))
setattr(self, "window_size", window_size)
self.window_size = window_size

# plugins
plugins = parser["CLI"].get("plugins", fallback="", raw=True)
Expand All @@ -671,7 +671,7 @@ def digest_parser(self, parser: configparser.ConfigParser) -> Self:

val = parser["CLI"].get("progress_bar")
if val:
setattr(self, "progress_bar", val)
self.progress_bar = val

val = parser["ffmpeg"].get("loglevel")
if val:
Expand All @@ -681,11 +681,11 @@ def digest_parser(self, parser: configparser.ConfigParser) -> Self:
val = parser["jupyter"].getboolean("media_embed")
except ValueError:
val = None
setattr(self, "media_embed", val)
self.media_embed = val

val = parser["jupyter"].get("media_width")
if val:
setattr(self, "media_width", val)
self.media_width = val

val = parser["CLI"].get("quality", fallback="", raw=True)
if val:
Expand Down Expand Up @@ -836,15 +836,12 @@ def digest_args(self, args: argparse.Namespace) -> Self:
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_location

return self
Expand Down
2 changes: 1 addition & 1 deletion manim/cli/cfg/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def write(level: str = None, openfile: bool = False) -> None:
"""Not enough values in input.
You may have added a new entry to default.cfg, in which case you will have to
modify write_cfg_subcmd_input to account for it.""",
)
) from None
if temp:
while temp and not _is_expected_datatype(
temp,
Expand Down
1 change: 1 addition & 0 deletions manim/cli/default_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ def command(self, *args, **kwargs):
warnings.warn(
"Use default param of DefaultGroup or set_default_command() instead",
DeprecationWarning,
stacklevel=1,
)

def _decorator(f):
Expand Down
4 changes: 3 additions & 1 deletion manim/mobject/geometry/arc.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,9 @@ def get_arc_center(self, warning: bool = True) -> Point3D:
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 = True
return np.array(ORIGIN)

Expand Down
4 changes: 2 additions & 2 deletions manim/mobject/geometry/boolean_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def _convert_vmobject_to_skia_path(self, vmobject: VMobject) -> SkiaPath:
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()
Expand All @@ -100,7 +100,7 @@ def _convert_vmobject_to_skia_path(self, vmobject: VMobject) -> SkiaPath:
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]):
Expand Down
4 changes: 2 additions & 2 deletions manim/mobject/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 e


class GenericGraph(VMobject, metaclass=ConvertToOpenGL):
Expand Down
2 changes: 1 addition & 1 deletion manim/mobject/opengl/opengl_point_cloud_mobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def thin_out(self, factor=5):
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):
Expand Down
2 changes: 1 addition & 1 deletion manim/mobject/svg/brace.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ def __init__(
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)

Expand Down
8 changes: 6 additions & 2 deletions manim/mobject/text/text_mobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -1453,7 +1453,9 @@ def _extract_gradient_tags(self):
"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 gradientmap

def _parse_color(self, col):
Expand Down Expand Up @@ -1495,7 +1497,9 @@ def _extract_color_tags(self):
"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 colormap

def __repr__(self):
Expand Down
4 changes: 2 additions & 2 deletions manim/mobject/types/point_cloud_mobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def thin_out(self, factor=5):
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

Expand All @@ -158,7 +158,7 @@ def sort_points(self, function=lambda p: p[0]):
"""
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 self

def fade_to(self, color, alpha, family=True):
Expand Down
6 changes: 3 additions & 3 deletions manim/scene/scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -899,16 +899,16 @@ def compile_animations(
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 e
else:
raise TypeError(
f"Unexpected argument {arg} passed to Scene.play().",
)
) from e

for animation in animations:
for k, v in kwargs.items():
Expand Down
8 changes: 4 additions & 4 deletions manim/scene/three_d_scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ def begin_ambient_camera_rotation(self, rate: float = 0.02, about: str = "theta"
}
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 e

def stop_ambient_camera_rotation(self, about="theta"):
"""
Expand All @@ -155,8 +155,8 @@ def stop_ambient_camera_rotation(self, about="theta"):
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 e

def begin_3dillusion_camera_rotation(
self,
Expand Down
2 changes: 1 addition & 1 deletion manim/utils/hashing.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ def default(self, obj: Any):
# 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):
Expand Down
3 changes: 2 additions & 1 deletion manim/utils/testing/_frames_testers.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ def check_frame(self, frame_number: int, frame: np.ndarray):
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,
)
return

Expand Down
2 changes: 1 addition & 1 deletion manim/utils/testing/_test_class_makers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion manim/utils/testing/frames_comparison.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def wrapper(*args, request: FixtureRequest, tmp_path, **kwargs):

# 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_marks
return wrapper
Expand Down
2 changes: 1 addition & 1 deletion manim/utils/tex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, end
11 changes: 9 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -133,6 +131,8 @@ fix = true

[tool.ruff.lint]
select = [
"B",
"C4",
"E",
"F",
"I",
Expand All @@ -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",
Expand All @@ -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
Expand Down
Loading