* **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.**
**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.
<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, <codeclass="python hljs"><spanclass="hljs-string">'print(a)'</span></code> calls <codeclass="python hljs"><spanclass="hljs-string">'a.__str__()'</span></code> and <codeclass="python hljs"><spanclass="hljs-string">'a + b'</span></code> calls <codeclass="python hljs"><spanclass="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, <codeclass="python hljs"><spanclass="hljs-string">'print(a)'</span></code> calls <codeclass="python hljs"><spanclass="hljs-string">'a.__str__()'</span></code> and <codeclass="python hljs"><spanclass="hljs-string">'a + b'</span></code> calls <codeclass="python hljs"><spanclass="hljs-string">'a.__add__(b)'</span></code>.</strong></li>
<li><strong>Methods decorated with <codeclass="python hljs"><spanclass="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 <ahref="#sortable">sortable</a> with <codeclass="python hljs"><spanclass="hljs-string">'order=True'</span></code> and immutable with <codeclass="python hljs"><spanclass="hljs-string">'frozen=True'</span></code>.</strong></li>
<li><strong>For object to be <ahref="#hashable">hashable</a>, all attributes must be hashable and 'frozen' must be True.</strong></li>
<li><strong>Function field() is needed because <codeclass="python hljs"><spanclass="hljs-string">'<attr_name>: list = []'</span></code> would make a list that is shared among all instances. Its 'default_factory' argument can be any <ahref="#callable">callable</a>.</strong></li>
<li><strong>Function field() is needed because <codeclass="python hljs"><spanclass="hljs-string">'<attr_name>: 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 <codeclass="python hljs"><spanclass="hljs-string">'typing.Any'</span></code>.</strong></li>
@ -927,7 +927,7 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str
<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>. 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>
<div><h4id="pythonhasmanydifferentiteratorobjects">Python has many different iterator objects:</h4><ul>
<li><strong>Sequence iterators returned by the <ahref="#iterator">iter()</a> function, such as list_iterator and set_iterator.</strong></li>
<li><strong>Sequence iterators returned by the <ahref="#iterator">iter()</a> function, such as list_iterator, etc.</strong></li>
<li><strong>Objects returned by the <ahref="#itertools">itertools</a> module, such as count, repeat and cycle.</strong></li>
<li><strong>Generators returned by the <ahref="#generator">generator functions</a> and <ahref="#comprehensions">generator expressions</a>.</strong></li>
<li><strong>File objects returned by the <ahref="#open">open()</a> function, etc.</strong></li>
<li><strong>Also catches subclasses, e.g. <codeclass="python hljs"><spanclass="hljs-string">'IndexError'</span></code> is caught by <codeclass="python hljs"><spanclass="hljs-string">'except LookupError:'</span></code>.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'traceback.print_exc()'</span></code> to print the full error message to standard error stream.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'print(<name>)'</span></code> to print just the cause of the exception (i.e. its arguments).</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'print(<name>)'</span></code> to print just the cause of the exception (that is, its arguments).</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'logging.exception(<str>)'</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 <ahref="#logging">Logging</a>.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'sys.exc_info()'</span></code> to get exception type, object, and traceback of caught exception.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'help=<str>'</span></code> to set argument description that will be displayed in help message.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'default=<obj>'</span></code> to override None as option's or optional argument's default value.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'type=FileType(<mode>)'</span></code> for files. Accepts 'encoding', but 'newline' is None.</strong></li>
<li><strong>Use <codeclass="python hljs"><spanclass="hljs-string">'type=FileType(<mode>)'</span></code> for files. It accepts 'encoding', but 'newline' is None.</strong></li>
</ul>
<div><h2id="open"><ahref="#open"name="open">#</a>Open</h2><p><strong>Opens a file and returns the corresponding file object.</strong></p><pre><codeclass="python language-python hljs"><file> = open(<path>, mode=<spanclass="hljs-string">'r'</span>, encoding=<spanclass="hljs-keyword">None</span>, newline=<spanclass="hljs-keyword">None</span>)
<num> = <stat>.st_mtime/st_size/… <spanclass="hljs-comment"># Returns modification time, size in bytes, etc.</span>
</code></pre>
<div><h3id="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><codeclass="python language-python hljs"><iter> = os.scandir(path=<spanclass="hljs-string">'.'</span>) <spanclass="hljs-comment"># Returns DirEntry objects located at the path.</span>
<str> = <DirEntry>.path <spanclass="hljs-comment"># Returns object's path (relative by default).</span>
<str> = <DirEntry>.path <spanclass="hljs-comment"># Is absolute if 'path' argument was absolute.</span>
<str> = <DirEntry>.name <spanclass="hljs-comment"># Returns path's final component as a string.</span>
<file> = open(<DirEntry>) <spanclass="hljs-comment"># Opens the file and returns its file object.</span>
<li><strong><codeclass="python hljs"><spanclass="hljs-string">'lineterminator'</span></code> - How writer terminates rows. Reader looks for '\n', '\r' and '\r\n'.</strong></li>
<li><strong><codeclass="python hljs"><spanclass="hljs-string">'quotechar'</span></code> - Character for quoting fields containing delimiters, quotechars, '\n' or '\r'.</strong></li>
<li><strong><codeclass="python hljs"><spanclass="hljs-string">'escapechar'</span></code> - Character for escaping quotechars (not needed if doublequote is True).</strong></li>
<li><strong><codeclass="python hljs"><spanclass="hljs-string">'doublequote'</span></code> - Whether quotechars inside fields are (or get) doubled or escaped.</strong></li>
<li><strong><codeclass="python hljs"><spanclass="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><codeclass="python hljs"><spanclass="hljs-string">'skipinitialspace'</span></code> - Is space character at the start of the field stripped by the reader.</strong></li>
<div><h2id="array"><ahref="#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><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> array <spanclass="hljs-keyword">import</span> array
<div><h2id="array"><ahref="#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><codeclass="python language-python hljs"><spanclass="hljs-keyword">from</span> array <spanclass="hljs-keyword">import</span> array
<pre><codeclass="python language-python hljs"><deque> = deque(<collection>) <spanclass="hljs-comment"># Use `maxlen=<int>` to set size limit.</span>
<deque>.appendleft(<el>) <spanclass="hljs-comment"># Opposite element is dropped if full.</span>
<deque>.extendleft(<collection>) <spanclass="hljs-comment"># Appends elements in reversed order.</span>
<deque>.extendleft(<collection>) <spanclass="hljs-comment"># Prepends reversed coll. to the deque.</span>
<deque>.rotate(n=<spanclass="hljs-number">1</span>) <spanclass="hljs-comment"># Last element becomes the first one.</span>
<el> = <deque>.popleft() <spanclass="hljs-comment"># Raises IndexError if deque is empty.</span>
</code></pre>
@ -2934,7 +2934,7 @@ $ deactivate <span class="hljs-comment"># Deactivates the active
'<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">\'<attr_name>: 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">\'<attr_name>: 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>',