python notes (@pythonnotes) header
python notes (@pythonnotes) profile picture

python tips for myself

Toronto, Ontario
Joined November 2022
f-string is becoming a dominant way to format strings in Python thanks to its powerful and concise syntax. But do you know backslashes may not appear inside the curly braces {}. Here is an sample and explanation.
1
121
A key difference between three class builders of #Python “data class” is that collections.namedtuple and typing.NamedTuple build tuple subclasses, therefore the instances are immutable. By default, @ dataclass produces mutable classes.
1
126
Python uses data buffer to temporarily store data before it is sent to output device.
1
96
The class collections.deque is a thread-safe double-ended queue designed for fast inserting and removing from both ends.
70
When a #Python function is defined, the Python bytecode compiler determines how to fetch a variable that appears in it based on some variable lookup logic.
To specify keyword-only arguments when defining a function, name them after the argument prefixed with *. If you don’t want to support variable positional arguments but still want keyword-only arguments, put a * by itself in the signature. #Python #pythonprogramming
In #Python, first-class functions can be helpful for programming in a functional style, of which one hallmark is using higher-order functions, such as `map`, `filter`, `reduce`. But, in same cases, list comprehensions or generator expressions can be better choices.
Decorators are just syntactic sugar. - A decorator is a function or another callable. - A decorator may replace the decorated function with a different one. - Decorators are executed immediately when a module is loaded. #Python
Because dataclasses just use normal Python class creation so two instances of class ABC share the same class variable a, which might not be a desired behavior in a dataclass, so it raises a ValueError to avoid this.
1
When you set default value to field using a mutable object like list or dictionary, a ValueError will come out. Use default_factory instead. #Python
1
For a dataclass in #Python, the insertion order of inherited fields into the dataclass is the reverse of MRO, so if parent class has a default argument, child class cannot have non-default arguments.
1
MRO in #Python is a Method Resolution Order used in inheritance, which is the order a method is searched in a class hierarchy, from bottom to top and left to right.
1
Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.
1
1
In #Python, an object is hashable if its hash code doesn't change, such as numeric types and str are all hashable. A tuple is hashable only if all its items are hashable.