Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Add type annotations to `table.py` (#4641)

Henrik Skov Midtibybd1276a0c6a2
diff --git a/manim/mobject/table.py b/manim/mobject/table.py
index ee0df9ece..270f851ab 100644
--- a/manim/mobject/table.py
+++ b/manim/mobject/table.py
@@ -66,6 +66,7 @@ __all__ = [
import itertools as it
from collections.abc import Callable, Iterable, Sequence
+from typing import Any, Self
from manim.mobject.geometry.line import Line
from manim.mobject.geometry.polygram import Polygon
@@ -89,12 +90,12 @@ class Table(VGroup):
Parameters
----------
table
- A 2D array or list of lists. Content of the table has to be a valid input
- for the callable set in ``element_to_mobject``.
+ A non-empty, finite iterable of equally sized iterables. The content has
+ to be valid input for the callable set in ``element_to_mobject``.
row_labels
- List of :class:`~.VMobject` representing the labels of each row.
+ An iterable of :class:`~.VMobject` representing the labels of each row.
col_labels
- List of :class:`~.VMobject` representing the labels of each column.
+ An iterable of :class:`~.VMobject` representing the labels of each column.
top_left_entry
The top-left entry of the table, can only be specified if row and
column labels are given.
@@ -201,19 +202,31 @@ class Table(VGroup):
include_background_rectangle: bool = False,
background_rectangle_color: ParsableManimColor = BLACK,
element_to_mobject: Callable[
+ [float | str],
+ VMobject,
+ ]
+ | Callable[
+ [VMobject],
+ VMobject,
+ ]
+ | Callable[
[float | str | VMobject],
VMobject,
- ] = Paragraph,
+ ]
+ | type[VMobject] = Paragraph,
element_to_mobject_config: dict = {},
arrange_in_grid_config: dict = {},
line_config: dict = {},
- **kwargs,
+ **kwargs: Any,
):
- self.row_labels = row_labels
- self.col_labels = col_labels
+ table_data = [list(row) for row in table]
+ row_label_data = list(row_labels) if row_labels is not None else []
+ col_label_data = list(col_labels) if col_labels is not None else []
+ self.row_labels = row_label_data or None
+ self.col_labels = col_label_data or None
self.top_left_entry = top_left_entry
- self.row_dim = len(table)
- self.col_dim = len(table[0])
+ self.row_dim = len(table_data)
+ self.col_dim = len(table_data[0])
self.v_buff = v_buff
self.h_buff = h_buff
self.include_outer_lines = include_outer_lines
@@ -227,14 +240,14 @@ class Table(VGroup):
self.arrange_in_grid_config = arrange_in_grid_config
self.line_config = line_config
- for row in table:
- if len(row) == len(table[0]):
+ for row in table_data:
+ if len(row) == len(table_data[0]):
pass
else:
raise ValueError("Not all rows in table have the same length.")
super().__init__(**kwargs)
- mob_table = self._table_to_mob_table(table)
+ mob_table: list[list[VMobject]] = self._table_to_mob_table(table_data)
self.elements_without_labels = VGroup(*it.chain(*mob_table))
mob_table = self._add_labels(mob_table)
self._organize_mob_table(mob_table)
@@ -256,14 +269,14 @@ class Table(VGroup):
def _table_to_mob_table(
self,
table: Iterable[Iterable[float | str | VMobject]],
- ) -> list:
+ ) -> list[list[VMobject]]:
"""Initializes the entries of ``table`` as :class:`~.VMobject`.
Parameters
----------
table
- A 2D array or list of lists. Content of the table has to be a valid input
- for the callable set in ``element_to_mobject``.
+ A non-empty, finite iterable of equally sized iterables. The content
+ has to be valid input for the callable set in ``element_to_mobject``.
Returns
--------
@@ -272,13 +285,15 @@ class Table(VGroup):
"""
return [
[
- self.element_to_mobject(item, **self.element_to_mobject_config)
+ # error: Argument 1 has incompatible type "float | str | VMobject"; expected "float | str" [arg-type]
+ # error: Argument 1 has incompatible type "float | str | VMobject"; expected "VMobject" [arg-type]
+ self.element_to_mobject(item, **self.element_to_mobject_config) # type: ignore[arg-type]
for item in row
]
for row in table
]
- def _organize_mob_table(self, table: Iterable[Iterable[VMobject]]) -> VGroup:
+ def _organize_mob_table(self, table: Sequence[Sequence[VMobject]]) -> VGroup:
"""Arranges the :class:`~.VMobject` of ``table`` in a grid.
Parameters
@@ -304,7 +319,7 @@ class Table(VGroup):
)
return help_table
- def _add_labels(self, mob_table: VGroup) -> VGroup:
+ def _add_labels(self, mob_table: list[list[VMobject]]) -> list[list[VMobject]]:
"""Adds labels to an in a grid arranged :class:`~.VGroup`.
Parameters
@@ -693,7 +708,9 @@ class Table(VGroup):
item.set_color(random_bright_color())
self.add(table)
"""
- return VGroup(*self.row_labels)
+ if self.row_labels is not None:
+ return VGroup(*self.row_labels)
+ return VGroup()
def get_col_labels(self) -> VGroup:
"""Return the column labels of the table.
@@ -721,7 +738,9 @@ class Table(VGroup):
item.set_color(random_bright_color())
self.add(table)
"""
- return VGroup(*self.col_labels)
+ if self.col_labels is not None:
+ return VGroup(*self.col_labels)
+ return VGroup()
def get_labels(self) -> VGroup:
"""Returns the labels of the table.
@@ -764,7 +783,7 @@ class Table(VGroup):
mob.add_background_rectangle(color=ManimColor(color))
return self
- def get_cell(self, pos: Sequence[int] = (1, 1), **kwargs) -> Polygon:
+ def get_cell(self, pos: Sequence[int] = (1, 1), **kwargs: Any) -> Polygon:
"""Returns one specific cell as a rectangular :class:`~.Polygon` without the entry.
Parameters
@@ -825,7 +844,7 @@ class Table(VGroup):
self,
pos: Sequence[int] = (1, 1),
color: ParsableManimColor = PURE_YELLOW,
- **kwargs,
+ **kwargs: Any,
) -> BackgroundRectangle:
"""Returns a :class:`~.BackgroundRectangle` of the cell at the given position.
@@ -864,7 +883,7 @@ class Table(VGroup):
self,
pos: Sequence[int] = (1, 1),
color: ParsableManimColor = PURE_YELLOW,
- **kwargs,
+ **kwargs: Any,
) -> Table:
"""Highlights one cell at a specific position on the table by adding a :class:`~.BackgroundRectangle`.
@@ -907,7 +926,7 @@ class Table(VGroup):
label_animation: Callable[[VMobject | VGroup], Animation] = Write,
element_animation: Callable[[VMobject | VGroup], Animation] = Create,
entry_animation: Callable[[VMobject | VGroup], Animation] = FadeIn,
- **kwargs,
+ **kwargs: Any,
) -> AnimationGroup:
"""Customized create-type function for tables.
@@ -947,7 +966,7 @@ class Table(VGroup):
self.play(table.create())
self.wait()
"""
- animations: Sequence[Animation] = [
+ animations: list[Animation] = [
line_animation(
VGroup(self.vertical_lines, self.horizontal_lines),
**kwargs,
@@ -974,12 +993,14 @@ class Table(VGroup):
return AnimationGroup(*animations, lag_ratio=lag_ratio)
- def scale(self, scale_factor: float, **kwargs):
+ def scale(
+ self, scale_factor: float, scale_stroke: bool = False, **kwargs: Any
+ ) -> Self:
# h_buff and v_buff must be adjusted so that Table.get_cell
# can construct an accurate polygon for a cell.
self.h_buff *= scale_factor
self.v_buff *= scale_factor
- super().scale(scale_factor, **kwargs)
+ super().scale(scale_factor, scale_stroke=scale_stroke, **kwargs)
return self
@@ -1006,8 +1027,9 @@ class MathTable(Table):
def __init__(
self,
table: Iterable[Iterable[float | str]],
- element_to_mobject: Callable[[float | str], VMobject] = MathTex,
- **kwargs,
+ element_to_mobject: Callable[[float | str], VMobject]
+ | type[VMobject] = MathTex,
+ **kwargs: Any,
):
"""
Special case of :class:`~.Table` with `element_to_mobject` set to :class:`~.MathTex`.
@@ -1016,8 +1038,8 @@ class MathTable(Table):
Parameters
----------
table
- A 2d array or list of lists. Content of the table have to be valid input
- for :class:`~.MathTex`.
+ A non-empty, finite iterable of equally sized iterables. The content
+ has to be valid input for :class:`~.MathTex`.
element_to_mobject
The :class:`~.Mobject` class applied to the table entries. Set as :class:`~.MathTex`.
kwargs
@@ -1061,8 +1083,9 @@ class MobjectTable(Table):
def __init__(
self,
table: Iterable[Iterable[VMobject]],
- element_to_mobject: Callable[[VMobject], VMobject] = lambda m: m,
- **kwargs,
+ element_to_mobject: Callable[[VMobject], VMobject]
+ | type[VMobject] = lambda m: m,
+ **kwargs: Any,
):
"""
Special case of :class:`~.Table` with ``element_to_mobject`` set to an identity function.
@@ -1071,7 +1094,8 @@ class MobjectTable(Table):
Parameters
----------
table
- A 2D array or list of lists. Content of the table must be of type :class:`~.Mobject`.
+ A non-empty, finite iterable of equally sized iterables containing
+ objects of type :class:`~.Mobject`.
element_to_mobject
The :class:`~.Mobject` class applied to the table entries. Set as ``lambda m : m`` to return itself.
kwargs
@@ -1109,8 +1133,9 @@ class IntegerTable(Table):
def __init__(
self,
table: Iterable[Iterable[float | str]],
- element_to_mobject: Callable[[float | str], VMobject] = Integer,
- **kwargs,
+ element_to_mobject: Callable[[float | str], VMobject]
+ | type[VMobject] = Integer,
+ **kwargs: Any,
):
"""
Special case of :class:`~.Table` with `element_to_mobject` set to :class:`~.Integer`.
@@ -1119,8 +1144,8 @@ class IntegerTable(Table):
Parameters
----------
table
- A 2d array or list of lists. Content of the table has to be valid input
- for :class:`~.Integer`.
+ A non-empty, finite iterable of equally sized iterables. The content
+ has to be valid input for :class:`~.Integer`.
element_to_mobject
The :class:`~.Mobject` class applied to the table entries. Set as :class:`~.Integer`.
kwargs
@@ -1153,9 +1178,10 @@ class DecimalTable(Table):
def __init__(
self,
table: Iterable[Iterable[float | str]],
- element_to_mobject: Callable[[float | str], VMobject] = DecimalNumber,
+ element_to_mobject: Callable[[float | str], VMobject]
+ | type[VMobject] = DecimalNumber,
element_to_mobject_config: dict = {"num_decimal_places": 1},
- **kwargs,
+ **kwargs: Any,
):
"""
Special case of :class:`~.Table` with ``element_to_mobject`` set to :class:`~.DecimalNumber`.
@@ -1165,8 +1191,8 @@ class DecimalTable(Table):
Parameters
----------
table
- A 2D array, or a list of lists. Content of the table must be valid input
- for :class:`~.DecimalNumber`.
+ A non-empty, finite iterable of equally sized iterables. The content
+ has to be valid input for :class:`~.DecimalNumber`.
element_to_mobject
The :class:`~.Mobject` class applied to the table entries. Set as :class:`~.DecimalNumber`.
element_to_mobject_config
diff --git a/mypy.ini b/mypy.ini
index ec7a219c6..291fe64e3 100644
--- a/mypy.ini
+++ b/mypy.ini
@@ -91,9 +91,6 @@ ignore_errors = True
[mypy-manim.mobject.opengl.opengl_vectorized_mobject]
ignore_errors = True
-[mypy-manim.mobject.table]
-ignore_errors = True
-
[mypy-manim.mobject.types.point_cloud_mobject]
ignore_errors = True
diff --git a/tests/module/mobject/test_table.py b/tests/module/mobject/test_table.py
index 969ff202d..e4f7b186a 100644
--- a/tests/module/mobject/test_table.py
+++ b/tests/module/mobject/test_table.py
@@ -2,7 +2,9 @@
from __future__ import annotations
-from manim import Table
+import numpy as np
+
+from manim import Circle, Table
from manim.utils.color import GREEN
@@ -41,3 +43,56 @@ def test_table_include_inner_lines_true():
assert len(table.get_horizontal_lines()) == 3
assert len(table.get_vertical_lines()) == 3
+
+
+def test_table_accepts_iterable_data():
+ """Table data can be any iterable of iterables."""
+ data = (iter(row) for row in [["A", "B"], ["C", "D"]])
+
+ table = Table(data)
+
+ assert len(table.get_entries()) == 4
+
+
+def test_table_accepts_numpy_label_arrays():
+ """NumPy arrays remain valid iterables for row and column labels."""
+ for label_parameter, label_getter in (
+ ("row_labels", Table.get_row_labels),
+ ("col_labels", Table.get_col_labels),
+ ):
+ labels = np.empty(2, dtype=object)
+ labels[:] = [Circle(), Circle()]
+
+ table = Table(
+ [["A", "B"], ["C", "D"]],
+ **{label_parameter: labels},
+ )
+ actual_labels = label_getter(table)
+
+ assert len(actual_labels) == len(labels)
+ assert all(
+ actual_labels[index] is labels[index] for index in range(len(labels))
+ )
+
+
+def test_empty_label_iterables_are_treated_as_absent():
+ """Empty label iterables do not affect the other label dimension."""
+ col_labels = [Circle(), Circle()]
+ table_without_row_labels = Table(
+ [["A", "B"], ["C", "D"]],
+ row_labels=iter(()),
+ col_labels=col_labels,
+ )
+
+ assert len(table_without_row_labels.get_row_labels()) == 0
+ assert len(table_without_row_labels.get_col_labels()) == 2
+
+ row_labels = [Circle(), Circle()]
+ table_without_col_labels = Table(
+ [["A", "B"], ["C", "D"]],
+ row_labels=row_labels,
+ col_labels=iter(()),
+ )
+
+ assert len(table_without_col_labels.get_row_labels()) == 2
+ assert len(table_without_col_labels.get_col_labels()) == 0