Browse Source

Numbers, Duck types, Bytes, Match statement

pull/135/merge
Jure Šorn 2 weeks ago
parent
commit
edb7680a98
2 changed files with 36 additions and 42 deletions
  1. 37
      README.md
  2. 41
      index.html

37
README.md

@ -320,7 +320,7 @@ String
<list> = <str>.split() # Splits on one or more whitespace characters.
<list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
<list> = <str>.splitlines(keepends=False) # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
<str> = <str>.join(<coll_of_strings>) # Joins elements using string as a separator.
<str> = <str>.join(<coll_of_strings>) # Joins elements by using string as a separator.
```
```python
@ -524,8 +524,7 @@ from math import log, log10, log2 # Log accepts base as second arg.
### Statistics
```python
from statistics import mean, median, mode # Mode returns the most common value.
from statistics import variance, stdev # Also: pvariance, pstdev, quantiles.
from statistics import mean, median, mode # Also: variance, stdev, quantiles.
```
### Random
@ -606,7 +605,7 @@ import zoneinfo, dateutil.tz
* **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) and microseconds (< 1M). Its str() method returns `'[±D, ]H:MM:SS[.…]'` and total_seconds() a float of all seconds.**
* **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.
<bytes> = <int>.to_bytes(n_bytes, …) # `byteorder='big/little', signed=False`.
@ -1970,7 +1967,7 @@ Bytes
### Decode
```python
<list> = list(<bytes>) # Returns ints in range from 0 to 255.
<list> = list(<bytes>) # Returns integers in range from 0 to 255.
<str> = str(<bytes>, 'utf-8') # Returns a string. Also <bytes>.decode().
<str> = <bytes>.hex() # Returns hex pairs. Accepts `sep=<str>`.
<int> = int.from_bytes(<bytes>, …) # `byteorder='big/little', signed=False`.
@ -2059,7 +2056,7 @@ Memory View
```python
<mview> = memoryview(<bytes/bytearray/array>) # Immutable if bytes is passed, else mutable.
<obj> = <mview>[index] # Returns int or float. Bytes if format is 'c'.
<obj> = <mview>[index] # Returns int/float. Bytes if format is 'c'.
<mview> = <mview>[<slice>] # Returns memoryview with rearranged elements.
<mview> = <mview>.cast('<typecode>') # Only works between B/b/c and other types.
<mview>.release() # Releases memory buffer of the base object.
@ -2126,7 +2123,7 @@ first_element = op.methodcaller('pop', 0)(<list>)
Match Statement
---------------
**Executes the first block with matching pattern. Added in Python 3.10.**
**Executes the first block with matching pattern.**
```python
match <object/expression>:
@ -2147,7 +2144,7 @@ match <object/expression>:
<mapping_patt> = {<value_pattern>: <patt>, ...} # Matches dictionary with matching items.
<class_pattern> = <type>(<attr_name>=<patt>, ...) # Matches object with matching attributes.
```
* **Sequence pattern can also be written as a tuple.**
* **Sequence pattern can also be written as a tuple, i.e. `'(<patt_1>, [...])'`.**
* **Use `'*<name>'` and `'**<name>'` in sequence/mapping patterns to bind remaining items.**
* **Sequence pattern must match all items of the collection, while mapping pattern does not.**
* **Patterns can be surrounded with brackets to override precedence (`'|'` > `'as'` > `','`).**

41
index.html

