Skip to content

Commit d77a47a

Browse files
MrDiverpre-commit-ci[bot]alembckeViicosJasonGrace2282
authored
Fix Typing (#3086)
* first draft of color class + starting library conversion * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * changed everything to Manim color todo: figure out circular dependency in utils * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * first working draft of new color version * resolving conflicts * resolving conflicts * resolving conflicts * resolving conflicts * resolving conflicts * changed default internal value of ManimColor to np.ndarray[float] * starting to fix tests * fixed more tests and changed precision of manim color * removed premature color conversion * fixed some more tests * final test changes * fix doctests * fix for 3.8 * fixing ManimColor string representation * removing some unneccesary conversions * moved community constants to manim_colors.py and added more color standards * Added typing.py and typed bezier.py, core.py, constants.py fully * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fixed codeql complaints * add type ignore for np.allclose * fixed import in three_dimensions * added ignore for F401 back again in flake * added typings to coordinate_systems.py * Few improvements to `graphing/coordinate_systems.py` * added some typings to mobject/geometry/line.py * updated typings for mobject/geometry/line.py * Add missing imports to `line.py` * added typings to three_dimensions.py * Use `FunctionOverride` for animation overrides Fix type signature of `set_color_by_gradient` * Remove `TYPE_CHECKING` check Doc is failing * Revert "Remove `TYPE_CHECKING` check" Fails due to circular import * Use `Self` in `coordinate_systems.py` * Typehinted mobject.py and updated manim.typing.py * Typed VMobject * Type-hinted manim.mobject.geometry * math.cos->np.cos, etc & fixed incorrect typehints * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix missing annotations import * TypeAlias fix in typing.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Add ignore errors again to mypy because commits are not possible like this * Fix last typing issues * Update docs * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Only type check manim * Try fixing pre-commit * fix merge * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix compat * Fix compat again * Fix imports compat * Use union syntax * Use union syntax * Fix reduce_across_dimension * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Various test and merge fixes * Doc fixes * Last doc fix * Revert usage of np over math * Bump numpy version * Remove obsolete duplicate example * Fixed Incorrect Typehint in manim.constants * Fix docstring typo * More fixes Use mypy.ini instead of .mypy.ini Fix more docstrings Improve types in utils and constants * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * docs fixes * Add internal aliases * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix compat * line lengths in .rst file, formatting, typos * add docstring for space_ops:cross2d * add some more arrow tip typings (in a non-circular import causing way) * yes, this can be deleted * fix formatting of example * added docstring to bezier::inverse_interpolation * added docstring + test for bezier::match_interpolate * some improvements in coordinate_systems * Vector -> Vector3 * replaced np.ndarray with more appropriate type hints * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Apply feedback * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * revert to previous (new) version * fix doctest * fix ReST errors --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Alex Lembcke <[email protected]> Co-authored-by: Viicos <[email protected]> Co-authored-by: JasonGrace2282 <[email protected]> Co-authored-by: Benjamin Hackl <[email protected]>
1 parent 25bb381 commit d77a47a

34 files changed

+2156
-1347
lines changed

.flake8

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
[flake8]
22
# Exclude the grpc generated code
3-
exclude = ./manim/grpc/gen/*
3+
exclude = ./manim/grpc/gen/*, __pycache__,.git,
4+
per-file-ignores = __init__.py:F401
45
max-complexity = 15
56
max-line-length = 88
67
statistics = True
@@ -9,7 +10,7 @@ rst-roles = attr,class,func,meth,mod,obj,ref,doc,exc
910
rst-directives = manim, SEEALSO, seealso
1011
docstring-convention=numpy
1112

12-
select = A,A00,B,B9,C4,C90,D,E,F,F,PT,RST,SIM,W
13+
select = A,A00,B,B9,C4,C90,D,E,F,F,PT,RST,SIM,W,F401
1314

1415
# General Compatibility
1516
extend-ignore = E203, W503, D202, D212, D213, D404
@@ -40,4 +41,4 @@ extend-ignore = E203, W503, D202, D212, D213, D404
4041

4142
# Plug-in: flake8-rst-docstrings
4243
RST201, RST203, RST210, RST212, RST213, RST215,
43-
RST301, RST303,
44+
RST301, RST303, RST499

.pre-commit-config.yaml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ repos:
5858
flake8-simplify==0.14.1,
5959
]
6060
- repo: https://github.com/pre-commit/mirrors-mypy
61-
rev: v1.4.1
61+
rev: v1.5.1
6262
hooks:
6363
- id: mypy
6464
additional_dependencies:
@@ -69,6 +69,7 @@ repos:
6969
types-requests,
7070
types-setuptools,
7171
]
72+
files: ^manim/
7273

7374
- repo: https://github.com/codespell-project/codespell
7475
rev: v2.2.5

docs/source/contributing/typings.rst

Lines changed: 44 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -2,102 +2,80 @@
22
Adding Typings
33
==============
44

5+
.. warning::
6+
This section is still a work in progress.
7+
58
Adding type hints to functions and parameters
69
---------------------------------------------
710

8-
.. warning::
9-
This section is still a work in progress.
11+
Manim is currently in the process of adding type hints into the library. In this
12+
section, you will find information about the standards used and some general
13+
guidelines.
1014

1115
If you've never used type hints before, this is a good place to get started:
1216
https://realpython.com/python-type-checking/#hello-types.
1317

14-
When adding type hints to manim, there are some guidelines that should be followed:
18+
Typing standards
19+
~~~~~~~~~~~~~~~~
1520

16-
* Coordinates have the typehint ``Sequence[float]``, e.g.
21+
Manim uses `mypy`_ to type check its codebase. You will find a list of
22+
configuration values in the ``mypy.ini`` configuration file.
1723

18-
.. code:: py
24+
To be able to use the newest typing features not available in the lowest
25+
supported Python version, make use of `typing_extensions`_.
1926

20-
def set_points_as_corners(self, points: Sequence[float]) -> "VMobject":
21-
"""Given an array of points, set them as corner of the Vmobject."""
27+
To be able to use the new Union syntax (``|``) and builtins subscripting, use
28+
the ``from __future__ import annotations`` import.
2229

23-
* ``**kwargs`` has no typehint
30+
.. _mypy: https://mypy-lang.org/
31+
.. _typing_extensions: https://pypi.org/project/typing-extensions/
2432

25-
* Mobjects have the typehint "Mobject", e.g.
33+
Typing guidelines
34+
~~~~~~~~~~~~~~~~~
2635

27-
.. code:: py
36+
* Manim has a dedicated :mod:`~.typing` module where type aliases are provided.
37+
Most of them may seem redundant, in particular the ones related to ``numpy``.
38+
This is in anticipation of the support for shape type hinting
39+
(`related issue <https://github.com/numpy/numpy/issues/16544>`_). Besides the
40+
pending shape support, using the correct type aliases will help users understand
41+
which shape should be used.
2842

29-
def match_color(self, mobject: "Mobject"):
30-
"""Match the color with the color of another :class:`~.Mobject`."""
31-
return self.set_color(mobject.get_color())
32-
33-
* Colors have the typehint ``Color``, e.g.
34-
35-
.. code:: py
36-
37-
def set_color(self, color: Color = YELLOW_C, family: bool = True):
38-
"""Condition is function which takes in one arguments, (x, y, z)."""
39-
40-
* As ``float`` and ``Union[int, float]`` are the same, use only ``float``
41-
42-
* For numpy arrays use the typehint ``np.ndarray``
43-
44-
* Functions that does not return a value should get the type hint ``None``. (This annotations help catch the kinds of subtle bugs where you are trying to use a meaningless return value. )
43+
* Always use a type hint of ``None`` for functions that does not return
44+
a value (this also applies to ``__init__``), e.g.:
4545

4646
.. code:: py
4747
4848
def height(self, value) -> None:
4949
self.scale_to_fit_height(value)
5050
51-
* Parameters that are None by default should get the type hint ``Optional``
52-
53-
.. code:: py
51+
* For variables representing paths, use the ``StrPath`` or ``StrOrBytesPath``
52+
type alias defined in the :mod:`~.typing` module.
5453

55-
def rotate(
56-
self,
57-
angle,
58-
axis=OUT,
59-
about_point: Optional[Sequence[float]] = None,
60-
**kwargs,
61-
):
62-
pass
54+
* ``*args`` and ``**kwargs`` shouldn't be left untyped (in most cases you can
55+
use ``Any``).
6356

57+
* Following `PEP 484 <https://peps.python.org/pep-0484/#the-numeric-tower>`_,
58+
use ``float`` instead of ``int | float``.
6459

65-
* The ``__init__()`` method always should have None as its return type.
66-
67-
* Functions and lambda functions should get the typehint ``Callable``
60+
* Mobjects have the typehint ``Mobject``, e.g.:
6861

6962
.. code:: py
7063
71-
rate_func: Callable[[float], float] = lambda t: smooth(1 - t)
72-
73-
74-
* Assuming that typical path objects are either Paths or strs, one can use the typehint ``typing.Union[str, pathlib.Path]``
64+
def match_color(self, mobject: "Mobject"):
65+
"""Match the color with the color of another :class:`~.Mobject`."""
66+
return self.set_color(mobject.get_color())
7567
76-
.. note::
77-
As a helper for tool for typesets, you can use `typestring-parser
78-
<https://github.com/Dominik1123/typestring-parser>`_
79-
which can be accessed by first installing it via ``pip`` - ``pip install typestring-parser`` and
80-
then using ``from typestring_parser import parse``.
68+
* Always parametrize generics (``list[int]`` instead of ``list``,
69+
``type[Any]`` instead of ``type``, etc.). This also applies to callables:
8170

82-
.. doctest::
83-
:options: +SKIP
71+
.. code:: py
8472
85-
>>> from typestring_parser import parse
86-
>>> parse("int")
87-
<class 'int'>
88-
>>> parse("int or str")
89-
typing.Union[int, str]
90-
>>> parse("list of str or str")
91-
typing.Union[typing.List[str], str]
92-
>>> parse("list of (int, str)")
93-
typing.List[typing.Tuple[int, str]]
73+
rate_func: Callable[[float], float] = lambda t: smooth(1 - t)
9474
9575
Missing Sections for typehints are:
9676
-----------------------------------
97-
* Tools for typehinting
98-
* Link to MyPy
77+
9978
* Mypy and numpy import errors: https://realpython.com/python-type-checking/#running-mypy
100-
* Where to find the alias
101-
* When to use Object and when to use "Object".
102-
* The use of a TypeVar on the type hints for copy().
103-
* The definition and use of Protocols (like Sized, or Sequence, or Iterable...)
79+
* When to use ``object`` vs ``Any``
80+
* The use of a TypeVar on the type hints for ``copy()``.
81+
* The definition and use of Protocols (like ``Sized``, ``Sequence``, ``Iterable``...)

manim/_config/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
]
2121

2222
parser = make_config_parser()
23-
logger: logging.Logger
2423

2524
# The logger can be accessed from anywhere as manim.logger, or as
2625
# logging.getLogger("manim"). The console must be accessed as manim.console.

manim/_config/logger_utils.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
if TYPE_CHECKING:
2828
from pathlib import Path
29+
2930
HIGHLIGHTED_KEYWORDS = [ # these keywords are highlighted specially
3031
"Played",
3132
"animations",

manim/_config/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@
2727

2828
from .. import constants
2929
from ..constants import RendererType
30+
from ..typing import StrPath
3031
from ..utils.color import ManimColor
3132
from ..utils.tex import TexTemplate, TexTemplateFromFile
32-
from ..utils.tex_templates import TexTemplateLibrary
3333

3434

3535
def config_file_paths() -> list[Path]:
@@ -76,7 +76,7 @@ def config_file_paths() -> list[Path]:
7676

7777

7878
def make_config_parser(
79-
custom_file: str | os.PathLike | None = None,
79+
custom_file: StrPath | None = None,
8080
) -> configparser.ConfigParser:
8181
"""Make a :class:`ConfigParser` object and load any ``.cfg`` files.
8282

manim/animation/changing.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
from typing import Callable
88

9-
from manim._config import config
109
from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL
1110
from manim.mobject.types.vectorized_mobject import VGroup, VMobject
1211
from manim.utils.color import (

manim/animation/creation.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ def construct(self):
9292
from ..mobject.mobject import Group, Mobject
9393
from ..mobject.types.vectorized_mobject import VMobject
9494
from ..utils.bezier import integer_interpolate
95-
from ..utils.rate_functions import double_smooth, linear, smooth
95+
from ..utils.rate_functions import double_smooth, linear
9696

9797

9898
class ShowPartial(Animation):

manim/animation/indication.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ def construct(self):
4545
from manim.mobject.geometry.line import Line
4646
from manim.mobject.geometry.polygram import Rectangle
4747
from manim.mobject.geometry.shape_matchers import SurroundingRectangle
48+
from manim.scene.scene import Scene
4849

4950
from .. import config
5051
from ..animation.animation import Animation
@@ -313,7 +314,7 @@ def _get_bounds(self, alpha: float) -> Tuple[float]:
313314
lower = max(lower, 0)
314315
return (lower, upper)
315316

316-
def clean_up_from_scene(self, scene: "Scene") -> None:
317+
def clean_up_from_scene(self, scene: Scene) -> None:
317318
super().clean_up_from_scene(scene)
318319
for submob, start in self.get_all_families_zipped():
319320
submob.pointwise_become_partial(start, 0, 1)

manim/camera/camera.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
import itertools as it
1010
import operator as op
1111
import pathlib
12-
import time
1312
from functools import reduce
1413
from typing import Any, Callable, Iterable
1514

0 commit comments

Comments
 (0)