Skip to content

Commit ed1fd4e

Browse files
committed
Dict, Set, Format, Function, Imports, Operator, Logging, Plot, Audio
1 parent 528cee4 commit ed1fd4e

3 files changed

Lines changed: 168 additions & 163 deletions

File tree

README.md

Lines changed: 82 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,9 @@ value = <dict>.setdefault(key, default=None) # Returns and writes default if
101101
```
102102

103103
```python
104-
<dict>.update(<dict>) # Adds items. Replaces ones with matching keys.
105-
value = <dict>.pop(key) # Removes item or raises KeyError if missing.
106-
{k for k, v in <dict>.items() if v == value} # Returns set of keys that point to the value.
104+
<dict>.update(<dict>) # Adds items to dict. Passed dict has priority.
105+
value = <dict>.pop(key) # Removes item or raises KeyError when missing.
106+
{k for k, v in <dict>.items() if v == 123} # Returns a set of keys whose value equals 123.
107107
{k: v for k, v in <dict>.items() if k in keys} # Returns a dict of items with specified keys.
108108
```
109109

@@ -120,27 +120,27 @@ value = <dict>.pop(key) # Removes item or raises KeyErro
120120
Set
121121
---
122122
```python
123-
<set> = {<el_1>, <el_2>, ...} # Coll. of unique items. Also set(), set(<coll>).
123+
<set> = {<el_1>, <el_2>, ...} # Coll. of unique items. Also set(), set(<coll>).
124124
```
125125

126126
```python
127-
<set>.add(<el>) # Adds item to the set. Same as `<set> |= {<el>}`.
128-
<set>.update(<collection> [, ...]) # Adds items to the set. Same as `<set> |= <set>`.
127+
<set>.add(<el>) # Adds item to the set. Same as `<set> |= {<el>}`.
128+
<set>.update(<collection> [, ...]) # Adds items to the set. Same as `<set> |= <set>`.
129129
```
130130

131131
```python
132-
<set> = <set>.union(<coll>) # Returns a set of all items. Also <set> | <set>.
133-
<set> = <set>.intersection(<coll>) # Returns all shared items. Also <set> & <set>.
134-
<set> = <set>.difference(<coll>) # Returns set's unique items. Also <set> - <set>.
135-
<set> = <set>.symmetric_difference(<coll>) # Returns non-shared items. Also <set> ^ <set>.
136-
<bool> = <set>.issuperset(<coll>) # Returns False if collection has unique items.
137-
<bool> = <set>.issubset(<coll>) # Is collection a superset? Also <set> <= <set>.
132+
<set> = <set>.union(<coll>) # Returns a set of all items. Also <set> | <set>.
133+
<set> = <set>.intersection(<coll>) # Returns all shared items. Also <set> & <set>.
134+
<set> = <set>.difference(<coll>) # Returns set's unique items. Also <set> - <set>.
135+
<set> = <set>.symmetric_diff…(<coll>) # Returns non-shared items. Also <set> ^ <set>.
136+
<bool> = <set>.issuperset(<coll>) # Returns False if collection has unique items.
137+
<bool> = <set>.issubset(<coll>) # Is collection a superset? Also <set> <= <set>.
138138
```
139139

140140
```python
141-
<el> = <set>.pop() # Removes and returns an item or raises KeyError.
142-
<set>.remove(<el>) # Removes the item or raises KeyError if missing.
143-
<set>.discard(<el>) # Same as remove() but it doesn't raise an error.
141+
<el> = <set>.pop() # Removes and returns an item or raises KeyError.
142+
<set>.remove(<el>) # Removes the item or raises KeyError if missing.
143+
<set>.discard(<el>) # Same as remove() but it doesn't raise an error.
144144
```
145145

146146
### Frozen Set
@@ -413,11 +413,11 @@ Format
413413

414414
### General Options
415415
```python
416-
{<obj>:<10} # '<obj> '
417-
{<obj>:^10} # ' <obj> '
418-
{<obj>:>10} # ' <obj>'
419-
{<obj>:.<10} # '<obj>.....'
420-
{<obj>:0} # '<obj>'
416+
{<obj>:<10} # '<obj> '.
417+
{<obj>:^10} # ' <obj> '.
418+
{<obj>:>10} # ' <obj>'.
419+
{<obj>:.<10} # '<obj>.....'.
420+
{<obj>:0} # '<obj>'.
421421
```
422422
* **Objects are converted to strings with format() function, e.g. `'format(<obj>, "<10")'`.**
423423
* **Options can be generated dynamically via nested braces: `f'{<obj>:{<str/int>}[…]}'`.**
@@ -426,29 +426,29 @@ Format
426426

427427
### Strings
428428
```python
429-
{'abcde':10} # 'abcde '
430-
{'abcde':10.3} # 'abc '
431-
{'abcde':.3} # 'abc'
432-
{'abcde'!r:10} # "'abcde' "
429+
{'abcde':10} # 'abcde '.
430+
{'abcde':10.3} # 'abc '.
431+
{'abcde':.3} # 'abc'.
432+
{'abcde'!r:10} # "'abcde' ".
433433
```
434434

435435
### Numbers
436436
```python
437-
{123456:10} # ' 123456'
438-
{123456:10,} # ' 123,456'
439-
{123456:10_} # ' 123_456'
440-
{123456:+10} # ' +123456'
441-
{123456:=+10} # '+ 123456'
442-
{123456: } # ' 123456'
443-
{-123456: } # '-123456'
437+
{123456:10} # ' 123456'.
438+
{123456:10,} # ' 123,456'.
439+
{123456:10_} # ' 123_456'.
440+
{123456:+10} # ' +123456'.
441+
{123456:=+10} # '+ 123456'.
442+
{123456: } # ' 123456'.
443+
{-123456: } # '-123456'.
444444
```
445445

446446
### Floats
447447
```python
448-
{1.23456:10.3} # ' 1.23'
449-
{1.23456:10.3f} # ' 1.235'
450-
{1.23456:10.3e} # ' 1.235e+00'
451-
{1.23456:10.3%} # ' 123.456%'
448+
{1.23456:10.3} # ' 1.23'.
449+
{1.23456:10.3f} # ' 1.235'.
450+
{1.23456:10.3e} # ' 1.235e+00'.
451+
{1.23456:10.3%} # ' 123.456%'.
452452
```
453453

454454
#### Comparison of presentation types:
@@ -480,7 +480,8 @@ Format
480480
+--------------+----------------+----------------+----------------+----------------+
481481
```
482482
* **`'{<num>:g}'` is `'{<float>:.6}'` that strips `'.0'` and has exponent starting at `'1e+06'`.**
483-
* **When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. Hence `'{6.5:.0f}'` becomes a `'6'`, while `'{7.5:.0f}'` an `'8'`. This rule only effects numbers that can be represented exactly by a float (`.5`, `.25`, …).**
483+
* **When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. Hence `'{6.5:.0f}'` becomes a `'6'`, while `'{7.5:.0f}'` an `'8'`.**
484+
* **The last rule only effects numbers that can be represented exactly by a float (`.5`, `.25`, …).**
484485

