Python
Table of Contents
- 1. Type
- 2. Syntax
- 3. Function
- 4. Class
- 5. Import
- 6. Module
- 7. Packages
- 7.1.
functoolbuiltin - 7.2.
itertoolbuiltin - 7.3.
collectionsbuiltin - 7.4.
globbuiltin - 7.5.
subprocessbuiltin - 7.6.
osbuiltin - 7.7.
rebuiltin - 7.8.
typingbuiltin - 7.9.
threadingbuiltin - 7.10.
loggingbuiltin - 7.11.
inspectbuiltin - 7.12.
importlibbuiltin - 7.13.
csvbuiltin - 7.14.
picklebuiltin - 7.15.
randombuiltin - 7.16.
doctestandunittestbuiltin - 7.17.
returns - 7.18.
numpy - 7.19.
pyautogui - 7.20.
shutil - 7.21.
pydantic - 7.22. SQLAlchemy
- 7.23.
beautifulsoup - 7.24. Cookiecutter
- 7.25. PuLP
- 7.26. PyTorch
- 7.27. PyMuPDF
- 7.28.
tkinter - 7.29.
manim - 7.30.
sympy - 7.31. Package Utilities
- 7.32. Compiler
- 7.1.
- 8. Configurations
- 9. REPL
- 10. Debugging
- 11. Internal
- 12. IPython
- 13. Jupyter
- 14. See Also
- 15. Reference
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>.
- It calls the
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.sforstr,rforrepr,aforasciif"...{<object>}…"=
1.2.2. Format Specification Mini-Language
formatspec[[fill]align][sign]["z"]["#"]["0"][width][grouping_option]["." precision][type]- string — Common string operations — Python 3.13.5 documentation
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 theoldtext withnewtextcountstimes 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
- Shorthand for
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>)applystrto 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. Thestr()function is meant to return representations of values which are fairly human-readable, whilerepr()is meant to generate representations which can be read by the interpreter.1print(),str(),format()callstron the object. It
calls
__str__, when it is not defined, callsrepr.reprcalls__repr__, when it is not defined it returns the default representation.- A cell in
ipythonshell will return thereprof an object.
__getattr__(self, key)is called when there's no property of namekey.- e.g.
obj.some_key => obj.__getattr__("some_key") __getattribute__(self, key)is always called when accessing a
property and overrides others.
- e.g.
__format__(self, format_string) -> stris called onformat(<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:
- Try to import with finders in
sys.meta_pathone by one. If none succeed, the import error occurs. logseq.order-list-type:: number - Finder returns a loader of a module. logseq.order-list-type:: number
- 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 forthis package,parent package,grandparent package, … - Only
from ... import ...is possible.
6. Module
- Python module is a directory containing
__init__.pywhich 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/activateis the script that setup the virtual environment.
7. Packages
- Packages are stored in
/usr/lib/pythonN.NN/site-packages/
7.1. functool builtin
partialpartial 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
dequeclass- It supports
popleft,appendleft,extendleft
- It supports
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]) -> CompletedProcessrun the shell command
7.6. os builtin
remove(path)remove a file
7.7. re builtin
match(pattern: str, string: str) -> Matchcheck if the entire string exactly match the patternsearch(pattern: str, string: str) -> Matchlook for a substring that matches the patternfindall(pattern, string, flags=0) -> list[str]match all occurencesfinditer(pattern, string, flags=0) -> Iterable[Match]Match.expand(template: str) -> strperform 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
Protocolcreates inheritance-free interfaces.class Interface(Protocol): value: int def func(param: int) -> int: ...
7.9. threading builtin
Thread(target=..., [args=...])setup the thread, andthread.start()starts it.thread.join()is where the thread returns.
7.10. logging builtin
- Modern Python logging - YouTube
loggingis the root logger.logger = logging.getLogger()makes a child logger.loggercan showdebug,info,warn,error,exceptionorcritical
7.11. inspect builtin
- see source code.
7.12. importlib builtin
importcustomization
7.13. csv builtin
csv.writer- Instance of this(
_writer) will take the file and the table and
write it.
- Instance of this(
csv.reader- Instance of this(
_reader) is an iterable that gives out each
line.
- Instance of this(
7.14. pickle builtin
Object Serialization
7.15. random builtin
random()sample uniformly between 0 and 1uniform(a, b)uniform distributiongauss(mu=0, sigma=1)Gaussian distribution
choice(seq: Iterable)select random elementchoices(population: Iterable, weghts: Iterable|None, *, cum_weghts: Iterable|None, k: int)- select
kelements frompopulationallowing repetition. cum_weightsare the cumulative weights.
- select
shuffle(x)sample(population, k, *, counts=None)- select
kunique elements
- select
7.16. doctest and unittest builtin
Builtin Python functionality for testing.
Examplessection within the function docstring would run ondoctest.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
1on 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
BaseModulecan be anotherBaseModuleand the
JSON data is automatically propagated accordingly.
Field- It defines the details of a field within the
BaseModule
- It defines the details of a field within the
7.22. SQLAlchemy
SQL interface
7.23. beautifulsoup
HTML parser
7.24. Cookiecutter
Project Templates
7.25. PuLP
- It solves linear programs.
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 thedtype.
<tensor>.device -> <device>.<device> :device(type='cpu'|'cuda'|…)=<tensor>.to(<device>) -> <tensor>converts thedevice.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 thedim.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-1for the value to be automatically determined.
7.26.1.4. Operation
<tensor>.T: Transposetorch.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
FunctionhasFunction.grad_fnwhich 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.autogradkeeps 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
tkoriginally written intcl, the programming language. # pacman -S tkis required on Arch machine, although thetkinterpackage is installed.tkinter.Tkis 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
.getand.setmethod to change their value. - It is passed to the widget as a
textvariableparameter 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
commandis a blocking function. If the handling takes a long time, it needs to be threaded. Buttonhas threestate: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: Widgetsfiledialog: File selection dialogmessagebox: Info/Error dialog
7.28.5. togl
- it is a tk widget for OpenGL rendering.
- Python interactive help
modulesrequired the PyOpenGL has Togl installed.
7.29. manim
- Installed within
~/Video/alsciokat/.venv
7.29.1. Structure
7.29.1.1. Mobject
- Math Object Reference
- Module:
manim.mobject.
7.29.1.1.1. class mobject.Mobject
- PARAMETER
color: ParsableManimColor | list[ParsableManimColor]name: str | Nonedim: intz_index: float
- ATTRIBUTE
animateSee ((669ebee9-b376-4c59-a8da-95747098b2e5))submobjects: list[Mobject]points: numpy.ndarraydepth,width,height
- METHOD
add(*mobjects: Mobject)Add as a submobjectremove(*mobjects: Mobject)copy()get_...()set_...() -> selfmatch_...() -> selfalign_to(mobject_or_point: Mobject | Point3D, direction=array([0.,0.,0.]): Vector3D) -> self- align mobject to another mobject in certain direction.
move_toan Mobject or a point. Useful for centering thingsnext_toto_edgecenterarrangearrange_in_gridshift()scale()rotate()flip()add_updater(update_function: Updater, index=None: int | None, call_updater=False: bool) -> selfupdate_functionSee ((669f5743-827d-4b3f-8279-b9b924123a2e))indexthe index within theself.updatersthe function to be added. Added to the last ifNonecall_updaterwhether 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_colorfill_opacitystroke_colorstroke_opacitystroke_width
- METHOD
set_opacityset_colorset_fillset_points_smoothly(points)
7.29.1.1.3. Texts
- Module:
.text.
- Module:
tex_mobject. class SingleStringMathTex- Bases:
SVGMobject<- Bases:VMobject - PARAMETERS
tex_string: strstroke_width: floatfont_size=48: floattex_environment'align*': str=should_center=True: booltex_template=None: TexTemplate | Noneclass minim.utils.tex.TexTemplatespecifies preambles.
- Bases:
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: strmultiple tex mobject is created as submobjects.
- METHODS
get_part_by_tex(tex: str) -> MathTexindex_of_part(mobject?)index_of_part_by_tex(tex: str) -> MathTexset_color_by_tex(tex: str, color: ParsableManimColor)set_opacity_by_tex(tex: str, opacity: float)
- Bases:
class Tex- Bases:
MathTex
- Bases:
- Module:
.text_mobject - The text is rendered using ((669c64ae-993e-4b9a-b8d6-1ddcb3c2e62a))
class MarkupText- Bases:
SVGMobject - PARAMETER
text: straccept the markup textfont: strfont_size: floatgradient: tuplecolor: ParsableManimColorslant: boolfill_opacity: floatstroke_width: float
- Bases:
class Text- Bases:
SVGMobject - PARAMETER
- The Pango options are given in the form of parameters.
disable_ligature: boolt2w: 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
- Bases:
class Paragraph- Bases:
VGroup - PARAMETER
*text: strline_spacing-1: float=-1means autoalignment=None: 'left' | 'center' | 'right' | None
- ATTRIBUTE
chars: VGroup[VGroup[char]]Group of lines that are groups of characters.
- Bases:
7.29.1.1.4. Geometries
- Module:
.geometry. class arc.TipableVMobject- Bases:
VMobject - PARAMETERS
tip_length=0.35: floatnormal_vector=array([0., 0., 1.]): Vector3Dtip_style={}: dict
- METHODS
add_tip(tip=None)create_tip()get_tip()get_tips()has_tip()has_start_tip()pop_tips()get_start()get_end()
- Bases:
abstract class tips.ArrowTip- Bases:
VMobject - It is to be extended together with other =mobject=s
- ATTRIBUTES
base: Point3Dthe base of the tipcolorfill_colortip_angle: floattip_point: Point3Dvector: Vector3Dvector from the base to the tip point
- Bases:
ArrowTriangleTip,ArrowTriangleFilledTip- Bases:
ArrowTip,Triangle
- Bases:
StealthTip- Bases:
ArrowTip - ((669f099c-a556-402b-94c8-aa4a94f3cf1c)) arrow shape
- Bases:
class line.Line- Bases:
TipableVMobject - PARAMETERS
start=array([-1,0,0]): Vector3Dend=array([1,0,0]): Vector3D
- METHODS
generate_points(),init_points()- Empty method that is called upon creation, implemented by subclasses
get_projection(point: Point3D) -> Vector3Dget_angle(),get_slope(),get_unit_vector()set_angle(),set_length()put_start_and_end_on(start: Point3D, end: Point3D) -> self
- Bases:
class line.TangentLine- Bases:
Line - PARAMETERS
vmob: VMobjectalpha: floatvalue between 0 and 1 that represents the position within thevmoblength=1: floatd_alpha=1e-06: floatuncertainty inalpha?
- Bases:
class line.DashedLine- Bases:
Line - PARAMTERS
dashed_length=0.05: floatthe length of each dashdashed_ratio=0.5: floatthe ratio of dash space to empty space, ranging between 0 and 1
- Bases:
class shape_matchers.Underline- Bases:
Line - The underline mobject
- PARAMETERS
mobject: Mobjectbuff=0.1: float
- Bases:
class line.Vector- Bases:
Arrow - PARAMETER
direction: Point2D | Point3Dbuff: floatdistance of the vector form its endpoints.
- Bases:
7.29.1.1.5. Groups
class mobject.Group- Bases:
Mobject - Nothing more than mobjects bunched together into a single mobject,
- since a
Mobjectcan 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 anyMobject, orVGroup.
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] | Nonex_length=None: float | Noney_length=None: float | Nonedimension=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, useNoneto 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 andbounded_graphif specified) withcolorandopacity. IfcolorisIterablethen it becomes gradient.
- Get are under the
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.ndarrayplot(function: Callable[[float], float], x_range=None: Sequence[float] | None) -> ParametricFunction
- Bases:
class number_line.NumberLine- Bases:
Line - PARAMETERS
x_range=None: Sequence[float]|None[<min>, <max>, <step>]for the linelength=None: float|Noneunit_size=1: floatdistance between each tick. overwritten iflengthspecifiedinclude_ticks=True: booltick_size=0.1: floatnumbers_with_elongated_ticks=None: Iterable[float]|Nonelonger_tick_multiple=2: intthe scaling factor of the length of the longer tickrotation=0: floatangle of the linesinclude_tip=False: boolscaling=LinearBase: _ScaleBaseLogBaseis also possibleline_to_number_buff=0.25: floatnumbers_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 mobjectadd_numbers(x_values: Iterable[float])AddDecimalNumbermobjectadd_ticksnumber_to_point(number: float | ndarray) -> ndarray,n2p(number)point_to_number(point: Sequence[float]) -> float,p2n(point)
- Bases:
class coordinate_systems.Axes- Bases:
VGroup,CoordinateSystem - PARAMETER
axis_config=None: dict | None- The configuration of the number lines
axis_configit is passed down to theNumberlinex_axis_config,y_axis_configto control individually
tips=True: bool
- METHOD
coords_to_point(*coords: float | Sequence[float] | Sequence[Sequence[float]] | ndarray) -> np.ndarraypoints_to_coords(point: Sequence[float]) -> np.ndarray[float]get_axes() -> VGroup[Axis]
- Bases:
class coordinate_systems.NumberPlane- Bases
Axes - PARAMETER
background_line_style=None: dict[str, Any] | Nonefaded_line_stylefaded_line_ratio=1: int
- The axes are
LinefromAxes, and grid lines are its own.
- Bases
7.29.1.1.7. Vector Field
class VectorFieldclass 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: floatApply lags in between the animations of submobjects.rate_func: Callable[[float], float]Determine the rate at which the animation movesrate_functionsis predefined for this..linear
run_time: floatThe length of the animation in second.METHODS
This is not present for the
_AnimationBuilderwhich is the return of themobject.animateset_rate_func(rate_func) -> selfset_run_time(run_time) -> selfbegin()begin the animationfinish()finish the animationcopy() -> Animationcreate copyclass _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: floatrate_func: Callable
7.29.1.2.1. Updater
UpdaterNonTimeBasedUpdater: Callable[[Mobject], object]TimeBasedUpdater: Callable[[Mobject, float], object]
- They are stored within the
mobject.updaters, and they are called whenmobject.update()is called, which happens every frame by defualt. - In the case of
TimeBasedUpdaterthe second argumentdtis 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: Mobjecttarget_mobject: Mobjecttransform_mismatches=False: boolfade_transform_mismatches=False: bool
- Two mobjects match if their
tex_stringmatches.- 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_objectis checked whether there exists matchingtex_stringin themobject, and if a match is found, the transformation from the submobject of themobjectto that oftarget_mobjectis generated.
- Groups of mobjects can be transformed into one another, where groups can be created xplicitly or by the use of
- PARAMETER
class manim.animation.transform.ReplacementTransform- Bases:
Transform - PARAMETER
mobject: Mobjecttarget_mobject: Mobject
- Morph the
mobjectintotarget_mobject, while replacing thetarget_mobject.
- Bases:
class manim.animation.transform.FadeTransform- Bases:
Transform
- Bases:
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
durationseconds.
- No op, for
remove(*mobjects: Mobject
class section.Sectionself.next_section()- Call within the
constructmethod, starts a new section. Section will be removed if there's no animation. - The name of the section can be specified as the parameter.
- Call within the
- 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
- PARAMTERS
7.29.3. Utilities
7.29.3.1. Update Utilities
always(method: Callable, *args, **kwargs) -> Mobjectalways_redraw(func: Callable[[], Mobject]) -> MobjectRedraw the mobject at each framealways_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() -> floatincrement_value(d_value: float)set_value(value: float)interpolate(mobject1: Mobject, mobject2: Mobject, alpha: float, path_func)
- Bases:
class ComplexValueTracker- Bases:
ValueTracker
- Bases:
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--transparentUse transparent background and output in.movformat-p--previewShow preview on render completion--preview_command <program>Preview using<program>-q[l|m|h|p|k]--quality [l|m|h|p|k]lfor 854 × 480 15 FPS,mfor HD 30 FPS,hfor
FHD 60 FPS,
pfor QHD 60 FPS,kfor UHD 60 FPS-s--save_last_frameAs a PNG-
--save_sections- save sections under the
media/videos/<scene>/<quality>/sections/.
- save sections under the
-c?--background_color COLORSet the background to the one of the colors predefined.--flush_cacheRemove all partial movies in this directory.--disable_cachingDo not generate partial movies?
7.29.5. CLI
manimrenderUsed when nothing specifiedcfgwritewrite amanim.cfgfile within a terminal step by step
7.30. sympy
sympy.Package Structureabc.- This module contains the common variables:
a, b, x, y, z, t,
- This module contains the common variables:
which can also defined directly by
sympy.symbols("x y z": str) -> list[Symbol]core.symbol.class Symbol
numbers.class Integerclass 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.funcThe parent node.argstop-level argument
relational.class EqualityaliasEq.__init__(Expr, Expr)
matrices.class MutableDenseMatrixaliasMatrix.__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.coordsysrectclass CoordSys3D(name: str, transformation: Lambda, Tuple, str)- transformation includes
"spherical", … .x.y.zcoordinate variables.i.i.kunit vectors.create_new(name: str, transformation) -> CoordSys3D.locate_new(name: str, position: Vector) -> CoordSys3D.orient_new(name: str, orienters) -> CoordSys3D.base_vectors() -> tuple[Vector]
- transformation includes
.base_scalar() -> tuple[Expr]vectorclass 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
dyadicclass Dyadic
parametricregionclass ParametricRegion(definition: tuple[Expr*], *bounds: *tuple[Symbol, Number, Number]])
implicitregionclass ImplicitRegion(tuple[Symbol*], Expr)
express(Vector|Dyadic|sympyfiable, CoordSys3D, CoordSys3D?, bool) -> Vector|Dyadic|Exprcurl(Vector) -> Vectordivergence(Vector) -> Exprgradient(Expr) -> Vectoris_conservative(Vector) -> bool
integrals.integrals.class Integralclass 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.zbasis vectors.orient(ReferenceFrame, rot_type: str, amount: list[Symbol, Vector])rot_typecan be'Axis'to rotates the reference
- This vectors are different from the regular
frame by
Symbolamount arountVectoraxis.[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) -> Vectorfunctions.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|Exprdynamicssymbols(names: str) -> *Symbol- Return a symbol that is a function of time
t.
- Return a symbol that is a function of time
fieldfunctions.divergence(Vector, ReferenceFrame) -> Exprcurl(Vector, ReferenceFrame) -> Vectorgradient(scalar_field: Expr, ReferenceFrame) -> Vectorscalar_potential(Vector, ReferenceFrame) -> Expris_conservative(Vector) -> bool,
is_solenoidal(Vector) -> boolmechanics.
7.30.1. Basic
- Expression
simplify(Expr) -> Exprtrigsimp(Expr) -> Exprpowsimp(Expr) -> Exprcombsimp(Expr) -> Expr
expand(Expr) -> Exprfactor(Expr) -> Exprcollect(Expr, Symbol) -> Exprcancel(Expr) -> Exprreduce the rational expression
- Function
factorial(n)binomial(n, k)gamma(z)
Calculus
- Differentiation
diff(Expr, Symbol) -> ExprdifferentiateDerivative(Expr, Symbol, \[int | Symbol,\] Symbol, \[int | Symbol,\] ...) -> Expr
unevaluated derivative
.doit()evaluate it
- Integration
integrate(Expr, \{ Tuple[Symbol, Number, Number] | Symbol \}*) -> Exprline_integrate(Expr, Curve, Iterable[Symbol]) -> ExprCurve(tuple[Expr, Expr], tuple[Symbol, Number, Number])
vector_integrate()
Integral(Expr, \{ Tuple[Symbol, Number, Number] | Symbol \}*) -> Expr
limit(Expr, Symbol, Number)
- Differentiation
- Solve
solveset(Expr, Symbol, domain) -> Set- It is the wrapper for many solvers
linsolvenonlinsolve
- Linear Algebra
diag(...)
- Expression Tree
srepr(Expr) -> strshow the expression tree
- Other
init_printing(use_unicode: bool)pprint(Expr, **kwargs)lambdify(Symbol, Expr, str) -> Callable[...]
7.30.2. Physics
sympy.physics.mechanicsbiomechanics
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
setuptoolshatchlingflitpdmare used to build the package.
7.31.2. Distribution
Built Distribution
- It is self-contained. It only needs to be moved to certain
directory.
wheelis a built binary package format.
- Source Distribution
- It needs to be compiled on the target system.
7.32. Compiler
7.32.1. PyInstaller
7.32.2. Nuitka
8. Configurations
8.1. uv
Written in Rust Automatically manage virtual environments and packages.
uv initto make auvenvironmentuv add PACKAGE,uv remove PACKAGEuv 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
- THIS is Why List Comprehension is SO Efficient! - YouTube
- Python compiles the python code into bytecode, so that Python Virtual Machine(PVM) can execute it.
- Access the bytecode via
dis(disassemble) package.
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
threadspackage is used, limiting the computing power. multiprocessormodule make use of multiple interpreters. So it is not affected by GIL, but it has its own limitations.
12. IPython
12.1. System Command
!COMMANDit callsos.system()- Most of the tools are available.
12.2. History
_i_ii_iiiprevious three input_i4_ih[2:5]input history line4, line2-4
______previous three output_ohouput history
_dhdirectory history
12.3. Magic Function
- The arguments are given only positionally.
%quickrefshow the quick reference%timeit%%timeit%%latexrender 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. Kernels
ipykernelJupyter kernel based on IPython.python -m ipykernel install --user --name=<kernel name>oripython kernel install --user --name=<kernel name>to install the kernel to Jupyter environment.
13.2. nbconvert
--to (latex|pdf|markdown|html|...)