Browse Source

Class, Duck types, Paths, CSV, Deque

pull/116/merge
Jure Šorn 2 months ago
parent
commit
87dbc203f3
3 changed files with 23 additions and 24 deletions
  1. 20
      README.md
  2. 24
      index.html
  3. 3
      pdf/remove_links.py

20
README.md

@ -971,7 +971,7 @@ class MyClass:
>>> obj.a, str(obj), repr(obj)
(1, '1', 'MyClass(1)')
```
* **Methods whose names start and end with two underscores are called special methods. They are executed when object is passed to a built-in function or used as an operand, for example, `'print(a)'` calls `'a.__str__()'` and `'a + b'` calls `'a.__add__(b)'`.**
* **Methods whose names start and end with two underscores are called special methods. They are executed when object is passed to a built-in function or used as an operand,<br>for example, `'print(a)'` calls `'a.__str__()'` and `'a + b'` calls `'a.__add__(b)'`.**
* **Methods decorated with `'@staticmethod'` receive neither 'self' nor 'cls' argument.**
* **Return value of str() special method should be readable and of repr() unambiguous. If only repr() is defined, it will also be used for str().**
@ -1042,7 +1042,7 @@ class <class_name>:
```
* **Objects can be made [sortable](#sortable) with `'order=True'` and immutable with `'frozen=True'`.**
* **For object to be [hashable](#hashable), all attributes must be hashable and 'frozen' must be True.**
* **Function field() is needed because `'<attr_name>: list = []'` would make a list that is shared among all instances. Its 'default_factory' argument can be any [callable](#callable).**
* **Function field() is needed because `'<attr_name>: list = []'` would make a list that is shared among all instances. Its 'default_factory' argument accepts any callable object.**
* **For attributes of arbitrary type use `'typing.Any'`.**
```python
@ -1094,7 +1094,7 @@ Duck Types
### 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 (because id() returns object's memory address that is guaranteed to be unique).**
* **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.**
* **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. Result is False if both return NotImplemented.**
* **Ne() automatically works on any object that has eq() defined.**
```python
@ -1172,7 +1172,7 @@ class Counter:
```
#### Python has many different iterator objects:
* **Sequence iterators returned by the [iter()](#iterator) function, such as list\_iterator and set\_iterator.**
* **Sequence iterators returned by the [iter()](#iterator) function, such as list\_iterator, etc.**
* **Objects returned by the [itertools](#itertools) module, such as count, repeat and cycle.**
* **Generators returned by the [generator functions](#generator) and [generator expressions](#comprehensions).**
* **File objects returned by the [open()](#open) function, etc.**
@ -1407,7 +1407,7 @@ except (<exception>, [...]) as <name>: ...
```
* **Also catches subclasses, e.g. `'IndexError'` is caught by `'except LookupError:'`.**
* **Use `'traceback.print_exc()'` to print the full error message to standard error stream.**
* **Use `'print(<name>)'` to print just the cause of the exception (i.e. its arguments).**
* **Use `'print(<name>)'` to print just the cause of the exception (that is, its arguments).**
* **Use `'logging.exception(<str>)'` to log the passed message, followed by the full error message of the caught exception. For details about setting up the logger see [Logging](#logging).**
* **Use `'sys.exc_info()'` to get exception type, object, and traceback of caught exception.**
@ -1549,7 +1549,7 @@ args = p.parse_args() # Exits on par
* **Use `'help=<str>'` to set argument description that will be displayed in help message.**
* **Use `'default=<obj>'` to override None as option's or optional argument's default value.**
* **Use `'type=FileType(<mode>)'` for files. Accepts 'encoding', but 'newline' is None.**
* **Use `'type=FileType(<mode>)'` for files. It accepts 'encoding', but 'newline' is None.**
Open
@ -1657,7 +1657,7 @@ from pathlib import Path
```python
<iter> = os.scandir(path='.') # Returns DirEntry objects located at the path.
<str> = <DirEntry>.path # Returns object's path (relative by default).
<str> = <DirEntry>.path # Is absolute if 'path' argument was absolute.
<str> = <DirEntry>.name # Returns path's final component as a string.
<file> = open(<DirEntry>) # Opens the file and returns its file object.
```
@ -1836,7 +1836,7 @@ import csv
* **`'lineterminator'` - How writer terminates rows. Reader looks for '\n', '\r' and '\r\n'.**
* **`'quotechar'` - Character for quoting fields containing delimiters, quotechars, '\n' or '\r'.**
* **`'escapechar'` - Character for escaping quotechars (not needed if doublequote is True).**
* **`'doublequote'` - Whether quotechars inside fields are (or get) doubled or escaped.**
* **`'doublequote'` - Whether quotechars inside fields are/get doubled instead of escaped.**
* **`'quoting'` - 0: As necessary, 1: All, 2: All but numbers which are read as floats, 3: None.**
* **`'skipinitialspace'` - Is space character at the start of the field stripped by the reader.**
@ -2028,7 +2028,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03'
Array
-----
**List that can only hold numbers of a predefined C type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be reversed with byteswap() method.**
**List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be reversed with byteswap() method.**
```python
from array import array
@ -2084,7 +2084,7 @@ from collections import deque
```python
<deque> = deque(<collection>) # Use `maxlen=<int>` to set size limit.
<deque>.appendleft(<el>) # Opposite element is dropped if full.
<deque>.extendleft(<collection>) # Appends elements in reversed order.
<deque>.extendleft(<collection>) # Prepends reversed coll. to the deque.
<deque>.rotate(n=1) # Last element becomes the first one.
<el> = <deque>.popleft() # Raises IndexError if deque is empty.
```

24
index.html

@ -56,7 +56,7 @@
<body>
<header>
<aside>July 29, 2025</aside>
<aside>July 30, 2025</aside>
<a href="https://gto76.github.io" rel="author">Jure Šorn</a>
</header>
@ -827,7 +827,7 @@ player = Player(point, direction) <span class="hljs-comment">#
(<span class="hljs-number">1</span>, <span class="hljs-string">'1'</span>, <span class="hljs-string">'MyClass(1)'</span>)
</code></pre>
<ul>
<li><strong>Methods whose names start and end with two underscores are called special methods. They are executed when object is passed to a built-in function or used as an operand, for example, <code class="python hljs"><span class="hljs-string">'print(a)'</span></code> calls <code class="python hljs"><span class="hljs-string">'a.__str__()'</span></code> and <code class="python hljs"><span class="hljs-string">'a + b'</span></code> calls <code class="python hljs"><span class="hljs-string">'a.__add__(b)'</span></code>.</strong></li>
<li><strong>Methods whose names start and end with two underscores are called special methods. They are executed when object is passed to a built-in function or used as an operand,<br>for example, <code class="python hljs"><span class="hljs-string">'print(a)'</span></code> calls <code class="python hljs"><span class="hljs-string">'a.__str__()'</span></code> and <code class="python hljs"><span class="hljs-string">'a + b'</span></code> calls <code class="python hljs"><span class="hljs-string">'a.__add__(b)'</span></code>.</strong></li>
<li><strong>Methods decorated with <code class="python hljs"><span class="hljs-string">'@staticmethod'</span></code> receive neither 'self' nor 'cls' argument.</strong></li>
<li><strong>Return value of str() special method should be readable and of repr() unambiguous. If only repr() is defined, it will also be used for str().</strong></li>
</ul>
@ -891,7 +891,7 @@ Z = make_dataclass(<span class="hljs-string">'Z'</span>, [<span class="hljs-stri
<ul>
<li><strong>Objects can be made <a href="#sortable">sortable</a> with <code class="python hljs"><span class="hljs-string">'order=True'</span></code> and immutable with <code class="python hljs"><span class="hljs-string">'frozen=True'</span></code>.</strong></li>
<li><strong>For object to be <a href="#hashable">hashable</a>, all attributes must be hashable and 'frozen' must be True.</strong></li>
<li><strong>Function field() is needed because <code class="python hljs"><span class="hljs-string">'&lt;attr_name&gt;: list = []'</span></code> would make a list that is shared among all instances. Its 'default_factory' argument can be any <a href="#callable">callable</a>.</strong></li>
<li><strong>Function field() is needed because <code class="python hljs"><span class="hljs-string">'&lt;attr_name&gt;: list = []'</span></code> would make a list that is shared among all instances. Its 'default_factory' argument accepts any callable object.</strong></li>
<li><strong>For attributes of arbitrary type use <code class="python hljs"><span class="hljs-string">'typing.Any'</span></code>.</strong></li>
</ul>
<pre><code class="python language-python hljs">P = make_dataclass(<span class="hljs-string">'P'</span>, [<span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>])
@ -927,7 +927,7 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str
<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>. That means all user-defined objects compare not equal by default (because id() returns object's memory address that is guaranteed to be unique).</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>Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. Result is False 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>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
@ -1002,7 +1002,7 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str
(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
</code></pre>
<div><h4 id="pythonhasmanydifferentiteratorobjects">Python has many different iterator objects:</h4><ul>
<li><strong>Sequence iterators returned by the <a href="#iterator">iter()</a> function, such as list_iterator and set_iterator.</strong></li>
<li><strong>Sequence iterators returned by the <a href="#iterator">iter()</a> function, such as list_iterator, etc.</strong></li>
<li><strong>Objects returned by the <a href="#itertools">itertools</a> module, such as count, repeat and cycle.</strong></li>
<li><strong>Generators returned by the <a href="#generator">generator functions</a> and <a href="#comprehensions">generator expressions</a>.</strong></li>
<li><strong>File objects returned by the <a href="#open">open()</a> function, etc.</strong></li>
@ -1212,7 +1212,7 @@ LogicOp = Enum(<span class="hljs-string">'LogicOp'</span>, {<span class="hljs-st
<ul>
<li><strong>Also catches subclasses, e.g. <code class="python hljs"><span class="hljs-string">'IndexError'</span></code> is caught by <code class="python hljs"><span class="hljs-string">'except LookupError:'</span></code>.</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'traceback.print_exc()'</span></code> to print the full error message to standard error stream.</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'print(&lt;name&gt;)'</span></code> to print just the cause of the exception (i.e. its arguments).</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'print(&lt;name&gt;)'</span></code> to print just the cause of the exception (that is, its arguments).</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'logging.exception(&lt;str&gt;)'</span></code> to log the passed message, followed by the full error message of the caught exception. For details about setting up the logger see <a href="#logging">Logging</a>.</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'sys.exc_info()'</span></code> to get exception type, object, and traceback of caught exception.</strong></li>
</ul>
@ -1327,7 +1327,7 @@ args = p.parse_args() <span class="h
<ul>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'help=&lt;str&gt;'</span></code> to set argument description that will be displayed in help message.</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'default=&lt;obj&gt;'</span></code> to override None as option's or optional argument's default value.</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'type=FileType(&lt;mode&gt;)'</span></code> for files. Accepts 'encoding', but 'newline' is None.</strong></li>
<li><strong>Use <code class="python hljs"><span class="hljs-string">'type=FileType(&lt;mode&gt;)'</span></code> for files. It accepts 'encoding', but 'newline' is None.</strong></li>
</ul>
<div><h2 id="open"><a href="#open" name="open">#</a>Open</h2><p><strong>Opens a file and returns the corresponding file object.</strong></p><pre><code class="python language-python hljs">&lt;file&gt; = open(&lt;path&gt;, mode=<span class="hljs-string">'r'</span>, encoding=<span class="hljs-keyword">None</span>, newline=<span class="hljs-keyword">None</span>)
</code></pre></div>
@ -1408,7 +1408,7 @@ args = p.parse_args() <span class="h
&lt;num&gt; = &lt;stat&gt;.st_mtime/st_size/… <span class="hljs-comment"># Returns modification time, size in bytes, etc.</span>
</code></pre>
<div><h3 id="direntry">DirEntry</h3><p><strong>Unlike listdir(), scandir() returns DirEntry objects that cache isfile, isdir, and on Windows also stat information, thus significantly increasing the performance of code that requires it.</strong></p><pre><code class="python language-python hljs">&lt;iter&gt; = os.scandir(path=<span class="hljs-string">'.'</span>) <span class="hljs-comment"># Returns DirEntry objects located at the path.</span>
&lt;str&gt; = &lt;DirEntry&gt;.path <span class="hljs-comment"># Returns object's path (relative by default).</span>
&lt;str&gt; = &lt;DirEntry&gt;.path <span class="hljs-comment"># Is absolute if 'path' argument was absolute.</span>
&lt;str&gt; = &lt;DirEntry&gt;.name <span class="hljs-comment"># Returns path's final component as a string.</span>
&lt;file&gt; = open(&lt;DirEntry&gt;) <span class="hljs-comment"># Opens the file and returns its file object.</span>
</code></pre></div>
@ -1539,7 +1539,7 @@ CompletedProcess(args=[<span class="hljs-string">'bc'</span>, <span class="hljs-
<li><strong><code class="python hljs"><span class="hljs-string">'lineterminator'</span></code> - How writer terminates rows. Reader looks for '\n', '\r' and '\r\n'.</strong></li>
<li><strong><code class="python hljs"><span class="hljs-string">'quotechar'</span></code> - Character for quoting fields containing delimiters, quotechars, '\n' or '\r'.</strong></li>
<li><strong><code class="python hljs"><span class="hljs-string">'escapechar'</span></code> - Character for escaping quotechars (not needed if doublequote is True).</strong></li>
<li><strong><code class="python hljs"><span class="hljs-string">'doublequote'</span></code> - Whether quotechars inside fields are (or get) doubled or escaped.</strong></li>
<li><strong><code class="python hljs"><span class="hljs-string">'doublequote'</span></code> - Whether quotechars inside fields are/get doubled instead of escaped.</strong></li>
<li><strong><code class="python hljs"><span class="hljs-string">'quoting'</span></code> - 0: As necessary, 1: All, 2: All but numbers which are read as floats, 3: None.</strong></li>
<li><strong><code class="python hljs"><span class="hljs-string">'skipinitialspace'</span></code> - Is space character at the start of the field stripped by the reader.</strong></li>
</ul><div><h3 id="dialects">Dialects</h3><pre><code class="text language-text">┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
@ -1692,7 +1692,7 @@ CompletedProcess(args=[<span class="hljs-string">'bc'</span>, <span class="hljs-
<div><h2 id="array"><a href="#array" name="array">#</a>Array</h2><p><strong>List that can only hold numbers of a predefined C type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be reversed with byteswap() method.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> array <span class="hljs-keyword">import</span> array
<div><h2 id="array"><a href="#array" name="array">#</a>Array</h2><p><strong>List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be reversed with byteswap() method.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> array <span class="hljs-keyword">import</span> array
</code></pre></div>
@ -1727,7 +1727,7 @@ CompletedProcess(args=[<span class="hljs-string">'bc'</span>, <span class="hljs-
<pre><code class="python language-python hljs">&lt;deque&gt; = deque(&lt;collection&gt;) <span class="hljs-comment"># Use `maxlen=&lt;int&gt;` to set size limit.</span>
&lt;deque&gt;.appendleft(&lt;el&gt;) <span class="hljs-comment"># Opposite element is dropped if full.</span>
&lt;deque&gt;.extendleft(&lt;collection&gt;) <span class="hljs-comment"># Appends elements in reversed order.</span>
&lt;deque&gt;.extendleft(&lt;collection&gt;) <span class="hljs-comment"># Prepends reversed coll. to the deque.</span>
&lt;deque&gt;.rotate(n=<span class="hljs-number">1</span>) <span class="hljs-comment"># Last element becomes the first one.</span>
&lt;el&gt; = &lt;deque&gt;.popleft() <span class="hljs-comment"># Raises IndexError if deque is empty.</span>
</code></pre>
@ -2934,7 +2934,7 @@ $ deactivate <span class="hljs-comment"># Deactivates the active
<footer>
<aside>July 29, 2025</aside>
<aside>July 30, 2025</aside>
<a href="https://gto76.github.io" rel="author">Jure Šorn</a>
</footer>

3
pdf/remove_links.py

@ -15,8 +15,7 @@ MATCHES = {
'<strong>Hints are used by type checkers like <a href="https://pypi.org/project/mypy/">mypy</a>, data validation libraries such as <a href="https://pypi.org/project/pydantic/">Pydantic</a> and lately also by <a href="https://pypi.org/project/Cython/">Cython</a> compiler. However, they are not enforced by CPython interpreter.</strong>': '<strong>Hints are used by type checkers like mypy, data validation libraries such as Pydantic and lately also by Cython compiler. However, they are not enforced by CPython interpreter.</strong>',
'<strong>Objects can be made <a href="#sortable">sortable</a> with <code class="python hljs"><span class="hljs-string">\'order=True\'</span></code> and immutable with <code class="python hljs"><span class="hljs-string">\'frozen=True\'</span></code>.</strong>': '<strong>Objects can be made sortable with <code class="python hljs"><span class="hljs-string">\'order=True\'</span></code> and immutable with <code class="python hljs"><span class="hljs-string">\'frozen=True\'</span></code>.</strong>',
'<strong>For object to be <a href="#hashable">hashable</a>, all attributes must be hashable and \'frozen\' must be True.</strong>': '<strong>For object to be hashable, all attributes must be hashable and \'frozen\' must be True.</strong>',
'<strong>Function field() is needed because <code class="python hljs"><span class="hljs-string">\'&lt;attr_name&gt;: list = []\'</span></code> would make a list that is shared among all instances. Its \'default_factory\' argument can be any <a href="#callable">callable</a>.</strong>': '<strong>Function field() is needed because <code class="python hljs"><span class="hljs-string">\'&lt;attr_name&gt;: list = []\'</span></code> would make a list that is shared among all instances. Its \'default_factory\' argument can be any callable (p. 17).</strong>',
'<strong>Sequence iterators returned by the <a href="#iterator">iter()</a> function, such as list_iterator and set_iterator.</strong>': '<strong>Sequence iterators returned by the iter() function, such as list_iterator and set_iterator.</strong>',
'<strong>Sequence iterators returned by the <a href="#iterator">iter()</a> function, such as list_iterator, etc.</strong>': '<strong>Sequence iterators returned by the iter() function, such as list_iterator and set_iterator.</strong>',
'<strong>Objects returned by the <a href="#itertools">itertools</a> module, such as count, repeat and cycle.</strong>': '<strong>Objects returned by the itertools module, such as count, repeat and cycle (p. 3).</strong>',
'<strong>Generators returned by the <a href="#generator">generator functions</a> and <a href="#comprehensions">generator expressions</a>.</strong>': '<strong>Generators returned by the generator functions (p. 4) and generator expressions (p. 11).</strong>',
'<strong>File objects returned by the <a href="#open">open()</a> function, etc.</strong>': '<strong>File objects returned by the open() function (p. 22), etc.</strong>',

Loading…
Cancel
Save