@ -120,8 +120,8 @@ product_of_elems = functools.reduce(<span class="hljs-keyword">lambda</span> out
list_of_chars = list(<str>)
</code></pre>
<ul>
<li><strong>For details about sorted(), min() and max() see sortable (p. 16).</strong></li>
<li><strong>Module 'operator' (p. 31) provides functions itemgetter() and mul() that offer the same functionality as lambda expressions (p. 11) above.</strong></li>
<li><strong>For details about sorted(), min() and max() see <ahref="#sortable">sortable</a>.</strong></li>
<li><strong>Module <ahref="#operator">operator</a> provides functions itemgetter() and mul() that offer the same functionality as <ahref="#lambda">lambda</a> expressions above.</strong></li>
</ul>
<pre><codeclass="python language-python hljs"><list>.insert(<int>, <el>) <spanclass="hljs-comment"># Inserts item at index and moves the rest to the right.</span>
<el> = <list>.pop([<int>]) <spanclass="hljs-comment"># Removes and returns item at index or from the end.</span>
<li><strong>Options can be generated dynamically: <codeclass="python hljs"><spanclass="hljs-string">f'<spanclass="hljs-subst">{<el>:{<str/int>}</span>[…]}'</span></code>.</strong></li>
<li><strong>Adding <codeclass="python hljs"><spanclass="hljs-string">'!r'</span></code> before the colon converts object to string by calling its repr() method (p. 14).</strong></li>
<li><strong>Adding <codeclass="python hljs"><spanclass="hljs-string">'!r'</span></code> before the colon converts object to string by calling its <ahref="#class">repr()</a> method.</strong></li>
<li><strong>A decorator takes a function, adds some functionality and returns it.</strong></li>
<li><strong>It can be any callable, but is usually implemented as a function that returns a closure.</strong></li>
<li><strong>It can be any <ahref="#callable">callable</a>, but is usually implemented as a function that returns a <ahref="#closure">closure</a>.</strong></li>
@ -894,9 +894,9 @@ Z = dataclasses.make_dataclass(<span class="hljs-string">'Z'</span>, [<span clas
<ul>
<li><strong>Objects can be made sortable 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 hashable, 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 callable (p. 17).</strong></li>
<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>For attributes of arbitrary type use <codeclass="python hljs"><spanclass="hljs-string">'typing.Any'</span></code>.</strong></li>
<div><h4id="pythonhasmanydifferentiteratorobjects">Python has many different iterator objects:</h4><ul>
<li><strong>Sequence iterators returned by the iter() function, such as list_iterator and set_iterator (p. 3).</strong></li>
<li><strong>Objects returned by the itertools module, such as count, repeat and cycle (p. 3).</strong></li>
<li><strong>Generators returned by the generator functions (p. 4) and generator expressions (p. 11).</strong></li>
<li><strong>File objects returned by the open() function (p. 22), etc.</strong></li>
<li><strong>Sequence iterators returned by the <ahref="#iterator">iter()</a> function, such as list_iterator and set_iterator.</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>
</ul><div><h3id="callable">Callable</h3><ul>
<li><strong>All functions and classes have a call() method, hence are callable.</strong></li>
<li><strong>When this cheatsheet uses <codeclass="python hljs"><spanclass="hljs-string">'<function>'</span></code> as an argument, it actually means <codeclass="python hljs"><spanclass="hljs-string">'<callable>'</span></code>.</strong></li>
@ -1452,7 +1452,7 @@ shutil.rmtree(<path>) <span class="hljs-comment"># Deletes t
</code></pre>
<ul>
<li><strong>Paths can be either strings, Paths or DirEntry objects.</strong></li>
<li><strong>Functions report OS related errors by raising OSError or one of its subclasses (p. 23).</strong></li>
<li><strong>Functions report OS related errors by raising either OSError or one of its <ahref="#exceptions-1">subclasses</a>.</strong></li>
</ul>
<div><h3id="shellcommands">Shell Commands</h3><pre><codeclass="python language-python hljs"><pipe> = os.popen(<spanclass="hljs-string">'<command>'</span>) <spanclass="hljs-comment"># Executes command in sh/cmd. Returns its stdout pipe.</span>
<str> = <pipe>.read(size=<spanclass="hljs-number">-1</span>) <spanclass="hljs-comment"># Reads 'size' chars or until EOF. Also readline/s().</span>
<li><strong>File must be opened with a <codeclass="python hljs"><spanclass="hljs-string">'newline=""'</span></code> argument, or newlines embedded inside quoted fields will not be interpreted correctly!</strong></li>
<li><strong>To print the spreadsheet to the console use Tabulate library (p. 34).</strong></li>
<li><strong>For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library (p. 46).</strong></li>
<li><strong>To print the spreadsheet to the console use <ahref="#table">Tabulate</a> library.</strong></li>
<li><strong>For XML and binary Excel files (xlsx, xlsm and xlsb) use <ahref="#dataframeplotencodedecode">Pandas</a> library.</strong></li>
<li><strong>Reader accepts any iterator of strings, not just files.</strong></li>
<li><strong>Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetime.</strong></li>
<li><strong>Bools will be stored and returned as ints and dates as ISO formatted strings (p. 9).</strong></li>
<li><strong>Bools will be stored and returned as ints and dates as <ahref="#encode">ISO formatted strings</a>.</strong></li>
</ul>
<div><h3id="example">Example</h3><p><strong>Values are not actually saved in this example because <codeclass="python hljs"><spanclass="hljs-string">'conn.commit()'</span></code> is omitted!</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-meta">>>></span>conn = sqlite3.connect(<spanclass="hljs-string">'test.db'</span>)
<spanclass="hljs-meta">>>></span>conn.execute(<spanclass="hljs-string">'CREATE TABLE person (person_id INTEGER PRIMARY KEY, name, height)'</span>)
<div><h3id="threadpoolexecutor">Thread Pool Executor</h3><ul>
<li><strong>Object that manages thread execution.</strong></li>
<li><strong>An object with the same interface called ProcessPoolExecutor provides true parallelism by running a separate interpreter in each process. All arguments must be pickable (p. 25).</strong></li>
<li><strong>An object with the same interface called ProcessPoolExecutor provides true parallelism by running a separate interpreter in each process. All arguments must be <ahref="#pickle">pickable</a>.</strong></li>
<Exec>.shutdown(wait=<spanclass="hljs-keyword">True</span>) <spanclass="hljs-comment"># Blocks until all threads finish executing.</span>
</code></pre></div>
@ -1898,7 +1898,7 @@ ValueError: malformed node or string
<li><strong>Coroutine definition starts with <codeclass="python hljs"><spanclass="hljs-string">'async'</span></code> and its call with <codeclass="python hljs"><spanclass="hljs-string">'await'</span></code>.</strong></li>
<li><strong><codeclass="python hljs"><spanclass="hljs-string">'asyncio.run(<coroutine>)'</span></code> is the main entry point for asynchronous programs.</strong></li>
<li><strong>Functions wait(), gather() and as_completed() start multiple coroutines at the same time.</strong></li>
<li><strong>Asyncio module also provides its own Queue, Event, Lock and Semaphore classes (p. 30).</strong></li>
<li><strong>Asyncio module also provides its own <ahref="#queue">Queue</a>, <ahref="#semaphoreeventbarrier">Event</a>, <ahref="#lock">Lock</a> and <ahref="#semaphoreeventbarrier">Semaphore</a> classes.</strong></li>
</ul><div><h4id="runsaterminalgamewhereyoucontrolanasteriskthatmustavoidnumbers">Runs a terminal game where you control an asterisk that must avoid numbers:</h4><pre><codeclass="python language-python hljs"><spanclass="hljs-keyword">import</span> asyncio, collections, curses, curses.textpad, enum, random
P = collections.namedtuple(<spanclass="hljs-string">'P'</span>, <spanclass="hljs-string">'x y'</span>) <spanclass="hljs-comment"># Position</span>
@ -2081,7 +2081,7 @@ app.run()
</code></pre>
<ul>
<li><strong>Starts the app on <codeclass="python hljs"><spanclass="hljs-string">'http://localhost:5000'</span></code>.</strong></li>
<li><strong>A WSGI server like Waitress and a HTTP server such as Nginx are needed to run globally.</strong></li>
<li><strong>A WSGI server like <ahref="https://flask.palletsprojects.com/en/latest/deploying/waitress/">Waitress</a> and a HTTP server such as <ahref="https://flask.palletsprojects.com/en/latest/deploying/nginx/">Nginx</a> are needed to run globally.</strong></li>
<li><strong>The "latest and greatest" profiler that can also monitor GPU usage is called Scalene.</strong></li>
<li><strong>The "latest and greatest" profiler that can also monitor GPU usage is called <ahref="https://github.com/plasma-umass/scalene">Scalene</a>.</strong></li>
</ul>
<div><h2id="numpy"><ahref="#numpy"name="numpy">#</a>NumPy</h2><p><strong>Array manipulation mini-language. It can run up to one hundred times faster than the equivalent Python code. An even faster alternative that runs on a GPU is called CuPy.</strong></p><pre><codeclass="python language-python hljs"><spanclass="hljs-comment"># $ pip3 install numpy</span>