* **Times and datetimes that have defined timezone are called aware and ones that don't, naive. If object is naive, it is presumed to be in the system's timezone!**
* **`'fold=1'` means the second pass in case of time jumping back for one hour.**
* **Timedelta normalizes arguments to ±days, seconds (<86400)andmicroseconds(<1M).Itsstr()methodreturns`'[±D, ]H:MM:SS[.…]'`andtotal_seconds()afloatofallseconds.**
* **Use `'<D/DT>.weekday()'` to get the day of the week as an int, with Monday being 0.**
* **Use `'<D/DT>.weekday()'` to get the day of the week as an integer, with Monday being 0.**
### Now
```python
@ -1076,7 +1075,7 @@ class Person:
```
### Slots
**Mechanism that restricts objects to attributes listed in 'slots', reduces their memory footprint.**
**Mechanism that restricts objects to attributes listed in 'slots'.**
```python
class MyClassWithSlots:
@ -1097,8 +1096,7 @@ Duck Types
**A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type.**
### Comparable
* **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.**
* **That means all user-defined objects compare not equal by default.**
* **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`. That means all user-defined objects compare not equal by default, because id() returns object's unique identification number (its memory address).**
* **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. False is returned if both return NotImplemented.**
* **Ne() automatically works on any object that has eq() defined.**
@ -1113,9 +1111,8 @@ class MyComparable:
```
### Hashable
* **Hashable object needs both hash() and eq() methods and its hash value should never change.**
* **Hashable objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do.**
* **That is why Python automatically makes classes unhashable if you only implement eq().**
* **Hashable object needs both hash() and eq() methods and its hash value must not change.**
* **Hashable objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do. That is why Python automatically makes classes unhashable if you only implement eq().**
```python
class MyHashable:
@ -1133,7 +1130,7 @@ class MyHashable:
```
### Sortable
* **With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods and the rest will be automatically generated.**
* **With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods (used by <, >, <=, >=) and the rest will be automatically generated.**
* **Functions sorted() and min() only require lt() method, while max() only requires gt(). However, it is best to define them all so that confusion doesn't arise in other contexts.**
* **When two lists, strings or dataclasses are compared, their values get compared in order until a pair of unequal values is found. The comparison of this two values is then returned. The shorter sequence is considered smaller in case of all values being equal.**
* **To sort collection of strings in proper alphabetical order pass `'key=locale.strxfrm'` to sorted() after running `'locale.setlocale(locale.LC_COLLATE, "en_US.UTF-8")'`.**
@ -1205,7 +1202,7 @@ class Counter:
### Context Manager
* **With statements only work on objects that have enter() and exit() special methods.**
* **Enter() should lock the resources and optionally return an object.**
* **Exit() should release the resources.**
* **Exit() should release the resources (for example close a file).**
* **Any exception that happens inside the with block is passed to the exit() method.**
* **The exit() method can suppress the exception by returning a true value.**
```python
@ -1530,7 +1527,7 @@ Input
```
* **Reads a line from the user input or pipe if present (trailing newline gets stripped).**
* **If argument is passed, it gets printed to the standard output before input is read.**
* **EOFError is raised if user hits EOF (ctrl-d/ctrl-z⏎) or if input stream is exhausted.**
* **EOFError is raised if user hits EOF (ctrl-d/ctrl-z⏎) or if stream is already exhausted.**
Command Line Arguments
@ -1955,14 +1952,14 @@ Bytes
```python
<bytes> = b'<str>' # Only accepts ASCII characters and \x00-\xff.
<int> = <bytes>[index] # Returns an int in range from 0 to 255.
<int> = <bytes>[index] # Returns an integer in range from 0 to 255.
<bytes> = <bytes>[<slice>] # Returns bytes even if it has only one element.
<bytes> = <bytes>.join(<coll_of_bytes>) # Joins elements using bytes as a separator.
<bytes> = <bytes>.join(<coll_of_bytes>) # Joins elements by using bytes as a separator.
```
### Encode
```python
<bytes> = bytes(<coll_of_ints>) # Ints must be in range from 0 to 255.
<bytes> = bytes(<coll_of_ints>) # Integers must be in range from 0 to 255.
<bytes> = bytes(<str>, 'utf-8') # Encodes the string. Also <str>.encode().
<bytes> = bytes.fromhex('<hex>') # Hex pairs can be separated by whitespaces.
<pre><codeclass="python language-python hljs"><list> = <str>.split() <spanclass="hljs-comment"># Splits on one or more whitespace characters.</span>
<list> = <str>.split(sep=<spanclass="hljs-keyword">None</span>, maxsplit=<spanclass="hljs-number">-1</span>) <spanclass="hljs-comment"># Splits on 'sep' str at most 'maxsplit' times.</span>
<list> = <str>.splitlines(keepends=<spanclass="hljs-keyword">False</span>) <spanclass="hljs-comment"># On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.</span>
<str> = <str>.join(<coll_of_strings>) <spanclass="hljs-comment"># Joins elements using string as a separator.</span>
<str> = <str>.join(<coll_of_strings>) <spanclass="hljs-comment"># Joins elements by using string as a separator.</span>
</code></pre>
<pre><codeclass="python language-python hljs"><bool> = <sub_str><spanclass="hljs-keyword">in</span><str><spanclass="hljs-comment"># Checks if string contains the substring.</span>
<bool> = <str>.startswith(<sub_str>) <spanclass="hljs-comment"># Pass tuple of strings for multiple options.</span>
<spanclass="hljs-keyword">from</span> math <spanclass="hljs-keyword">import</span> log, log10, log2 <spanclass="hljs-comment"># Log accepts base as second arg.</span>
</code></pre></div>
<div><h3id="statistics">Statistics</h3><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> statistics <spanclass="hljs-keyword">import</span> mean, median, mode <spanclass="hljs-comment"># Mode returns the most common value.</span>
<li><strong>Times and datetimes that have defined timezone are called aware and ones that don't, naive. If object is naive, it is presumed to be in the system's timezone!</strong></li>
<li><strong><codeclass="python hljs"><spanclass="hljs-string">'fold=1'</span></code> means the second pass in case of time jumping back for one hour.</strong></li>
<li><strong>Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M). Its str() method returns <codeclass="python hljs"><spanclass="hljs-string">'[±D, ]H:MM:SS[.…]'</span></code> and total_seconds() a float of all seconds.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'<D/DT>.weekday()'</span></code> to get the day of the week as an int, with Monday being 0.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'<D/DT>.weekday()'</span></code> to get the day of the week as an integer, with Monday being 0.</strong></li>
</ul>
<div><h3id="now">Now</h3><pre><codeclass="python language-python hljs"><D/DTn> = D/DT.today() <spanclass="hljs-comment"># Current local date or naive DT. Also DT.now().</span>
<DTa> = DT.now(<tzinfo>) <spanclass="hljs-comment"># Aware DT from current time in passed timezone.</span>
@ -920,7 +919,7 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str
<spanclass="hljs-string">'Guido van Rossum'</span>
</code></pre>
<div><h3id="slots">Slots</h3><p><strong>Mechanism that restricts objects to attributes listed in 'slots', reduces their memory footprint.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-class"><spanclass="hljs-keyword">class</span><spanclass="hljs-title">MyClassWithSlots</span>:</span>
<div><h3id="slots">Slots</h3><p><strong>Mechanism that restricts objects to attributes listed in 'slots'.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-class"><spanclass="hljs-keyword">class</span><spanclass="hljs-title">MyClassWithSlots</span>:</span>
@ -932,8 +931,7 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str
</code></pre></div>
<div><h2id="ducktypes"><ahref="#ducktypes"name="ducktypes">#</a>Duck Types</h2><p><strong>A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type.</strong></p><div><h3id="comparable">Comparable</h3><ul>
<li><strong>If eq() method is not overridden, it returns <codeclass="python hljs"><spanclass="hljs-string">'id(self) == id(other)'</span></code>, which is the same as <codeclass="python hljs"><spanclass="hljs-string">'self is other'</span></code>.</strong></li>
<li><strong>That means all user-defined objects compare not equal by default.</strong></li>
<li><strong>If eq() method is not overridden, it returns <codeclass="python hljs"><spanclass="hljs-string">'id(self) == id(other)'</span></code>, which is the same as <codeclass="python hljs"><spanclass="hljs-string">'self is other'</span></code>. That means all user-defined objects compare not equal by default, because id() returns object's unique identification number (its memory address).</strong></li>
<li><strong>Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. False is returned if both return NotImplemented.</strong></li>
<li><strong>Ne() automatically works on any object that has eq() defined.</strong></li>
@ -949,9 +947,8 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str
<div><h3id="hashable">Hashable</h3><ul>
<li><strong>Hashable object needs both hash() and eq() methods and its hash value should never change.</strong></li>
<li><strong>Hashable objects that compare equal must have the same hash value, meaning default hash() that returns <codeclass="python hljs"><spanclass="hljs-string">'id(self)'</span></code> will not do.</strong></li>
<li><strong>That is why Python automatically makes classes unhashable if you only implement eq().</strong></li>
<li><strong>Hashable object needs both hash() and eq() methods and its hash value must not change.</strong></li>
<li><strong>Hashable objects that compare equal must have the same hash value, meaning default hash() that returns <codeclass="python hljs"><spanclass="hljs-string">'id(self)'</span></code> will not do. That is why Python automatically makes classes unhashable if you only implement eq().</strong></li>
@ -968,7 +965,7 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str
<div><h3id="sortable">Sortable</h3><ul>
<li><strong>With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods and the rest will be automatically generated.</strong></li>
<li><strong>With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods (used by <, >, <=, >=) and the rest will be automatically generated.</strong></li>
<li><strong>Functions sorted() and min() only require lt() method, while max() only requires gt(). However, it is best to define them all so that confusion doesn't arise in other contexts.</strong></li>
<li><strong>When two lists, strings or dataclasses are compared, their values get compared in order until a pair of unequal values is found. The comparison of this two values is then returned. The shorter sequence is considered smaller in case of all values being equal.</strong></li>
<li><strong>To sort collection of strings in proper alphabetical order pass <codeclass="python hljs"><spanclass="hljs-string">'key=locale.strxfrm'</span></code> to sorted() after running <codeclass="python hljs"><spanclass="hljs-string">'locale.setlocale(locale.LC_COLLATE, "en_US.UTF-8")'</span></code>.</strong></li>
@ -1036,7 +1033,7 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str
<div><h2id="bytes"><ahref="#bytes"name="bytes">#</a>Bytes</h2><p><strong>A bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.</strong></p><pre><codeclass="python language-python hljs"><bytes> = <spanclass="hljs-string">b'<str>'</span><spanclass="hljs-comment"># Only accepts ASCII characters and \x00-\xff.</span>
<int> = <bytes>[index] <spanclass="hljs-comment"># Returns an int in range from 0 to 255.</span>
<int> = <bytes>[index] <spanclass="hljs-comment"># Returns an integer in range from 0 to 255.</span>
<bytes> = <bytes>[<slice>] <spanclass="hljs-comment"># Returns bytes even if it has only one element.</span>
<bytes> = <bytes>.join(<coll_of_bytes>) <spanclass="hljs-comment"># Joins elements using bytes as a separator.</span>
<bytes> = <bytes>.join(<coll_of_bytes>) <spanclass="hljs-comment"># Joins elements by using bytes as a separator.</span>
</code></pre></div>
<div><h3id="encode-1">Encode</h3><pre><codeclass="python language-python hljs"><bytes> = bytes(<coll_of_ints>) <spanclass="hljs-comment"># Ints must be in range from 0 to 255.</span>
<div><h3id="encode-1">Encode</h3><pre><codeclass="python language-python hljs"><bytes> = bytes(<coll_of_ints>) <spanclass="hljs-comment"># Integers must be in range from 0 to 255.</span>
<bytes> = bytes(<str>, <spanclass="hljs-string">'utf-8'</span>) <spanclass="hljs-comment"># Encodes the string. Also <str>.encode().</span>
<bytes> = bytes.fromhex(<spanclass="hljs-string">'<hex>'</span>) <spanclass="hljs-comment"># Hex pairs can be separated by whitespaces.</span>
<div><h3id="decode-1">Decode</h3><pre><codeclass="python language-python hljs"><list> = list(<bytes>) <spanclass="hljs-comment"># Returns ints in range from 0 to 255.</span>
<div><h3id="decode-1">Decode</h3><pre><codeclass="python language-python hljs"><list> = list(<bytes>) <spanclass="hljs-comment"># Returns integers in range from 0 to 255.</span>
<str> = str(<bytes>, <spanclass="hljs-string">'utf-8'</span>) <spanclass="hljs-comment"># Returns a string. Also <bytes>.decode().</span>
<file>.write(<array>) <spanclass="hljs-comment"># Writes array's memory to the binary file.</span>
</code></pre>
<div><h2id="memoryview"><ahref="#memoryview"name="memoryview">#</a>Memory View</h2><p><strong>A sequence object that points to the memory of another bytes-like object. Each element can reference a single or multiple consecutive bytes, depending on format. Order and number of elements can be changed with slicing.</strong></p><pre><codeclass="python language-python hljs"><mview> = memoryview(<bytes/bytearray/array>) <spanclass="hljs-comment"># Immutable if bytes is passed, else mutable.</span>
<obj> = <mview>[index] <spanclass="hljs-comment"># Returns int or float. Bytes if format is 'c'.</span>
<obj> = <mview>[index] <spanclass="hljs-comment"># Returns int/float. Bytes if format is 'c'.</span>
<mview> = <mview>[<slice>] <spanclass="hljs-comment"># Returns memoryview with rearranged elements.</span>
<mview> = <mview>.cast(<spanclass="hljs-string">'<typecode>'</span>) <spanclass="hljs-comment"># Only works between B/b/c and other types.</span>
<mview>.release() <spanclass="hljs-comment"># Releases memory buffer of the base object.</span>
<li><strong>Most operators call the object's special method that is named after them (second object is passed as an argument), while logical operators call their own code that relies on bool().</strong></li>
<li><strong>Comparisons can be chained: <codeclass="python hljs"><spanclass="hljs-string">'x < y < z'</span></code> gets converted to <codeclass="python hljs"><spanclass="hljs-string">'(x < y) and (y < z)</span></code>'.</strong></li>
</ul>
<div><h2id="matchstatement"><ahref="#matchstatement"name="matchstatement">#</a>Match Statement</h2><p><strong>Executes the first block with matching pattern. Added in Python 3.10.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">match</span><object/expression>:
<div><h2id="matchstatement"><ahref="#matchstatement"name="matchstatement">#</a>Match Statement</h2><p><strong>Executes the first block with matching pattern.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">match</span><object/expression>:
<li><strong>Sequence pattern can also be written as a tuple.</strong></li>
<li><strong>Sequence pattern can also be written as a tuple, i.e. <codeclass="python hljs"><spanclass="hljs-string">'(<patt_1>, [...])'</span></code>.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'*<name>'</span></code> and <codeclass="python hljs"><spanclass="hljs-string">'**<name>'</span></code> in sequence/mapping patterns to bind remaining items.</strong></li>
<li><strong>Sequence pattern must match all items of the collection, while mapping pattern does not.</strong></li>
<li><strong>Patterns can be surrounded with brackets to override precedence (<codeclass="python hljs"><spanclass="hljs-string">'|'</span></code>><codeclass="python hljs"><spanclass="hljs-string">'as'</span></code>><codeclass="python hljs"><spanclass="hljs-string">','</span></code>).</strong></li>
@ -2945,7 +2942,7 @@ $ deactivate <span class="hljs-comment"># Deactivates the active