Python

Table of Contents

1. Type

1.1. int

  • .bit_length(): length of digits in binary. Exclude the sign and leading zeros.
  • .bit_count(): number of ones in binary. Exclude the sign. aka. population count.

1.2. str

  • .format(): formats {(<empty>|<int>|<identifier>):<format_spec>} within the string.
    • It calls the __format__ of the object with <format_string>.

1.2.1. Formatted String Literal

  • F-String
  • The newest method of formatting
  • f"...{<object>:<format_spec>}..."
  • f"...{<object>!(s|r|a)}...": Specify conversion method. s for str, r for repr, a for ascii
  • f"...{<object>}…"=

1.2.2. Format Specification Mini-Language

1.2.3. String Interpolation

  • C-Style formatting
  • Use % operator
  • The oldest method of formatting
  • It does not use the __format__ method of the object. The object of the correct type must be provided.
  • "...%<c_format_string>..." % <object>
  • "...%<c_format_string>...%<c_format_string>..." % <iterable_object>

1.2.4. Methods

Strings are also an Iterable. Use list constructor to split individual characters.

  • replace(old: str, new: str, counts: int) replace the old text with new text counts times from the beginning of the string.

2. Syntax

2.1. Set operations

  • Generalized bitwise operations.
  • A - B: in A, not B.
  • A & B: in A and In B.
  • A | B: in A or in B.
  • A ^ B: in A not B, or in B not A.
    • Shorthand for symmetric_difference

2.2. Loops

Python does not have label for loops. Use exception instead.

2.3. Match

x = (2,3)
match x:
    case 1 | 2:
        print("case 1")
    case (a, b):
        print(a+b)
    case _:
        print("fallback")

2.4. Error Handling

try:
    # codes before
    raise Exception()

# codes after
except Exception as e:
    # code if error

3. Function

3.1. Built-In

  • format(<object>, <format string>) apply str to the object and format it.
  • iter() calls the __iter__() method that returns a generator.
  • next() calls the __next__() method

3.2. Decorator

  • @<decorator> is used before a function definition.
  • A decorator is a function that act on a function and ouputs a function.
@decorator
def f():
    pass     # is equivalent to

f = decorator(f)

4. Class

4.1. Static Methods

  • .__subclasses__() -> List[class]

4.2. Initialization

  • def __init__(self, ...): is called when the object is being initalized.

    • def __new__(cls, ...) -> <instance>: is called when the object

    is being created.

4.3. Dunder Methods

  • __add__(self, other), __sub__(self, other) is called when the standard binary operation is performed.

    • __radd__(self, other), __rsub__(self, other) is called when

    the object comes after the operator.

  • __invert__(self) is called when binary not operator ~ is used.
  • __call__(self, ...) is called when the object itself is called.
  • __str__(self), __repr__(self) is called when an object is to be shown. The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter.1

    • print(), str(), format() call str on the object. It

    calls __str__, when it is not defined, calls repr. repr calls __repr__, when it is not defined it returns the default representation.

    • A cell in ipython shell will return the repr of an object.
  • __getattr__(self, key) is called when there's no property of name key.

    • e.g. obj.some_key => obj.__getattr__("some_key")
    • __getattribute__(self, key) is always called when accessing a

    property and overrides others.

  • __format__(self, format_string) -> str is called on format(<obect>, <format_string>).

4.4. Inheritance

  • Every class is inherited from the metaclass type.

4.4.1. Superclass

  • Accessed with super(). It traverses the inheritance stack and find the closest one.

4.4.2. Method Resolution Order

MRO

  • Methods and super function follow this. If methods conflict when inherited from multiple classes, method with higher order is used, that is the one comes first.
  • __mro__() or .mro() to see the resolution order.

See Method resolution order in Python Inheritance - GeeksforGeeks

5. Import

Parent Directory is not accessible, unless it's in sys.path.

It has three steps:

  1. Try to import with finders in sys.meta_path one by one. If none succeed, the import error occurs. logseq.order-list-type:: number
  2. Finder returns a loader of a module. logseq.order-list-type:: number
  3. Execute the loader to create a module. logseq.order-list-type:: number

5.1. Finders

  • System Path -> Local Path -> Others

5.2. Relative Import

This is not referring to the relative path. Use regular import for direct import.

  • Prefix with ., .., ..., … each for this package, parent package, grandparent package, …
  • Only from ... import ... is possible.

6. Module

  • Python module is a directory containing __init__.py which runs when the module is imported.
  • It can be used from the command line with python -m <modulename>

6.1. venv   builtin

  • python -m venv DIR
    • --system-site-packages: Allow the access to the system packages.
  • VENV/bin/activate is the script that setup the virtual environment.

7. Packages

  • Packages are stored in /usr/lib/pythonN.NN/site-packages/

7.1. functool   builtin

  • partial partial application of a function

7.2. itertool   builtin

  • groupby(Iterable, key=Function) -> Dict{Function -> A: A : List[Iterable -> B: B]}
  • takewhile(Function -> bool, Iterable) take the elements one by one until it's evaluated to false.
  • Take inspiration from APL.