485486
### Ints
486487
```python
@@ -598,10 +599,10 @@ import zoneinfo, dateutil.tz
598599
```
599600

600601
```python
601-
<D> = date(year, month, day) # Accepts valid dates between AD 1 and AD 9999.
602-
<T> = time(hour=0, minute=0, second=0) # Also: `microsecond=0, tzinfo=None, fold=0`.
603-
<DT> = datetime(year, month, day, hour=0) # Also: `minute=0, second=0, microsecond=0, …`.
604-
<TD> = timedelta(weeks=0, days=0, hours=0) # Also: `minutes=0, seconds=0, microseconds=0`.
602+
<D> = date(year, month, day) # Only accepts valid dates between AD 1 and 9999.
603+
<T> = time(hour=0, minute=0, second=0) # Accepts `microsecond=0, tzinfo=None, fold=0`.
604+
<DT> = datetime(year, month, day, hour=0) # Accepts `minute=0, second=0, microsecond=0, …`.
605+
<TD> = timedelta(weeks=0, days=0, hours=0) # Accepts `minutes=0, seconds=0, microseconds=0`.
605606
```
606607
* **Times and datetimes that have defined timezone are called aware and ones that don't, naive. If time or datetime object is naive, it is presumed to be in the system's timezone!**
607608
* **`'fold=1'` means the second pass in case of time jumping back (usually for one hour).**
@@ -671,10 +672,11 @@ import zoneinfo, dateutil.tz
671672
Function
672673
--------
673674
**Independent block of code that returns a value when called.**
675+
674676
```python
675-
def <func_name>(<nondefault_args>): ... # E.g. `def func(x, y): ...`.
676-
def <func_name>(<default_args>): ... # E.g. `def func(x=0, y=0): ...`.
677-
def <func_name>(<nondefault_args>, <default_args>): ... # E.g. `def func(x, y=0): ...`.
677+
def <func_name>(<nondefault_args>): ... # E.g. `func(x, y):`.
678+
def <func_name>(<default_args>): ... # E.g. `func(x=0, y=0):`.
679+
def <func_name>(<nondefault_args>, <default_args>): ... # E.g. `func(x, y=0):`.
678680
```
679681
* **Function returns None if it doesn't encounter the `'return <object/expr>'` statement.**
680682
* **Run `'global <var_name>'` inside the function before assigning to the global variable.**
@@ -820,13 +822,14 @@ Imports
820822
**Mechanism that makes code in one file available to another file.**
821823