@ -56,7 +56,7 @@
<body>
<header>
<aside>May 16, 2025</aside>
<aside>May 21, 2025</aside>
<a href="https://gto76.github.io" rel="author">Jure Šorn</a>
</header>
@ -312,7 +312,7 @@ Point(x=<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>
<pre><code class="python language-python hljs">&lt;list&gt; = &lt;str&gt;.split() <span class="hljs-comment"># Splits on one or more whitespace characters.</span>
&lt;list&gt; = &lt;str&gt;.split(sep=<span class="hljs-keyword">None</span>, maxsplit=<span class="hljs-number">-1</span>) <span class="hljs-comment"># Splits on 'sep' str at most 'maxsplit' times.</span>
&lt;list&gt; = &lt;str&gt;.splitlines(keepends=<span class="hljs-keyword">False</span>) <span class="hljs-comment"># On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.</span>
&lt;str&gt; = &lt;str&gt;.join(&lt;coll_of_strings&gt;) <span class="hljs-comment"># Joins elements using string as a separator.</span>
&lt;str&gt; = &lt;str&gt;.join(&lt;coll_of_strings&gt;) <span class="hljs-comment"># Joins elements by using string as a separator.</span>
</code></pre>
<pre><code class="python language-python hljs">&lt;bool&gt; = &lt;sub_str&gt; <span class="hljs-keyword">in</span> &lt;str&gt; <span class="hljs-comment"># Checks if string contains the substring.</span>
&lt;bool&gt; = &lt;str&gt;.startswith(&lt;sub_str&gt;) <span class="hljs-comment"># Pass tuple of strings for multiple options.</span>
@ -480,8 +480,7 @@ Point(x=<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>
<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> log, log10, log2 <span class="hljs-comment"># Log accepts base as second arg.</span>
</code></pre></div>
<div><h3 id="statistics">Statistics</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> statistics <span class="hljs-keyword">import</span> mean, median, mode <span class="hljs-comment"># Mode returns the most common value.</span>
<span class="hljs-keyword">from</span> statistics <span class="hljs-keyword">import</span> variance, stdev <span class="hljs-comment"># Also: pvariance, pstdev, quantiles.</span>
<div><h3 id="statistics">Statistics</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> statistics <span class="hljs-keyword">import</span> mean, median, mode <span class="hljs-comment"># Also: variance, stdev, quantiles.</span>
</code></pre></div>
<div><h3 id="random">Random</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> random, randint, uniform <span class="hljs-comment"># Also: gauss, choice, shuffle, seed.</span>
@ -539,7 +538,7 @@ shuffle(&lt;list&gt;) <span class="hljs-comment">#
<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><code class="python hljs"><span class="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 (&lt; 86 400) and microseconds (&lt; 1M). Its str() method returns <code class="python hljs"><span class="hljs-string">'[±D, ]H:MM:SS[.…]'</span></code> and total_seconds() a float of all seconds.</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'&lt;D/DT&gt;.weekday()'</span></code> to get the day of the week as an int, with Monday being 0.</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'&lt;D/DT&gt;.weekday()'</span></code> to get the day of the week as an integer, with Monday being 0.</strong></li>
</ul>
<div><h3 id="now">Now</h3><pre><code class="python language-python hljs">&lt;D/DTn&gt; = D/DT.today() <span class="hljs-comment"># Current local date or naive DT. Also DT.now().</span>
&lt;DTa&gt; = DT.now(&lt;tzinfo&gt;) <span class="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
<span class="hljs-meta">&gt;&gt;&gt; </span>person.name
<span class="hljs-string">'Guido van Rossum'</span>
</code></pre>
<div><h3 id="slots">Slots</h3><p><strong>Mechanism that restricts objects to attributes listed in 'slots', reduces their memory footprint.</strong></p><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClassWithSlots</span>:</span>
<div><h3 id="slots">Slots</h3><p><strong>Mechanism that restricts objects to attributes listed in 'slots'.</strong></p><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClassWithSlots</span>:</span>
__slots__ = [<span class="hljs-string">'a'</span>]
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
self.a = <span class="hljs-number">1</span>
@ -932,8 +931,7 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str
</code></pre></div>
<div><h2 id="ducktypes"><a href="#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><h3 id="comparable">Comparable</h3><ul>
<li><strong>If eq() method is not overridden, it returns <code class="python hljs"><span class="hljs-string">'id(self) == id(other)'</span></code>, which is the same as <code class="python hljs"><span class="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 <code class="python hljs"><span class="hljs-string">'id(self) == id(other)'</span></code>, which is the same as <code class="python hljs"><span class="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>
</ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyComparable</span>:</span>
@ -949,9 +947,8 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str
<div><h3 id="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 <code class="python hljs"><span class="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 <code class="python hljs"><span class="hljs-string">'id(self)'</span></code> will not do. That is why Python automatically makes classes unhashable if you only implement eq().</strong></li>
</ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyHashable</span>:</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
self._a = a
@ -968,7 +965,7 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str
<div><h3 id="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 &lt;, &gt;, &lt;=, &gt;=) 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 <code class="python hljs"><span class="hljs-string">'key=locale.strxfrm'</span></code> to sorted() after running <code class="python hljs"><span class="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><h3 id="contextmanager">Context Manager</h3><ul>
<li><strong>With statements only work on objects that have enter() and exit() special methods.</strong></li>
<li><strong>Enter() should lock the resources and optionally return an object.</strong></li>
<li><strong>Exit() should release the resources.</strong></li>
<li><strong>Exit() should release the resources (for example close a file).</strong></li>
<li><strong>Any exception that happens inside the with block is passed to the exit() method.</strong></li>
<li><strong>The exit() method can suppress the exception by returning a true value.</strong></li>
</ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyOpen</span>:</span>
@ -1315,7 +1312,7 @@ pprint(&lt;collection&gt;, width=<span class="hljs-number">80</span>, depth=<spa
<ul>
<li><strong>Reads a line from the user input or pipe if present (trailing newline gets stripped).</strong></li>
<li><strong>If argument is passed, it gets printed to the standard output before input is read.</strong></li>
<li><strong>EOFError is raised if user hits EOF (ctrl-d/ctrl-z⏎) or if input stream is exhausted.</strong></li>
<li><strong>EOFError is raised if user hits EOF (ctrl-d/ctrl-z⏎) or if stream is already exhausted.</strong></li>
</ul>
<div><h2 id="commandlinearguments"><a href="#commandlinearguments" name="commandlinearguments">#</a>Command Line Arguments</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> sys
scripts_path = sys.argv[<span class="hljs-number">0</span>]
@ -1632,19 +1629,19 @@ CompletedProcess(args=[<span class="hljs-string">'bc'</span>, <span class="hljs-
┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
</code></pre>
<div><h2 id="bytes"><a href="#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><code class="python language-python hljs">&lt;bytes&gt; = <span class="hljs-string">b'&lt;str&gt;'</span> <span class="hljs-comment"># Only accepts ASCII characters and \x00-\xff.</span>
&lt;int&gt; = &lt;bytes&gt;[index] <span class="hljs-comment"># Returns an int in range from 0 to 255.</span>
&lt;int&gt; = &lt;bytes&gt;[index] <span class="hljs-comment"># Returns an integer in range from 0 to 255.</span>
&lt;bytes&gt; = &lt;bytes&gt;[&lt;slice&gt;] <span class="hljs-comment"># Returns bytes even if it has only one element.</span>
&lt;bytes&gt; = &lt;bytes&gt;.join(&lt;coll_of_bytes&gt;) <span class="hljs-comment"># Joins elements using bytes as a separator.</span>
&lt;bytes&gt; = &lt;bytes&gt;.join(&lt;coll_of_bytes&gt;) <span class="hljs-comment"># Joins elements by using bytes as a separator.</span>
</code></pre></div>
<div><h3 id="encode-1">Encode</h3><pre><code class="python language-python hljs">&lt;bytes&gt; = bytes(&lt;coll_of_ints&gt;) <span class="hljs-comment"># Ints must be in range from 0 to 255.</span>
<div><h3 id="encode-1">Encode</h3><pre><code class="python language-python hljs">&lt;bytes&gt; = bytes(&lt;coll_of_ints&gt;) <span class="hljs-comment"># Integers must be in range from 0 to 255.</span>
&lt;bytes&gt; = bytes(&lt;str&gt;, <span class="hljs-string">'utf-8'</span>) <span class="hljs-comment"># Encodes the string. Also &lt;str&gt;.encode().</span>
&lt;bytes&gt; = bytes.fromhex(<span class="hljs-string">'&lt;hex&gt;'</span>) <span class="hljs-comment"># Hex pairs can be separated by whitespaces.</span>
&lt;bytes&gt; = &lt;int&gt;.to_bytes(n_bytes, …) <span class="hljs-comment"># `byteorder='big/little', signed=False`.</span>
</code></pre></div>
<div><h3 id="decode-1">Decode</h3><pre><code class="python language-python hljs">&lt;list&gt; = list(&lt;bytes&gt;) <span class="hljs-comment"># Returns ints in range from 0 to 255.</span>
<div><h3 id="decode-1">Decode</h3><pre><code class="python language-python hljs">&lt;list&gt; = list(&lt;bytes&gt;) <span class="hljs-comment"># Returns integers in range from 0 to 255.</span>
&lt;str&gt; = str(&lt;bytes&gt;, <span class="hljs-string">'utf-8'</span>) <span class="hljs-comment"># Returns a string. Also &lt;bytes&gt;.decode().</span>
&lt;str&gt; = &lt;bytes&gt;.hex() <span class="hljs-comment"># Returns hex pairs. Accepts `sep=&lt;str&gt;`.</span>
&lt;int&gt; = int.from_bytes(&lt;bytes&gt;, …) <span class="hljs-comment"># `byteorder='big/little', signed=False`.</span>
@ -1713,7 +1710,7 @@ CompletedProcess(args=[<span class="hljs-string">'bc'</span>, <span class="hljs-
&lt;file&gt;.write(&lt;array&gt;) <span class="hljs-comment"># Writes array's memory to the binary file.</span>
</code></pre>
<div><h2 id="memoryview"><a href="#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><code class="python language-python hljs">&lt;mview&gt; = memoryview(&lt;bytes/bytearray/array&gt;) <span class="hljs-comment"># Immutable if bytes is passed, else mutable.</span>
&lt;obj&gt; = &lt;mview&gt;[index] <span class="hljs-comment"># Returns int or float. Bytes if format is 'c'.</span>
&lt;obj&gt; = &lt;mview&gt;[index] <span class="hljs-comment"># Returns int/float. Bytes if format is 'c'.</span>
&lt;mview&gt; = &lt;mview&gt;[&lt;slice&gt;] <span class="hljs-comment"># Returns memoryview with rearranged elements.</span>
&lt;mview&gt; = &lt;mview&gt;.cast(<span class="hljs-string">'&lt;typecode&gt;'</span>) <span class="hljs-comment"># Only works between B/b/c and other types.</span>
&lt;mview&gt;.release() <span class="hljs-comment"># Releases memory buffer of the base object.</span>
@ -1761,7 +1758,7 @@ first_element = op.methodcaller(<span class="hljs-string">'pop'</span>, <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: <code class="python hljs"><span class="hljs-string">'x &lt; y &lt; z'</span></code> gets converted to <code class="python hljs"><span class="hljs-string">'(x &lt; y) and (y &lt; z)</span></code>'.</strong></li>
</ul>
<div><h2 id="matchstatement"><a href="#matchstatement" name="matchstatement">#</a>Match Statement</h2><p><strong>Executes the first block with matching pattern. Added in Python 3.10.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">match</span> &lt;object/expression&gt;:
<div><h2 id="matchstatement"><a href="#matchstatement" name="matchstatement">#</a>Match Statement</h2><p><strong>Executes the first block with matching pattern.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">match</span> &lt;object/expression&gt;:
<span class="hljs-keyword">case</span> &lt;pattern&gt; [<span class="hljs-keyword">if</span> &lt;condition&gt;]:
&lt;code&gt;
...
@ -1780,7 +1777,7 @@ first_element = op.methodcaller(<span class="hljs-string">'pop'</span>, <span
</code></pre></div>
<ul>
<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. <code class="python hljs"><span class="hljs-string">'(&lt;patt_1&gt;, [...])'</span></code>.</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'*&lt;name&gt;'</span></code> and <code class="python hljs"><span class="hljs-string">'**&lt;name&gt;'</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 (<code class="python hljs"><span class="hljs-string">'|'</span></code> &gt; <code class="python hljs"><span class="hljs-string">'as'</span></code> &gt; <code class="python hljs"><span class="hljs-string">','</span></code>).</strong></li>
@ -2945,7 +2942,7 @@ $ deactivate <span class="hljs-comment"># Deactivates the active
<footer>
<aside>May 16, 2025</aside>
<aside>May 21, 2025</aside>
<a href="https://gto76.github.io" rel="author">Jure Šorn</a>
</footer>

Loading…
Cancel
Save