Browse Source

List, Duck type, Operator

pull/115/head
Jure Šorn 3 years ago
parent
commit
298ffed9ad
5 changed files with 27 additions and 15 deletions
  1. 16
      README.md
  2. 19
      index.html
  3. 2
      pdf/index_for_pdf.html
  4. 2
      pdf/index_for_pdf_print.html
  5. 3
      pdf/remove_links.py

16
README.md

@ -53,6 +53,7 @@ flatter_list = list(itertools.chain.from_iterable(<list>))
product_of_elems = functools.reduce(lambda out, el: out * el, <collection>) product_of_elems = functools.reduce(lambda out, el: out * el, <collection>)
list_of_chars = list(<str>) list_of_chars = list(<str>)
``` ```
* **For details about built-in functions sorted(), min() and max() see [sortable](#sortable).**
* **Module [operator](#operator) provides functions itemgetter() and mul() that offer the same functionality as [lambda](#lambda) expressions above.** * **Module [operator](#operator) provides functions itemgetter() and mul() that offer the same functionality as [lambda](#lambda) expressions above.**
```python ```python
@ -1084,6 +1085,7 @@ Duck Types
* **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.** * **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.**
* **That means all objects compare not equal by default.** * **That means all objects compare not equal by default.**
* **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.** * **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.**
* **Ne() automatically works on any object that has eq() defined.**
```python ```python
class MyComparable: class MyComparable:
@ -1116,7 +1118,10 @@ class MyHashable:
``` ```
### Sortable ### Sortable
* **With total_ordering decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods.**
* **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.**
* **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 elements being equal.**
```python ```python
from functools import total_ordering from functools import total_ordering
@ -1230,7 +1235,7 @@ True
### Collection ### Collection
* **Only required methods are iter() and len().** * **Only required methods are iter() and len().**
* **This cheatsheet actually means `'<iterable>'` when it uses `'<collection>'`.** * **This cheatsheet actually means `'<iterable>'` when it uses `'<collection>'`.**
* **I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'.**
* **I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The only drawback of this decision is that a reader could think a certain function doesn't accept iterators when it does, since iterators are the only iterable objects that are not collections.**
```python ```python
class MyCollection: class MyCollection:
def __init__(self, a): def __init__(self, a):
@ -2133,7 +2138,7 @@ Operator
```python ```python
from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs
from operator import eq, ne, lt, le, gt, ge from operator import eq, ne, lt, le, gt, ge
from operator import and_, or_, xor, not_
from operator import and_, or_, xor, inv
from operator import itemgetter, attrgetter, methodcaller from operator import itemgetter, attrgetter, methodcaller
``` ```
@ -2146,8 +2151,9 @@ product_of_elems = functools.reduce(op.mul, <collection>)
union_of_sets = functools.reduce(op.or_, <coll_of_sets>) union_of_sets = functools.reduce(op.or_, <coll_of_sets>)
last_element = op.methodcaller('pop')(<list>) last_element = op.methodcaller('pop')(<list>)
``` ```
* **Functions and\_() and or\_() correspond to operators '&' and '|'.**
* **They only work on objects with defined and() and or() special methods, i.e. ints and sets.**
* **Functions and\_(), or\_(), xor() and inv() correspond to operators '&', '|', '^' and '~'.**
* **They only work on objects with and(), or(), xor() and invert() special methods.**
* **Also: `'<int> = <int> &|^ <bool>'` and `'<bool> = <bool> &|^ <bool>'`.**
Introspection Introspection

19
index.html

@ -226,7 +226,7 @@ pre.prettyprint {
<body> <body>
<header> <header>
<aside>November 19, 2021</aside>
<aside>November 29, 2021</aside>
<a href="https://gto76.github.io" rel="author">Jure Šorn</a> <a href="https://gto76.github.io" rel="author">Jure Šorn</a>
</header> </header>
@ -273,6 +273,7 @@ product_of_elems = functools.reduce(<span class="hljs-keyword">lambda</span> out
list_of_chars = list(&lt;str&gt;) list_of_chars = list(&lt;str&gt;)
</code></pre> </code></pre>
<ul> <ul>
<li><strong>For details about built-in functions sorted(), min() and max() see <a href="#sortable">sortable</a>.</strong></li>
<li><strong>Module <a href="#operator">operator</a> provides functions itemgetter() and mul() that offer the same functionality as <a href="#lambda">lambda</a> expressions above.</strong></li> <li><strong>Module <a href="#operator">operator</a> provides functions itemgetter() and mul() that offer the same functionality as <a href="#lambda">lambda</a> expressions above.</strong></li>
</ul> </ul>
<pre><code class="python language-python hljs">&lt;list&gt;.insert(&lt;int&gt;, &lt;el&gt;) <span class="hljs-comment"># Inserts item at index and moves the rest to the right.</span> <pre><code class="python language-python hljs">&lt;list&gt;.insert(&lt;int&gt;, &lt;el&gt;) <span class="hljs-comment"># Inserts item at index and moves the rest to the right.</span>
@ -1065,6 +1066,7 @@ Z = dataclasses.make_dataclass(<span class="hljs-string">'Z'</span>, [<span clas
<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>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 objects compare not equal by default.</strong></li> <li><strong>That means all objects compare not equal by default.</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.</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.</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> </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> <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 self.a = a
@ -1097,7 +1099,9 @@ Z = dataclasses.make_dataclass(<span class="hljs-string">'Z'</span>, [<span clas
<div><h3 id="sortable">Sortable</h3><ul> <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.</strong></li>
<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>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 elements being equal.</strong></li>
</ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> total_ordering </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> total_ordering
<span class="hljs-meta">@total_ordering</span> <span class="hljs-meta">@total_ordering</span>
@ -1202,7 +1206,7 @@ Hello World!
<div><h3 id="collection">Collection</h3><ul> <div><h3 id="collection">Collection</h3><ul>
<li><strong>Only required methods are iter() and len().</strong></li> <li><strong>Only required methods are iter() and len().</strong></li>
<li><strong>This cheatsheet actually means <code class="python hljs"><span class="hljs-string">'&lt;iterable&gt;'</span></code> when it uses <code class="python hljs"><span class="hljs-string">'&lt;collection&gt;'</span></code>.</strong></li> <li><strong>This cheatsheet actually means <code class="python hljs"><span class="hljs-string">'&lt;iterable&gt;'</span></code> when it uses <code class="python hljs"><span class="hljs-string">'&lt;collection&gt;'</span></code>.</strong></li>
<li><strong>I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'.</strong></li>
<li><strong>I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The only drawback of this decision is that a reader could think a certain function doesn't accept iterators when it does, since iterators are the only iterable objects that are not collections.</strong></li>
</ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyCollection</span>:</span> </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyCollection</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> <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 self.a = a
@ -1905,7 +1909,7 @@ CompletedProcess(args=[<span class="hljs-string">'bc'</span>, <span class="hljs-
</code></pre> </code></pre>
<div><h2 id="operator"><a href="#operator" name="operator">#</a>Operator</h2><p><strong>Module of functions that provide the functionality of operators.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> add, sub, mul, truediv, floordiv, mod, pow, neg, abs <div><h2 id="operator"><a href="#operator" name="operator">#</a>Operator</h2><p><strong>Module of functions that provide the functionality of operators.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> add, sub, mul, truediv, floordiv, mod, pow, neg, abs
<span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> eq, ne, lt, le, gt, ge <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> eq, ne, lt, le, gt, ge
<span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> and_, or_, xor, not_
<span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> and_, or_, xor, inv
<span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> itemgetter, attrgetter, methodcaller <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> itemgetter, attrgetter, methodcaller
</code></pre></div> </code></pre></div>
@ -1919,8 +1923,9 @@ union_of_sets = functools.reduce(op.or_, &lt;coll_of_sets&gt;)
last_element = op.methodcaller(<span class="hljs-string">'pop'</span>)(&lt;list&gt;) last_element = op.methodcaller(<span class="hljs-string">'pop'</span>)(&lt;list&gt;)
</code></pre> </code></pre>
<ul> <ul>
<li><strong>Functions and_() and or_() correspond to operators '&amp;' and '|'.</strong></li>
<li><strong>They only work on objects with defined and() and or() special methods, i.e. ints and sets.</strong></li>
<li><strong>Functions and_(), or_(), xor() and inv() correspond to operators '&amp;', '|', '^' and '~'.</strong></li>
<li><strong>They only work on objects with and(), or(), xor() and invert() special methods.</strong></li>
<li><strong>Also: <code class="python hljs"><span class="hljs-string">'&lt;int&gt; = &lt;int&gt; &amp;|^ &lt;bool&gt;'</span></code> and <code class="python hljs"><span class="hljs-string">'&lt;bool&gt; = &lt;bool&gt; &amp;|^ &lt;bool&gt;'</span></code>.</strong></li>
</ul> </ul>
<div><h2 id="introspection"><a href="#introspection" name="introspection">#</a>Introspection</h2><p><strong>Inspecting code at runtime.</strong></p><div><h3 id="variables">Variables</h3><pre><code class="python language-python hljs">&lt;list&gt; = dir() <span class="hljs-comment"># Names of local variables (incl. functions).</span> <div><h2 id="introspection"><a href="#introspection" name="introspection">#</a>Introspection</h2><p><strong>Inspecting code at runtime.</strong></p><div><h3 id="variables">Variables</h3><pre><code class="python language-python hljs">&lt;list&gt; = dir() <span class="hljs-comment"># Names of local variables (incl. functions).</span>
&lt;dict&gt; = vars() <span class="hljs-comment"># Dict of local variables. Also locals().</span> &lt;dict&gt; = vars() <span class="hljs-comment"># Dict of local variables. Also locals().</span>
@ -3024,7 +3029,7 @@ $ pyinstaller script.py --add-data '&lt;path&gt;:.' <span class="hljs-comment">
<footer> <footer>
<aside>November 19, 2021</aside>
<aside>November 29, 2021</aside>
<a href="https://gto76.github.io" rel="author">Jure Šorn</a> <a href="https://gto76.github.io" rel="author">Jure Šorn</a>
</footer> </footer>

2
pdf/index_for_pdf.html

@ -14,7 +14,7 @@
<h3 id="b">B</h3> <h3 id="b">B</h3>
<p><strong>beautifulsoup library, <a href="#scrapespythonsurlversionnumberandlogofromitswikipediapage">35</a></strong><br> <p><strong>beautifulsoup library, <a href="#scrapespythonsurlversionnumberandlogofromitswikipediapage">35</a></strong><br>
<strong>binary representation, <a href="#ints">7</a>, <a href="#binhex">8</a></strong><br> <strong>binary representation, <a href="#ints">7</a>, <a href="#binhex">8</a></strong><br>
<strong>bitwise operators, <a href="#bitwiseoperators">8</a></strong><br>
<strong>bitwise operators, <a href="#bitwiseoperators">8</a>, <a href="#operator">31</a></strong><br>
<strong>bottle library, <a href="#web">36</a></strong><br> <strong>bottle library, <a href="#web">36</a></strong><br>
<strong>bytes, <a href="#open">22</a>-<a href="#modes">23</a>, <a href="#pickle">25</a>, <a href="#bytes">28</a>-<a href="#memoryview">29</a></strong> </p> <strong>bytes, <a href="#open">22</a>-<a href="#modes">23</a>, <a href="#pickle">25</a>, <a href="#bytes">28</a>-<a href="#memoryview">29</a></strong> </p>
<h3 id="c">C</h3> <h3 id="c">C</h3>

2
pdf/index_for_pdf_print.html

@ -14,7 +14,7 @@
<h3 id="b">B</h3> <h3 id="b">B</h3>
<p><strong>beautifulsoup library, 35</strong><br> <p><strong>beautifulsoup library, 35</strong><br>
<strong>binary representation, 7, 8</strong><br> <strong>binary representation, 7, 8</strong><br>
<strong>bitwise operators, 8</strong><br>
<strong>bitwise operators, 8, 31</strong><br>
<strong>bottle library, 36</strong><br> <strong>bottle library, 36</strong><br>
<strong>bytes, 22-23, 25, 28-29</strong> </p> <strong>bytes, 22-23, 25, 28-29</strong> </p>
<h3 id="c">C</h3> <h3 id="c">C</h3>

3
pdf/remove_links.py

@ -7,10 +7,11 @@ from pathlib import Path
MATCHES = { MATCHES = {
'<strong>For details about built-in functions sorted(), min() and max() see <a href="#sortable">sortable</a>.</strong>': '<strong>For details about built-in functions sorted(), min() and max() see sortable (p. 16).</strong>',
'<strong>Module <a href="#operator">operator</a> provides functions itemgetter() and mul() that offer the same functionality as <a href="#lambda">lambda</a> expressions above.</strong>': '<strong>Module \'operator\' (p. 31) provides functions itemgetter() and mul() that offer the same functionality as lambda expressions (p. 11) above.</strong>', '<strong>Module <a href="#operator">operator</a> provides functions itemgetter() and mul() that offer the same functionality as <a href="#lambda">lambda</a> expressions above.</strong>': '<strong>Module \'operator\' (p. 31) provides functions itemgetter() and mul() that offer the same functionality as lambda expressions (p. 11) above.</strong>',
'<strong>Adding <code class="python hljs"><span class="hljs-string">\'!r\'</span></code> before the colon converts object to string by calling its <a href="#class">repr()</a> method.</strong>': '<strong>Adding <code class="python hljs"><span class="hljs-string">\'!r\'</span></code> before the colon converts object to string by calling its repr() method (p. 14).</strong>', '<strong>Adding <code class="python hljs"><span class="hljs-string">\'!r\'</span></code> before the colon converts object to string by calling its <a href="#class">repr()</a> method.</strong>': '<strong>Adding <code class="python hljs"><span class="hljs-string">\'!r\'</span></code> before the colon converts object to string by calling its repr() method (p. 14).</strong>',
'<strong>It can be any <a href="#callable">callable</a>, but is usually implemented as a function that returns a <a href="#closure">closure</a>.</strong>': '<strong>It can be any callable (p. 17), but is usually implemented as a function that returns a closure (p. 12).</strong>', '<strong>It can be any <a href="#callable">callable</a>, but is usually implemented as a function that returns a <a href="#closure">closure</a>.</strong>': '<strong>It can be any callable (p. 17), but is usually implemented as a function that returns a closure (p. 12).</strong>',
'<strong>Default_factory can be any <a href="#callable">callable</a>.</strong>': '<strong>Default_factory can be any callable (p. 17).</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 (p.&nbsp;3).</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 (p.&nbsp;3).</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>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>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>',

Loading…
Cancel
Save