822824
```python
823-
import <module> # Imports a built-in or '<module>.py'.
824-
import <package> # Imports a built-in or '<package>/__init__.py'.
825-
import <package>.<module> # Imports a built-in or '<package>/<module>.py'.
825+
import <module> # Imports a built-in module or the '<module>.py'.
826+
import <package> # A built-in package or '<package>/__init__.py'.
827+
import <package>.<module> # A package's module or '<package>/<module>.py'.
828+
from <pkg/mod>[.…] import <obj> # Imports a module, function, variable or class.
826829
```
827-
* **Package is a collection of modules, but it can also define its own functions, classes, etc. On a filesystem this corresponds to a directory of Python files with an optional init script.**
828-
* **Running `'import <package>'` does not automatically provide access to the package's modules unless they are explicitly imported in the `'<package>/__init__.py'` script.**
829-
* **Directory of the file that is passed to python command serves as a root of local imports.**
830+
* **Package is a collection of modules, but it can also define its own functions, variables, etc. On a filesystem this corresponds to a directory of Python files with an optional init script.**
831+
* **`'import <package>'` only exposes modules that are imported inside `'__init__.py'`.**
832+
* **Directory of the file that is passed to python command serves as the root of local imports.**
830833
* **Use relative imports, i.e. `'from .[…][<pkg/mod>[.…]] import <obj>'`, if project has scattered entry points. Another option is to install the whole project by moving its code into 'src' dir, adding ['pyproject.toml'](https://packaging.python.org/en/latest/guides/writing-pyproject-toml/#basic-information) to its root, and running `'$ pip3 install -e .'`.**
831834

832835

@@ -1699,7 +1702,7 @@ import os, shutil
16991702
```
17001703

17011704
```python
1702-
os.chdir(<path>) # Changes the current working directory (CWD).
1705+
os.chdir(<path>) # Changes the current working directory (or CWD).
17031706
os.mkdir(<path>, mode=0o777) # Creates a directory. Permissions are in octal.
17041707
os.makedirs(<path>, mode=0o777) # Creates all path's dirs. Also `exist_ok=False`.
17051708
```
@@ -2099,14 +2102,14 @@ import operator as op
20992102
```
21002103

21012104
```python
2102-
<bool> = op.not_(<obj>) # or, and, not (or/and missing)
2103-
<bool> = op.eq/ne/lt/ge/is_/is_not/contains(<obj>, <obj>) # ==, !=, <, >=, is, is not, in
2104-
<obj> = op.or_/xor/and_(<int/set>, <int/set>) # |, ^, & (sorted by precedence)
2105-
<int> = op.lshift/rshift(<int>, <int>) # <<, >> (i.e. <int> << n_bits)
2106-
<obj> = op.add/sub/mul/truediv/floordiv/mod(<obj>, <obj>) # +, -, *, /, //, % (two groups)
2107-
<num> = op.neg/invert(<num>) # -, ~ (negate and bitwise not)
2108-
<num> = op.pow(<num>, <num>) # ** (pow() accepts 3 arguments)
2109-
<func> = op.itemgetter/attrgetter/methodcaller(<obj> [, ...]) # [index/key], .name, .name([…])
2105+
<bool> = op.not_(<obj>) # or, and, not (or/and missing).
2106+
<bool> = op.eq/ne/lt/ge/is_/is_not/contains(<obj>, <obj>) # ==, !=, <, >=, is, is not, in.
2107+
<obj> = op.or_/xor/and_(<int/set>, <int/set>) # |, ^, & (sorted by precedence).
2108+
<int> = op.lshift/rshift(<int>, <int>) # <<, >> (i.e. <int> << n_bits).
2109+
<obj> = op.add/sub/mul/truediv/floordiv/mod(<obj>, <obj>) # +, -, *, /, //, % (two groups).
2110+
<num> = op.neg/invert(<num>) # -, ~ (negate and bitwise not).
2111+
<num> = op.pow(<num>, <num>) # ** (pow() accepts 3 arguments).
2112+
<func> = op.itemgetter/attrgetter/methodcaller(<obj> [, ]) # [index/key], .name, .name([…]).
21102113
```
21112114

21122115
```python
@@ -2201,7 +2204,7 @@ log.basicConfig(
22012204
* **An object with `'filter(<LogRecord>)'` method (or the method itself) can be added to loggers and handlers via addFilter(). Message is dropped if filter() returns a false value.**
22022205
* **Logging messages generated by libraries are passed to the root's handlers. Level of the library's logger can be set with `'log.getLogger("<library>").setLevel(<str>)'`.**
22032206

2204-
#### Creates a logger that writes all messages to a file and sends them to the root's handler that prints warnings or higher:
2207+
#### Logger that writes messages to file and sends them to the root's handler that prints warnings or higher:
22052208
```python
22062209
>>> logger = log.getLogger('my_module')
22072210
>>> handler = log.FileHandler('test.log', encoding='utf-8')
@@ -2212,10 +2215,10 @@ log.basicConfig(
22122215
>>> log.basicConfig()
22132216
>>> roots_handler = log.root.handlers[0]
22142217
>>> roots_handler.setLevel('WARNING')
2215-
>>> logger.critical('Running out of disk space.')
2216-
CRITICAL:my_module:Running out of disk space.
2218+
>>> logger.critical('Missing config file.')
2219+
CRITICAL:my_module:Missing config file.
22172220
>>> print(open('test.log').read())
2218-
2023-02-07 23:21:01,430 CRITICAL:my_module:Running out of disk space.
2221+
2023-02-07 23:21:01,430 CRITICAL:my_module:Missing config file.
22192222
```
22202223

22212224

@@ -2402,11 +2405,11 @@ Plot
24022405
# $ pip3 install matplotlib
24032406
import matplotlib.pyplot as plt
24042407

2405-
plt.plot/bar/scatter(x_data, y_data [, label=<str>]) # Accepts plt.plot(y_data).
2406-
plt.legend() # Adds a legend of labels.
2407-
plt.title/xlabel/ylabel(<str>) # Adds title or axis label.
2408-
plt.show() # Also plt.savefig(<path>).
2409-
plt.clf() # Clears the plot (figure).
2408+
plt.plot/bar/scatter(x_data, y_data, label=None) # Accepts plt.plot(y_data).
2409+
plt.legend() # Adds a legend of labels.
2410+
plt.title/xlabel/ylabel(<str>) # Adds title or axis label.
2411+
plt.show() # Also plt.savefig(<path>).
2412+
plt.clf() # Clears the plot (figure).
24102413
```
24112414

24122415

@@ -2855,21 +2858,21 @@ import wave
28552858
```
28562859

28572860
```python
2858-
<Wave> = wave.open('<path>') # Opens specified WAV file for reading.
2859-
<int> = <Wave>.getframerate() # Returns number of frames per second.
2860-
<int> = <Wave>.getnchannels() # Returns number of samples per frame.
2861-
<int> = <Wave>.getsampwidth() # Returns number of bytes per sample.
2862-
<tuple> = <Wave>.getparams() # Returns namedtuple of all parameters.
2863-
<bytes> = <Wave>.readframes(nframes) # Returns all frames if `-1` is passed.
2861+
<Wave> = wave.open('<path>') # Opens specified WAV file for reading.
2862+
<int> = <Wave>.getframerate() # Returns number of frames per second.
2863+
<int> = <Wave>.getnchannels() # Returns number of samples per frame.
2864+
<int> = <Wave>.getsampwidth() # Returns number of bytes per sample.
2865+
<tuple> = <Wave>.getparams() # Returns namedtuple of all parameters.
2866+
<bytes> = <Wave>.readframes(nframes) # Returns all frames if `-1` is passed.
28642867
```
28652868

28662869
```python
2867-
<Wave> = wave.open('<path>', 'wb') # Creates/truncates a file for writing.
2868-
<Wave>.setframerate(<int>) # Pass 44100, or 48000 for video track.
2869-
<Wave>.setnchannels(<int>) # Pass 1 for mono, 2 for stereo signal.
2870-
<Wave>.setsampwidth(<int>) # Pass 2 for CD, 3 for hi-res quality.
2871-
<Wave>.setparams(<tuple>) # Passed tuple must contain all params.
2872-
<Wave>.writeframes(<bytes>) # Appends passed frames to audio file.
2870+
<Wave> = wave.open('<path>', 'wb') # Creates/truncates a file for writing.
2871+
<Wave>.setframerate(<int>) # Pass 44100, or 48000 for video track.
2872+
<Wave>.setnchannels(<int>) # Pass 1 for mono, 2 for stereo signal.
2873+
<Wave>.setsampwidth(<int>) # Pass 2 for CD, 3 for hi-res quality.
2874+
<Wave>.setparams(<tuple>) # Passed tuple must contain all params.
2875+
<Wave>.writeframes(<bytes>) # Appends passed frames to audio file.
28732876
```
28742877
* **The bytes object contains a sequence of frames, each consisting of one or more samples.**
28752878
* **In stereo signal, first sample of a frame belongs to the left channel (second to the right).**

0 commit comments

Comments
 (0)