Browse Source

Class, Duck types, Open, Memory view, Operator, Metaprogramming, Web, Profile

pull/109/merge
Jure Šorn 1 year ago
parent
commit
9c81a492b5
2 changed files with 20 additions and 20 deletions
  1. 18
      README.md
  2. 22
      index.html

18
README.md

@ -1068,7 +1068,7 @@ from dataclasses import make_dataclass
#### Rest of type annotations (CPython interpreter ignores them all):
```python
import typing as tp, collections.abc as abc
import collections.abc as abc, typing as tp
<var_name>: list/set/abc.Iterable/abc.Sequence/tp.Optional[<type>] [= <obj>]
<var_name>: dict/tuple/tp.Union[<type>, ...] [= <obj>]
def func(<arg_name>: <type> [= <obj>]) -> <type>: ...
@ -1252,7 +1252,7 @@ True
### Collection
* **Only required methods are iter() and len(). Len() should return the number of items.**
* **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'. 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 built-in objects that are iterable but are not collections.**
* **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 the reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections.**
```python
class MyCollection:
def __init__(self, a):
@ -1606,7 +1606,7 @@ Open
<file>.writelines(<collection>) # Writes a coll. of strings or bytes objects.
<file>.flush() # Flushes write buffer. Runs every 4096/8192 B.
```
* **Methods do not add or strip trailing newlines, even writelines().**
* **Methods do not add or strip trailing newlines, not even writelines().**
### Read Text from File
```python
@ -2045,7 +2045,7 @@ from array import array
Memory View
-----------
* **A sequence object that points to the memory of another object.**
* **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.**
* **Casting only works between char and other types and uses system's sizes.**
@ -2177,7 +2177,7 @@ product_of_elems = functools.reduce(op.mul, <collection>)
union_of_sets = functools.reduce(op.or_, <coll_of_sets>)
first_element = op.methodcaller('pop', 0)(<list>)
```
* **Binary operators require objects to have and(), or(), xor() and invert() special methods, unlike logical operators that work on all types of objects.**
* **Bitwise operators require objects to have and(), or(), xor() and invert() special methods, unlike logical operators that work on all types of objects.**
* **Also: `'<bool> = <bool> &|^ <bool>'` and `'<int> = <bool> &|^ <int>'`.**
@ -2250,7 +2250,7 @@ class MyMetaClass(type):
* **The only difference between the examples above is that my\_meta\_class() returns a class of type type, while MyMetaClass() returns a class of type MyMetaClass.**
### Metaclass Attribute
**Right before a class is created it checks if it has the 'metaclass' attribute defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type().**
**Right before a class is created it checks if it has the 'metaclass' attribute defined. If not, it recursively checks if any of its parents has it defined and eventually comes to type().**
```python
class MyClass(metaclass=MyMetaClass):
@ -2535,7 +2535,7 @@ from flask import Flask, send_from_directory, render_template_string, request
```python
app = Flask(__name__)
app.run(host=None, debug=None)
app.run(host=None, port=None, debug=None)
```
* **Starts the app at `'http://localhost:5000'`. Use `'host="0.0.0.0"'` to run externally.**
* **Install a WSGI server like [Waitress](https://flask.palletsprojects.com/en/latest/deploying/waitress/) and a HTTP server such as [Nginx](https://flask.palletsprojects.com/en/latest/deploying/nginx/) for better security.**
@ -2599,11 +2599,11 @@ duration_in_seconds = perf_counter() - start_time
### Profiling by Line
```text
$ pip3 install line_profiler
$ echo "@profile
$ echo '@profile
def main():
a = list(range(10000))
b = set(range(10000))
main()" > test.py
main()' > test.py
$ kernprof -lv test.py
Line # Hits Time Per Hit % Time Line Contents
=======================================================

22
index.html

@ -54,7 +54,7 @@
<body>
<header>
<aside>July 19, 2023</aside>
<aside>July 22, 2023</aside>
<a href="https://gto76.github.io" rel="author">Jure Šorn</a>
</header>
@ -903,7 +903,7 @@ Z = dataclasses.make_dataclass(<span class="hljs-string">'Z'</span>, [<span clas
&lt;class&gt; = make_dataclass(<span class="hljs-string">'&lt;class_name&gt;'</span>, &lt;coll_of_tuples&gt;)
&lt;tuple&gt; = (<span class="hljs-string">'&lt;attr_name&gt;'</span>, &lt;type&gt; [, &lt;default_value&gt;])</code></pre></div>
<div><h4 id="restoftypeannotationscpythoninterpreterignoresthemall">Rest of type annotations (CPython interpreter ignores them all):</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> typing <span class="hljs-keyword">as</span> tp, collections.abc <span class="hljs-keyword">as</span> abc
<div><h4 id="restoftypeannotationscpythoninterpreterignoresthemall">Rest of type annotations (CPython interpreter ignores them all):</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> collections.abc <span class="hljs-keyword">as</span> abc, typing <span class="hljs-keyword">as</span> tp
&lt;var_name&gt;: list/set/abc.Iterable/abc.Sequence/tp.Optional[&lt;type&gt;] [= &lt;obj&gt;]
&lt;var_name&gt;: dict/tuple/tp.Union[&lt;type&gt;, ...] [= &lt;obj&gt;]
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">func</span><span class="hljs-params">(&lt;arg_name&gt;: &lt;type&gt; [= &lt;obj&gt;])</span> -&gt; &lt;type&gt;:</span> ...
@ -1067,7 +1067,7 @@ Hello World!
<div><h3 id="collection">Collection</h3><ul>
<li><strong>Only required methods are iter() and len(). Len() should return the number of items.</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'. 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 built-in objects that are iterable but are not collections.</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 the reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are iterable but 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>
<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
@ -1371,7 +1371,7 @@ value = args.&lt;name&gt;
&lt;file&gt;.flush() <span class="hljs-comment"># Flushes write buffer. Runs every 4096/8192 B.</span>
</code></pre>
<ul>
<li><strong>Methods do not add or strip trailing newlines, even writelines().</strong></li>
<li><strong>Methods do not add or strip trailing newlines, not even writelines().</strong></li>
</ul>
<div><h3 id="readtextfromfile">Read Text from File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_file</span><span class="hljs-params">(filename)</span>:</span>
<span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
@ -1697,7 +1697,7 @@ CompletedProcess(args=[<span class="hljs-string">'bc'</span>, <span class="hljs-
<div><h2 id="memoryview"><a href="#memoryview" name="memoryview">#</a>Memory View</h2><ul>
<li><strong>A sequence object that points to the memory of another object.</strong></li>
<li><strong>A sequence object that points to the memory of another bytes-like object.</strong></li>
<li><strong>Each element can reference a single or multiple consecutive bytes, depending on format.</strong></li>
<li><strong>Order and number of elements can be changed with slicing.</strong></li>
<li><strong>Casting only works between char and other types and uses system's sizes.</strong></li>
@ -1801,7 +1801,7 @@ union_of_sets = functools.reduce(op.or_, &lt;coll_of_sets&gt;)
first_element = op.methodcaller(<span class="hljs-string">'pop'</span>, <span class="hljs-number">0</span>)(&lt;list&gt;)
</code></pre>
<ul>
<li><strong>Binary operators require objects to have and(), or(), xor() and invert() special methods, unlike logical operators that work on all types of objects.</strong></li>
<li><strong>Bitwise operators require objects to have and(), or(), xor() and invert() special methods, unlike logical operators that work on all types of objects.</strong></li>
<li><strong>Also: <code class="python hljs"><span class="hljs-string">'&lt;bool&gt; = &lt;bool&gt; &amp;|^ &lt;bool&gt;'</span></code> and <code class="python hljs"><span class="hljs-string">'&lt;int&gt; = &lt;bool&gt; &amp;|^ &lt;int&gt;'</span></code>.</strong></li>
</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>
@ -1852,7 +1852,7 @@ delattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>)
<li><strong>Like in our case, new() can also be called directly, usually from a new() method of a child class (</strong><code class="python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__new__</span><span class="hljs-params">(cls)</span>:</span> <span class="hljs-keyword">return</span> super().__new__(cls)</code><strong>).</strong></li>
<li><strong>The only difference between the examples above is that my_meta_class() returns a class of type type, while MyMetaClass() returns a class of type MyMetaClass.</strong></li>
</ul>
<div><h3 id="metaclassattribute">Metaclass Attribute</h3><p><strong>Right before a class is created it checks if it has the 'metaclass' attribute defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type().</strong></p><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span><span class="hljs-params">(metaclass=MyMetaClass)</span>:</span>
<div><h3 id="metaclassattribute">Metaclass Attribute</h3><p><strong>Right before a class is created it checks if it has the 'metaclass' attribute defined. If not, it recursively checks if any of its parents has it defined and eventually comes to type().</strong></p><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span><span class="hljs-params">(metaclass=MyMetaClass)</span>:</span>
b = <span class="hljs-number">12345</span>
</code></pre></div>
@ -2080,7 +2080,7 @@ WIKI_URL = <span class="hljs-string">'https://en.wikipedia.org/wiki/Python_(prog
<pre><code class="python language-python hljs">app = Flask(__name__)
app.run(host=<span class="hljs-keyword">None</span>, debug=<span class="hljs-keyword">None</span>)
app.run(host=<span class="hljs-keyword">None</span>, port=<span class="hljs-keyword">None</span>, debug=<span class="hljs-keyword">None</span>)
</code></pre>
<ul>
<li><strong>Starts the app at <code class="python hljs"><span class="hljs-string">'http://localhost:5000'</span></code>. Use <code class="python hljs"><span class="hljs-string">'host="0.0.0.0"'</span></code> to run externally.</strong></li>
@ -2130,11 +2130,11 @@ duration_in_seconds = perf_counter() - start_time
</code></pre></div>
<div><h3 id="profilingbyline">Profiling by Line</h3><pre><code class="text language-text">$ pip3 install line_profiler
$ echo "@profile
$ echo '@profile
def main():
a = list(range(10000))
b = set(range(10000))
main()" &gt; test.py
main()' &gt; test.py
$ kernprof -lv test.py
Line # Hits Time Per Hit % Time Line Contents
=======================================================
@ -2933,7 +2933,7 @@ $ pyinstaller script.py --add-data '&lt;path&gt;:.' <span class="hljs-comment">
<footer>
<aside>July 19, 2023</aside>
<aside>July 22, 2023</aside>
<a href="https://gto76.github.io" rel="author">Jure Šorn</a>
</footer>

Loading…
Cancel
Save