7.3. collections   builtin

  • deque class
    • It supports popleft, appendleft, extendleft

7.4. glob   builtin

  • The standard Unix path expansion within Python.
  • Method: glob('<pattern>') -> list[str]

    • Return: List of filenames that matches the pattern in current

    directory.

7.4.1. Patterns

  • ? any single letter.
  • * multiple letters.
  • [...] any character that is included.
  • [!...] any character that is not included.
  • **/* recursive.

7.5. subprocess   builtin

A replacement for os

  • run(cmds: list[str]) -> CompletedProcess run the shell command

7.6. os   builtin

  • remove(path) remove a file

7.7. re   builtin

  • match(pattern: str, string: str) -> Match check if the entire string exactly match the pattern
  • search(pattern: str, string: str) -> Match look for a substring that matches the pattern
  • findall(pattern, string, flags=0) -> list[str] match all occurences
  • finditer(pattern, string, flags=0) -> Iterable[Match]
  • Match
    • .expand(template: str) -> str perform substitution on the template
    • .group(group: str|int|list[str|int]) -> str|tuple[str]
  • See re — Regular expression operations — Python 3.13.2 documentation

7.8. typing   builtin

  • Protocol creates inheritance-free interfaces. class Interface(Protocol): value: int def func(param: int) -> int: ...

7.9. threading   builtin

  • Thread(target=..., [args=...]) setup the thread, and thread.start() starts it.
  • thread.join() is where the thread returns.

7.10. logging   builtin

  • Modern Python logging - YouTube
  • logging is the root logger.
  • logger = logging.getLogger() makes a child logger.
  • logger can show debug, info, warn, error, exception or critical

7.11. inspect   builtin

  • see source code.

7.12. importlib   builtin

  • import customization

7.13. csv   builtin

  • csv.writer

    • Instance of this(_writer) will take the file and the table and

    write it.

  • csv.reader

    • Instance of this(_reader) is an iterable that gives out each

    line.

7.14. pickle   builtin

Object Serialization

7.15. random   builtin

  • random() sample uniformly between 0 and 1
    • uniform(a, b) uniform distribution
    • gauss(mu=0, sigma=1) Gaussian distribution
  • choice(seq: Iterable) select random element
  • choices(population: Iterable, weghts: Iterable|None, *, cum_weghts: Iterable|None, k: int)
    • select k elements from population allowing repetition.
    • cum_weights are the cumulative weights.
  • shuffle(x)
  • sample(population, k, *, counts=None)
    • select k unique elements

7.16. doctest and unittest   builtin

Builtin Python functionality for testing.

  • Examples section within the function docstring would run on doctest.modtest().

7.17. returns

Use functional programming style, such as monad.

7.18. numpy

7.18.1. Broadcasting

When two arrays of different rank are point-wise operated (e.g. +, *), the sizes of the arrays are broadcasted to match each other.

The steps of determining the broadcast is:

  • The shape of the smaller rank is padded with 1 on the left.
  • Compare the length of each axis and
    • If they are equal, do nothing
    • If one of them is 1, broadcast it to match the other.
    • Otherwise throw an error.
7.18.1.1. Examples

Let me write the numpy array as a regular array, for the ease of reading.

A = [[1,1,2],
     [1,2,1],
     [2,1,1]]
B = [1,2,3]

A * B
# output
#  [[1,2,6],
#  [1,4,3],
#  [2,2,3]]

A * B[:, None]
# output
#  [[1,1,2],
#   [2,4,2],
#   [6,3,3]]

In the first case, the shape is padded on the left:

# right align
A: (3, 3) 
B:    (3,)

# pad 
A: (3, 3)
B: (1, 3)
    ↑  ↑
    |  ⌞________﹁
broadcast      match (do nothing)

and broadcasted:

# broadcast
B: (1, 3)  -> (3, 3)
B: [1,2,3] -> [[1,2,3],
               [1,2,3],
               [1,2,3]] 

In the second case, B gains a new axis at the position of None before the broadcasting:

# B[:, None] also known as "unsqueeze"
B: (3, )   -> (3, 1)  
   [1,2,3] -> [[1],
               [2],
               [3]]

# right align (no padding required)
A: (3, 3)
B: (3, 1)
    ↑  ↑
    |  ⌞________﹁
  match      broadcast

# broadcast
B: (3, 1) -> (3, 3)
   [[1],     [[1,1,1],
    [2],  ->  [2,2,2],
    [3]]      [3,3,3]]

7.19. pyautogui

7.20. shutil

7.21. pydantic

  • Struct annotation
  • BaseModule

    • It is inherited to specify the structure of an object, which

    then can be instantiated directly, or a ((66b7fc0d-d021-48de-97f7-471cdcd6fd52)) can be passed with ** spread.

    • A property of a BaseModule can be another BaseModule and the

    JSON data is automatically propagated accordingly.

  • Field
    • It defines the details of a field within the BaseModule

7.22. SQLAlchemy

SQL interface

7.23. beautifulsoup

HTML parser

7.24. Cookiecutter

Project Templates

7.25. PuLP

7.26. PyTorch

  • Machine Learning Framework based on the Torch library.
  • Originally developed by Meta AI and now part of the Linux Foundation.
  • import torch

7.26.1. Tensor

  • <tensor>.dtype -> torch.<type>
    • <tensor>.to(torch.<type>) -> <tensor> converts the dtype.
  • <tensor>.device -> <device>. <device> : device(type='cpu'|'cuda'|…)=

    • <tensor>.to(<device>) -> <tensor> converts the device.
    • torch.device(<str>) -> <device>
    • torch.cuda.is_available() -> bool,

    torch.cuda.device_count() -> int

  • <tensor>.shape -> torch.Size(<array>)
  • Tensors on the CPU share the memory with numpy array.
    • <tensor>.numpy() -> <numpy array>
    • torch.from_numpy(<numpy array>) -> <tensor>
7.26.1.1. Construction
  • torch.tensor(<array>, [dtype = torch.<type>, device = <str>, requires_grad = <bool>]) -> <tensor>

    • <array> can be numpy array.
    • <tensor>.requires_grad_(<bool>) also sets it.
    • with torch.no_grad(): disables the tracking for

    by any new variables.

    • Use it when the parameters are frozen or it does not require

    gradient.

    • <tensor>.detach() -> <tensor> disables the tracking.
  • torch.empty(<dimen>), torch.zeros(<dimen>), torch.ones(<dimen>), torch.rand(<dimen>)
  • torch.arange(start: float, end: float, step: float, ...) -> <tensor> returns first order tensor.
  • torch.ones_like(<tensor>), torch.rand_like(<tensor>) create tensor with the same shape and datatype.
  • torch.cat([<tensor>,...], dim = <int>) concatenate tensors along the dim.
  • torch.stack([<tensor>, ...], dim = <int>) concatenate tensors along a new dimension.
7.26.1.2. Slice
  • tensor[<slice, ... >] -> <tensor>. <slice> : [int]":"[int]|int=
7.26.1.3. Reshape
  • tensor.view(<dimen>). Use -1 for the value to be automatically determined.
7.26.1.4. Operation
  • <tensor>.T: Transpose
  • torch.add(<tensor>*), <tensor> +|- <tensor>
    • <tensor>.add_(<tensro>)
  • torch.mm(<tensor>*), <tensor> @ <tensor>: matrix multiplication. torch.mul(<tensor>*), <tensor> * <tensor>: component-wise multiplication.
  • <tensor>.sum() -> <tensor> returns a scalar tensor of the sum of all the components.
  • <tensor>.item() -> <component> return the component of a scalar tensor.
7.26.1.4.1. In-place Operation
  • Denoted by _ suffix.

7.26.2. Function

  • Function has Function.grad_fn which is its derivative.

7.26.3. Loss Function

  • Compute the derivative of loss function with respect to parameters
  • w = torch.tensor(..., requires_grad = true) <loss>.backward() w.grad -> <tensor of the gradients in each components>

7.26.4. Optimizer

  • Gradients add up by default. <optimizer>.zero_grad() to reset it to zero.
  • ** Stochastic Gradient Decent

    :CUSTOMID: stochastic-gradient-decent

    • torch.optim.SGD(<model>.parameters(), lr = <learning_rate>)
  • <loss>.backward() <optimizer>.step() # perform one decent <optimizer>.zero_grad()

7.26.5. Hyperparameters

  • batch_size: int = 64: number of samples decent per step.
  • learning_rate: float = 1e-3: related to the decent step size.
  • epochs: int = 5: Number of iteration over the entire dataset.

7.26.6. Computational Graph

  • Tensors and Functions construct a computational graph.
  • torch.autograd keeps the record of executed operations in a directed acyclic graph(DAG).
  • .backward() is called on the root of DAG.

7.27. PyMuPDF

  • Based on MuPDF or MμPDF.
  • import fitz

7.28. tkinter

  • Based on tk originally written in tcl, the programming language.
  • # pacman -S tk is required on Arch machine, although the tkinter package is installed.
  • tkinter.Tk is the root object that is at the top of the widget hierarchy.
  • A widget can be configured through the initialization, or .config[ure](), or ["option"] =

7.28.1. tkinter.Variable

  • Variable, StringVar, IntVar, BooleanVar.
  • They have .get and .set method to change their value.
  • It is passed to the widget as a textvariable parameter as the ouput, and work as a bridge between value producer and cosumer.

7.28.2. ttk

  • from tkinter import ttk
  • The designed widget library of Tk
  • Defines Frame, Label, Entry, Button, ComboBox, Scale, SpinBox, ProgressBar, …
  • Parameter command is a blocking function. If the handling takes a long time, it needs to be threaded.
  • Button has three state: normal, disabled, active

7.28.3. Geometry Manager

  • It places the widgets.
  • Widget.grid: it is the method to place the widget within the master widget in a grid.

7.28.4. Submodules

  • ttk: Widgets
  • filedialog: File selection dialog
  • messagebox: Info/Error dialog

7.28.5. togl

  • it is a tk widget for OpenGL rendering.
  • Python interactive help modules required the PyOpenGL has Togl installed.

7.29. manim

  • Installed within ~/Video/alsciokat/.venv

7.29.1. Structure

7.29.1.1. Mobject
7.29.1.1.1. class mobject.Mobject
  • PARAMETER
    • color: ParsableManimColor | list[ParsableManimColor]
    • name: str | None
    • dim: int
    • z_index: float
  • ATTRIBUTE
    • animate See ((669ebee9-b376-4c59-a8da-95747098b2e5))
    • submobjects: list[Mobject]
    • points: numpy.ndarray
    • depth, width, height
  • METHOD
    • add(*mobjects: Mobject) Add as a submobject
    • remove(*mobjects: Mobject)
    • copy()
    • get_...()
    • set_...() -> self
    • match_...() -> self
    • align_to(mobject_or_point: Mobject | Point3D, direction=array([0.,0.,0.]): Vector3D) -> self
      • align mobject to another mobject in certain direction.
    • move_to an Mobject or a point. Useful for centering things
    • next_to
    • to_edge
    • center
    • arrange
    • arrange_in_grid
    • shift()
    • scale()
    • rotate()
    • flip()
    • add_updater(update_function: Updater, index=None: int | None, call_updater=False: bool) -> self
      • update_function See ((669f5743-827d-4b3f-8279-b9b924123a2e))
      • index the index within the self.updaters the function to be added. Added to the last if None
      • call_updater whether call updater in the beginning
7.29.1.1.2. class types.vectorized_mobject.VMobject
  • Bases: Mobject
  • Mobjects except points are vectorized mobject.
  • PARAMETER
    • fill_color
    • fill_opacity
    • stroke_color
    • stroke_opacity
    • stroke_width
  • METHOD
    • set_opacity
    • set_color
    • set_fill
    • set_points_smoothly(points)
7.29.1.1.3. Texts
  • Module: .text.
7.29.1.1.3.1. TeX
  • Module: tex_mobject.
  • class SingleStringMathTex
    • Bases: SVGMobject <- Bases: VMobject
    • PARAMETERS
      • tex_string: str
      • stroke_width: float
      • font_size=48: float
      • tex_environment'align*': str=
      • should_center=True: bool
      • tex_template=None: TexTemplate | None
        • class minim.utils.tex.TexTemplate specifies preambles.
  • class MathTeX
    • Bases: SingleStringMathTex
    • Double braces {{...}}, or splitting strings divides them into submobjects. They are flattened to create a singule list of submobjects.
    • Since the environment is align* by default, & and \\ are allowed.
    • PARAMETERS
      • *tex_strings: str multiple tex mobject is created as submobjects.
    • METHODS
      • get_part_by_tex(tex: str) -> MathTex
      • index_of_part(mobject?)
      • index_of_part_by_tex(tex: str) -> MathTex
      • set_color_by_tex(tex: str, color: ParsableManimColor)
      • set_opacity_by_tex(tex: str, opacity: float)
  • class Tex
    • Bases: MathTex
7.29.1.1.3.2. Pango
  • Module: .text_mobject
  • The text is rendered using ((669c64ae-993e-4b9a-b8d6-1ddcb3c2e62a))
  • class MarkupText
    • Bases: SVGMobject
    • PARAMETER
      • text: str accept the markup text
      • font: str
      • font_size: float
      • gradient: tuple
      • color: ParsableManimColor
      • slant: bool
      • fill_opacity: float
      • stroke_width: float
  • class Text
    • Bases: SVGMobject
    • PARAMETER
      • The Pango options are given in the form of parameters.
      • disable_ligature: bool
      • t2w: dict[str, str]
        • Set weight
        • The key is either a word 'word', or a range [2:4], and the value is the option.
      • t2s: dict[str, str]
        • Set slant
      • t2c: dict[str, str]
        • Set color
  • class Paragraph
    • Bases: VGroup
    • PARAMETER
      • *text: str
      • line_spacing-1: float= -1 means auto
      • alignment=None: 'left' | 'center' | 'right' | None
    • ATTRIBUTE
      • chars: VGroup[VGroup[char]] Group of lines that are groups of characters.
7.29.1.1.4. Geometries
  • Module: .geometry.
  • class arc.TipableVMobject
    • Bases: VMobject
    • PARAMETERS
      • tip_length=0.35: float
      • normal_vector=array([0., 0., 1.]): Vector3D
      • tip_style={}: dict
    • METHODS
      • add_tip(tip=None)
      • create_tip()
      • get_tip() get_tips()
      • has_tip()
      • has_start_tip()
      • pop_tips()
      • get_start()
      • get_end()
  • abstract class tips.ArrowTip
    • Bases: VMobject
    • It is to be extended together with other =mobject=s
    • ATTRIBUTES
      • base: Point3D the base of the tip
      • color
      • fill_color
      • tip_angle: float
      • tip_point: Point3D
      • vector: Vector3D vector from the base to the tip point
  • ArrowTriangleTip, ArrowTriangleFilledTip
    • Bases: ArrowTip, Triangle
  • StealthTip
    • Bases: ArrowTip
    • ((669f099c-a556-402b-94c8-aa4a94f3cf1c)) arrow shape
  • class line.Line
    • Bases: TipableVMobject
    • PARAMETERS
      • start=array([-1,0,0]): Vector3D
      • end=array([1,0,0]): Vector3D
    • METHODS
      • generate_points(), init_points()
        • Empty method that is called upon creation, implemented by subclasses
      • get_projection(point: Point3D) -> Vector3D
      • get_angle(), get_slope(), get_unit_vector()
      • set_angle(), set_length()
      • put_start_and_end_on(start: Point3D, end: Point3D) -> self
  • class line.TangentLine
    • Bases: Line
    • PARAMETERS
      • vmob: VMobject
      • alpha: float value between 0 and 1 that represents the position within the vmob
      • length=1: float
      • d_alpha=1e-06: float uncertainty in alpha?
  • class line.DashedLine
    • Bases: Line
    • PARAMTERS
      • dashed_length=0.05: float the length of each dash
      • dashed_ratio=0.5: float the ratio of dash space to empty space, ranging between 0 and 1
  • class shape_matchers.Underline
    • Bases: Line
    • The underline mobject
    • PARAMETERS
      • mobject: Mobject
      • buff=0.1: float
  • class line.Vector
    • Bases: Arrow
    • PARAMETER
      • direction: Point2D | Point3D
      • buff: float distance of the vector form its endpoints.
7.29.1.1.5. Groups
  • class mobject.Group
  • Bases: Mobject
  • Nothing more than mobjects bunched together into a single mobject,
  • since a Mobject can already handle grouping.
  • class types.vectorized_mobject.VGroup
  • Bases: VMobject
  • PARAMETER
    • *vmobjects: VMobject
  • METHOD
    • add(*vmobjects: VMobject) -> VGroup
    • The dunder methods are also defined! +, +=, -, -= are all possible with any Mobject, or VGroup.
7.29.1.1.6. Graphing
  • Module: .graphing.
  • abstract class coordinate_systems.CoordinateSystem
    • Bases: object
    • PARAMETER
      • x_range=None: Sequence[float] | None [<start>, <end>], [<start>, <end>, <step>]
      • y_range=None: Sequence[float] | None
      • x_length=None: float | None
      • y_length=None: float | None
      • dimension=2: int
    • METHOD
      • add_coordinates(*axes_numbers: Iterable[float] | None | dict[float, str | float | Mobject]) Add labels to each axis manually, they are in canonical order, use None to skip an axis.
      • get_area(graph: ParametricFunction, x_range: tuple[float, float], color: ParsableManimColor | Iterable[ParsableManimColor], opacity=0.3: float, bounded_graph=None: ParametricFunction)
        • Get are under the graph (between it and bounded_graph if specified) with color and opacity. If color is Iterable then it becomes gradient.
      • get_graph_label()
      • get_horizontal_line()
      • get_vertical_line()
      • get_vertical_lines_to_graph()
      • get_line_from_axis_to_point()
      • get_lines_to_point()
      • get_origin()
      • get_x_axis_label(label: float | str | Mobject) get_y_axis_label()
        • It positions the label, and return it.
      • input_to_graph_point(x: float, graph: ParametricFunction | VMobject) -> np.ndarray
      • plot(function: Callable[[float], float], x_range=None: Sequence[float] | None) -> ParametricFunction
  • class number_line.NumberLine
    • Bases: Line
    • PARAMETERS
      • x_range=None: Sequence[float]|None [<min>, <max>, <step>] for the line
      • length=None: float|None
      • unit_size=1: float distance between each tick. overwritten if length specified
      • include_ticks=True: bool
      • tick_size=0.1: float
      • numbers_with_elongated_ticks=None: Iterable[float]|None
      • longer_tick_multiple=2: int the scaling factor of the length of the longer tick
      • rotation=0: float angle of the lines
      • include_tip=False: bool
      • scaling=LinearBase: _ScaleBase LogBase is also possible
      • line_to_number_buff=0.25: float
      • numbers_to_exclude=None: Iterable[float]|None, numbers_to_include=None: Iterable[float]|None
    • METHODS
      • add_labels(dict_values: dict[float, str|float|VMobject] dictionary from position to mobject
      • add_numbers(x_values: Iterable[float]) Add DecimalNumber mobject
      • add_ticks
      • number_to_point(number: float | ndarray) -> ndarray, n2p(number)
      • point_to_number(point: Sequence[float]) -> float, p2n(point)
  • class coordinate_systems.Axes
    • Bases: VGroup, CoordinateSystem
    • PARAMETER
      • axis_config=None: dict | None
        • The configuration of the number lines
        • axis_config it is passed down to the Numberline
        • x_axis_config, y_axis_config to control individually
      • tips=True: bool
    • METHOD
      • coords_to_point(*coords: float | Sequence[float] | Sequence[Sequence[float]] | ndarray) -> np.ndarray
      • points_to_coords(point: Sequence[float]) -> np.ndarray[float]
      • get_axes() -> VGroup[Axis]
  • class coordinate_systems.NumberPlane
    • Bases Axes
    • PARAMETER
      • background_line_style=None: dict[str, Any] | None
      • faded_line_style
      • faded_line_ratio=1: int
    • The axes are Line from Axes, and grid lines are its own.
7.29.1.1.7. Vector Field
  • class VectorField
  • class StreamLines
7.29.1.2. Animation
  • class manim.animation.animation.Animation
  • OVERRIDES
  • def __init__(self, mobject: Mobject, ..., **kwargs)
    • Take the animation parameters, including the mobject to be animated.
    • Don't forget

      super().__init__(mobject, **kwargs)
      
  • def interpolate_mobject(self, alpha: float)
    • Take the progression \(\alpha\) of the animation, and set the mobject accordingly.
  • PARAMETERS
  • lag_ratio: float Apply lags in between the animations of submobjects.
  • rate_func: Callable[[float], float] Determine the rate at which the animation moves
    • rate_functions is predefined for this.
      • .linear
  • run_time: float The length of the animation in second.
  • METHODS

    This is not present for the _AnimationBuilder which is the return of the mobject.animate

  • set_rate_func(rate_func) -> self
  • set_run_time(run_time) -> self
  • begin() begin the animation
  • finish() finish the animation
  • copy() -> Animation create copy
  • class _AnimationBuilder
    • It creates animation that interpolates between current state and the state defined by following method chain.
    • mobject.animate.set_opacity(1).shift(UP)
    • The animation builder itself can be configured by calling it with parameters: .animate()
    • run_time: float
      • rate_func: Callable
7.29.1.2.1. Updater
  • Updater
    • NonTimeBasedUpdater: Callable[[Mobject], object]
    • TimeBasedUpdater: Callable[[Mobject, float], object]
  • They are stored within the mobject.updaters, and they are called when mobject.update() is called, which happens every frame by defualt.
  • In the case of TimeBasedUpdater the second argument dt is the time past since the last frame given in seconds.
7.29.1.2.2. Transformation
  • class minim.animation.transform_matching_parts.TransformMatchingTex
    • PARAMETER
      • mobject: Mobject
      • target_mobject: Mobject
      • transform_mismatches=False: bool
      • fade_transform_mismatches=False: bool
    • Two mobjects match if their tex_string matches.
      • Groups of mobjects can be transformed into one another, where groups can be created xplicitly or by the use of MathTex.
      • Each submobject of target_object is checked whether there exists matching tex_string in the mobject, and if a match is found, the transformation from the submobject of the mobject to that of target_mobject is generated.
  • class manim.animation.transform.ReplacementTransform
    • Bases: Transform
    • PARAMETER
      • mobject: Mobject
      • target_mobject: Mobject
    • Morph the mobject into target_mobject, while replacing the target_mobject.
  • class manim.animation.transform.FadeTransform
    • Bases: Transform
7.29.1.3. Scene
  • Module: manim.scene
  • class scene.Scene
  • This class is to be inherited in order to create a scene.
  • OVERRIDE
    • def construct(self):
      • the content of the scene is specified within this method.
  • METHOD
    • add(*mobjects: Mobject) -> Scene
      • Simply add the mobjects to the scene so that it can be displayed.
    • play(*args: Animation | Iterable[Animation])
      • Play the animation
      • The mobject needs to be added first in order to animate with .animate.
    • wait(duration=1.0: float)
      • No op, for duration seconds.
    • remove(*mobjects: Mobject
  • class section.Section
  • self.next_section()
    • Call within the construct method, starts a new section. Section will be removed if there's no animation.
    • The name of the section can be specified as the parameter.
  • First section is automatically started.
  • Use 6 options to save them

7.29.2. Boolean Operation

  • manim.mobject.geometry.boolean_ops.
  • class Union, class Intersection, class Difference, class Exclusion
    • PARAMTERS
      • *vmobjects: VMobject
      • **kwargs

7.29.3. Utilities

7.29.3.1. Update Utilities
  • always(method: Callable, *args, **kwargs) -> Mobject
  • always_redraw(func: Callable[[], Mobject]) -> Mobject Redraw the mobject at each frame
  • always_rotate(mobject, rate), always_shift(mobject, direction, rate)
  • turn_animation_into_updater(animation, cycle=False, **kwargs) -> Mobject
    • Add updater of the animation to the mobjects being animated.
7.29.3.2. Value Tracker
  • manim.mobject.value_tracker.
  • class ValueTracker
    • Bases: Mobject
    • PARAMETERS
      • value=0: float
    • METHODS
      • get_value() -> float
      • increment_value(d_value: float)
      • set_value(value: float)
      • interpolate(mobject1: Mobject, mobject2: Mobject, alpha: float, path_func)
  • class ComplexValueTracker
    • Bases: ValueTracker

7.29.4. Configuration

7.29.4.1. Config File
  • manim.cfg
    • Library scoped: Provided by the library
    • User scoped: ~/.config/manim/manim.cfg
    • Folder scoped: within the same directory as the python file
  • FORMAT
    • toml [CLI] full_option_name = value ...
7.29.4.2. Command Line
  • -t --transparent Use transparent background and output in .mov format
  • -p --preview Show preview on render completion
  • --preview_command <program> Preview using <program>
  • -q[l|m|h|p|k] --quality [l|m|h|p|k]

    • l for 854 × 480 15 FPS, m for HD 30 FPS, h for

    FHD 60 FPS, p for QHD 60 FPS, k for UHD 60 FPS

  • -s --save_last_frame As a PNG
  • --save_sections
    • save sections under the media/videos/<scene>/<quality>/sections/.
  • -c? --background_color COLOR Set the background to the one of the colors predefined.
  • --flush_cache Remove all partial movies in this directory.
  • --disable_caching Do not generate partial movies?

7.29.5. CLI

  • manim
    • render Used when nothing specified
    • cfg
      • write write a manim.cfg file within a terminal step by step

7.30. sympy

  • sympy. Package Structure

    • abc.
      • This module contains the common variables: a, b, x, y, z, t,

    which can also defined directly by sympy.symbols("x y z": str) -> list[Symbol]

    • core.
      • symbol.
        • class Symbol
      • numbers.
        • class Integer
        • class Rational
      • expr.
        • class Expr
          • probably the parent class of most of the classes.
          • .equals(Expr) -> bool
          • .subs(Expr, Expr) .subs(Iterable[tuple[Expr, Expr]])
          • .evalf() -> float
          • .rewrite(Expr)
          • .diff(Iterable[Tuple[Symbol, int|Symbol]]) -> Expr
          • .series(Symbol, start_order: int, end_order: Number)
          • .removeO() -> Expr
          • .func The parent node
          • .args top-level argument
      • relational.
        • class Equality alias Eq
          • .__init__(Expr, Expr)
    • matrices.
      • class MutableDenseMatrix alias Matrix
        • .__init__(Iterable[Iterable[Number]])
        • .row(int) -> Covector .col(int) -> Vector
        • .nullspace() -> list[Vector],

    .columnspace() -> list[Vector]

    • .eigenvals() -> dict[eigenvalue, algebraic_multiplicity]
    • .eigenvects() -> list[tupe[eigenvalue, algebraic_multiplicity, list[eigenvector]]]
    • .charpoly(Symbol) -> Expr
    • vector.

      • coordsysrect
        • class CoordSys3D(name: str, transformation: Lambda, Tuple, str)
          • transformation includes "spherical", …
          • .x .y .z coordinate variables
          • .i .i .k unit vectors
          • .create_new(name: str, transformation) -> CoordSys3D
          • .locate_new(name: str, position: Vector) -> CoordSys3D
          • .orient_new(name: str, orienters) -> CoordSys3D
          • .base_vectors() -> tuple[Vector]

      .base_scalar() -> tuple[Expr]

      • vector
        • class Vector
          • .components -> dict[basis_vector, component]
          • .cross(Vector) -> Vector, .dot(Vector) -> Number
          • .magnitude() -> Number, .normalize() -> Vector
          • .outer(Vector) -> Dyadic
          • .projection(Vector) -> Vector
          • .separate() -> dict[CoordSys3D, Vector]
          • .to_matrix(CoordSys3D) -> Matrix
      • dyadic
        • class Dyadic
      • parametricregion
        • class ParametricRegion(definition: tuple[Expr*], *bounds: *tuple[Symbol, Number, Number]])
      • implicitregion
        • class ImplicitRegion(tuple[Symbol*], Expr)
      • express(Vector|Dyadic|sympyfiable, CoordSys3D, CoordSys3D?, bool) -> Vector|Dyadic|Expr
      • curl(Vector) -> Vector
      • divergence(Vector) -> Expr
      • gradient(Expr) -> Vector
      • is_conservative(Vector) -> bool
    • integrals.
      • integrals.
        • class Integral
        • class ParametricIntegral(Vector | sympyfiable, ParametricRegion)
      • vector_integrate(Vector, region | *bounds)
    • physics.

      • vector.
        • This vectors are different from the regular Vector
        • frame.
          • class ReferenceFrame(name: str)
            • .x .y .z basis vectors
            • .orient(ReferenceFrame, rot_type: str, amount: list[Symbol, Vector])
              • rot_type can be 'Axis' to rotates the reference

      frame by Symbol amount arount Vector axis.

      • [0] [1] [2] coordinate variable
      • class CoordinateSym(name: str, ReferenceFrame, index: int)
        • Extract the coordinate variable
      • vector.
        • class Vector
          • .diff(Symbol, ReferenceFrame) -> Vector
          • .cross(Vector) -> Vector, .dot(Vector) -> Expr
          • .express(ReferenceFrame, variables: bool) -> Vector|Expr
          • .magnitude() -> Expr, .normalize() -> Vector
          • .outer(Vector) -> Dyadic
          • .to_matrix(ReferenceFrame) -> ImmutableMatrix(shape(3,1))
          • .free_dynamicsymbols(ReferenceFrame) -> set[Function]
          • .free_symbols(ReferenceFrame) -> set[Symbol]
      • dyadic.
        • class Dyadic
      • point.
        • class Point(name: str)
          • .locatenew(name: str, value: Vector) -> Point
          • .set_acc(ReferenceFrame, Vector) set acceleration
          • .set_pos(Point, Vector),

      .set_vel(ReferenceFrame, Vector)

      • vel(ReferenceFrame) -> Vector,

      acc(ReferenceFrame) -> Vector

      • functions.
        • dot(Vector, Vector) -> Expr,

      cross(Vector, Vector) -> Vector, outer(Vector, Vector) -> Dyadic

      • These are just wrappers.
      • express(Vector|Dyadic|sympyfiable, ReferenceFrame, ReferenceFrame?, variables) -> Vector|Dyadic|Expr
      • dynamicssymbols(names: str) -> *Symbol
        • Return a symbol that is a function of time t.
      • fieldfunctions.
        • divergence(Vector, ReferenceFrame) -> Expr
        • curl(Vector, ReferenceFrame) -> Vector
        • gradient(scalar_field: Expr, ReferenceFrame) -> Vector
        • scalar_potential(Vector, ReferenceFrame) -> Expr
        • is_conservative(Vector) -> bool,

      is_solenoidal(Vector) -> bool

      • mechanics.

7.30.1. Basic

  • Expression
    • simplify(Expr) -> Expr
      • trigsimp(Expr) -> Expr
      • powsimp(Expr) -> Expr
      • combsimp(Expr) -> Expr
    • expand(Expr) -> Expr
    • factor(Expr) -> Expr
    • collect(Expr, Symbol) -> Expr
    • cancel(Expr) -> Expr reduce the rational expression
  • Function
    • factorial(n)
    • binomial(n, k)
    • gamma(z)
  • Calculus

    • Differentiation
      • diff(Expr, Symbol) -> Expr differentiate
      • Derivative(Expr, Symbol, \[int | Symbol,\] Symbol, \[int | Symbol,\] ...) -> Expr

    unevaluated derivative

    • .doit() evaluate it
    • Integration
      • integrate(Expr, \{ Tuple[Symbol, Number, Number] | Symbol \}*) -> Expr
        • line_integrate(Expr, Curve, Iterable[Symbol]) -> Expr
          • Curve(tuple[Expr, Expr], tuple[Symbol, Number, Number])
        • vector_integrate()
      • Integral(Expr, \{ Tuple[Symbol, Number, Number] | Symbol \}*) -> Expr
    • limit(Expr, Symbol, Number)
  • Solve
    • solveset(Expr, Symbol, domain) -> Set
      • It is the wrapper for many solvers
    • linsolve
    • nonlinsolve
  • Linear Algebra
    • diag(...)
  • Expression Tree
    • srepr(Expr) -> str show the expression tree
  • Other
    • init_printing(use_unicode: bool)
    • pprint(Expr, **kwargs)
    • lambdify(Symbol, Expr, str) -> Callable[...]

7.30.2. Physics

  • sympy.physics.
    • mechanics
    • biomechanics
  • scdl
  • SoundCloud Download
  • Installed within ~/Music/scdl/.venv/
  • -l URL

7.31. Package Utilities

  • Package can import itself, since it is already installed.

7.31.1. Build

  • setuptools hatchling flit pdm are used to build the package.

7.31.2. Distribution

  • Built Distribution

    • It is self-contained. It only needs to be moved to certain

    directory.

    • wheel is a built binary package format.
  • Source Distribution
    • It needs to be compiled on the target system.

7.32. Compiler

7.32.2. Nuitka

8. Configurations

8.1. uv

Written in Rust Automatically manage virtual environments and packages.

  • uv init to make a uv environment
  • uv add PACKAGE, uv remove PACKAGE
  • uv run FILE.PY

9. REPL

  • Read Evaluate Print Loop

9.1. Help

  • help() to enter

10. Debugging

Add breakpoint() at a line that you want to break.

num = 23
# bunch of codes

breakpoint()

# bunch of codes

and enter the debug console.

(Pdb) print(num)
 42

11. Internal

11.1. Bytecode

11.2. Global Interpreter Lock

  • GIL
  • It is a feature of the interpreter that limits the interpreter to only operate on a single thread.
  • It is still applicable even when the threads package is used, limiting the computing power.
  • multiprocessor module make use of multiple interpreters. So it is not affected by GIL, but it has its own limitations.

12. IPython

12.1. System Command

  • !COMMAND it calls os.system()
  • Most of the tools are available.

12.2. History

  • _i _ii _iii previous three input
    • _i4 _ih[2:5] input history line 4, line 2-4
  • _ __ ___ previous three output
    • _oh ouput history
  • _dh directory history

12.3. Magic Function

  • The arguments are given only positionally.
  • %quickref show the quick reference
  • %timeit %%timeit
  • %%latex render a cell as a block of LaTeX

12.4. Help

  • obj? obj?? (?obj ??obj) get help or more help for object

13. Jupyter

13.1. nbconvert

  • --to (latex|pdf|markdown|html|...)

14. See Also

15. Reference

Footnotes:

Created: 2025-06-18 Wed 21:38