From 62b4b491d97d42452664403cfbbe2d0adb8b2b5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 1 Feb 2026 20:49:20 +0100 Subject: [PATCH 01/59] Open, Coroutines, Audio --- README.md | 10 +++++----- index.html | 14 +++++++------- pdf/remove_links.py | 2 +- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 2d0cf6d6f..513ff1ab9 100644 --- a/README.md +++ b/README.md @@ -1577,7 +1577,7 @@ Open * **`'FileNotFoundError'` can be raised when reading with `'r'` or `'r+'`.** * **`'FileExistsError'` exception can be raised when writing with `'x'`.** * **`'IsADirectoryError'`, `'PermissionError'` can be raised by any.** -* **`'OSError'` is the parent class of all listed exceptions.** +* **`'except OSError [as ]: …'` catches all listed exceptions.** ### File Object ```python @@ -1725,7 +1725,7 @@ os.rmdir() # Deletes the empty directory or raises OSError shutil.rmtree() # Deletes the directory and all of its contents. ``` * **Provided paths can be either strings, Path objects, or DirEntry objects.** -* **Functions report OS related errors by raising OSError or one of its [subclasses](#exceptions-1).** +* **Functions report errors by raising OSError or one of its [subclasses](#exceptions-1).** Shell Commands @@ -2325,7 +2325,7 @@ import asyncio as aio ```python = aio.gather(, ...) # Schedules coros. Returns list of results on await. = aio.wait(, return_when=…) # `'ALL/FIRST_COMPLETED'`. Returns (done, pending). - = aio.as_completed() # Iter of coros. Each returns next result on await. + = aio.as_completed() # Calling `await next()` returns next result. ``` #### Runs a terminal game where you control an asterisk that must avoid numbers: @@ -2928,9 +2928,9 @@ write_to_wav_file('test.wav', (get_sin(i) for i in range(100_000))) #### Adds noise to the WAV file: ```python from random import uniform -samples_f, params = read_wav_file('test.wav') +samples_f, prms = read_wav_file('test.wav') samples_f = (f + uniform(-0.02, 0.02) for f in samples_f) -write_to_wav_file('test.wav', samples_f, p=params) +write_to_wav_file('test.wav', samples_f, p=prms) ``` ### Audio Player diff --git a/index.html b/index.html index 8619d3bd0..9a7f7728a 100644 --- a/index.html +++ b/index.html @@ -56,7 +56,7 @@
- +
@@ -1353,7 +1353,7 @@
  • 'FileNotFoundError' can be raised when reading with 'r' or 'r+'.
  • 'FileExistsError' exception can be raised when writing with 'x'.
  • 'IsADirectoryError', 'PermissionError' can be raised by any.
  • -
  • 'OSError' is the parent class of all listed exceptions.
  • +
  • 'except OSError [as <name>]: …' catches all listed exceptions.
  • File Object

    <file>.seek(0)                      # Moves current position to the start of file.
     <file>.seek(offset)                 # Moves 'offset' chars/bytes from the start.
     <file>.seek(0, 2)                   # Moves current position to the end of file.
    @@ -1459,7 +1459,7 @@
     
    • Provided paths can be either strings, Path objects, or DirEntry objects.
    • -
    • Functions report OS related errors by raising OSError or one of its subclasses.
    • +
    • Functions report errors by raising OSError or one of its subclasses.

    #Shell Commands

    import os, subprocess, shlex
     
    @@ -1917,7 +1917,7 @@

    Format

    <coro> = aio.gather(<coro/task>, ...) # Schedules coros. Returns list of results on await. <coro> = aio.wait(<tasks>, return_when=…) # `'ALL/FIRST_COMPLETED'`. Returns (done, pending). -<iter> = aio.as_completed(<coros/tasks>) # Iter of coros. Each returns next result on await. +<iter> = aio.as_completed(<coros/tasks>) # Calling `await next(<iter>)` returns next result.

    Runs a terminal game where you control an asterisk that must avoid numbers:

    import asyncio, collections, curses, curses.textpad, enum, random
     
    @@ -2401,9 +2401,9 @@ 

    Format

    Adds noise to the WAV file:

    from random import uniform
    -samples_f, params = read_wav_file('test.wav')
    +samples_f, prms = read_wav_file('test.wav')
     samples_f = (f + uniform(-0.02, 0.02) for f in samples_f)
    -write_to_wav_file('test.wav', samples_f, p=params)
    +write_to_wav_file('test.wav', samples_f, p=prms)
     

    Audio Player

    # $ pip3 install nava
    @@ -2935,7 +2935,7 @@ 

    Format

      -
    • Timezones returned by tzlocal(), ZoneInfo() and implicit local timezone of naive objects have offsets that vary through time due to DST and historical changes of the base offset.
    • +
    • Timezones returned by tzlocal(), ZoneInfo(), and implicit local timezone of naive objects have offsets that vary through time due to DST and historical changes of the base offset.
    • To get ZoneInfo() to work on Windows run '> pip3 install tzdata'.

    Encode

    <D/T/DT> = D/T/DT.fromisoformat(<str>)      # Object from the ISO string. Raises ValueError.
    @@ -1029,7 +1029,7 @@
     

    Context Manager

    • With statements only work on objects that have enter() and exit() special methods.
    • -
    • Enter() should lock the resources and optionally return an object (file, lock, etc.).
    • +
    • Enter() should lock the resources and optionally return an object (file, socket, etc.).
    • Exit() should release the resources (for example close a file, release a lock, etc.).
    • Any exception that happens inside the with block is passed to the exit() method.
    • The exit() method can suppress the exception by returning a true value.
    • @@ -1660,14 +1660,14 @@
    • System’s type sizes, byte order, and alignment rules are used by default.
    from struct import pack, unpack
     
    -<bytes> = pack('<format>', <el_1> [, ...])  # Packs numbers according to format.
    -<tuple> = unpack('<format>', <bytes>)       # Use `iter_unpack()` to get tuples.
    +<bytes> = pack('<format>', <num_1>, ...)  # Packs numbers according to format.
    +<tuple> = unpack('<format>', <bytes>)     # Use `iter_unpack()` to get tuples.
     
    >>> pack('>hhl', 1, 2, 3)
     b'\x00\x01\x00\x02\x00\x00\x00\x03'
    ->>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
    +>>> unpack('bhh', b'\x01\x00\x02\x00\x03\x00')
     (1, 2, 3)
     

    Format

    For standard type sizes and manual alignment (padding) start format string with:

      @@ -2935,7 +2935,7 @@

      Format

    Callable

    • All functions and classes have a call() method that is executed when they are called.
    • -
    • Use 'callable(<obj>)' or 'isinstance(<obj>, collections.abc.Callable)' to check if object is callable. You can also call the object and check if it raised TypeError.
    • -
    • When this cheatsheet uses '<function>' as an argument, it means '<callable>'.
    • +
    • Use 'callable(<obj>)' or 'isinstance(<obj>, collections.abc.Callable)' to check if object is callable. You can also call the object and see if it raised TypeError.
    • +
    • When this text uses '<function>' as an argument, it actually means '<callable>'.
    class Counter:
         def __init__(self):
             self.i = 0
    @@ -1030,9 +1030,8 @@
     

    Context Manager

    • With statements only work on objects that have enter() and exit() special methods.
    • Enter() should lock the resources and optionally return an object (file, socket, etc.).
    • -
    • Exit() should release the resources (for example close a file, release a lock, etc.).
    • -
    • Any exception that happens inside the with block is passed to the exit() method.
    • -
    • The exit() method can suppress the exception by returning a true value.
    • +
    • Exit() should release the resources (for example close the file, release the lock, etc.).
    • +
    • Any exception that happens inside the with block is passed to exit() method. Exit() method can then suppress that exception by returning a true value (None is false).
    class MyOpen:
         def __init__(self, filename):
             self.filename = filename
    @@ -1141,7 +1140,7 @@
     
      -
    • Method iter() is required for 'isinstance(<obj>, abc.Iterable)' to return True, however any object with getitem() will work with any code expecting an iterable.
    • +
    • Method iter() is required for 'isinstance(<obj>, abc.Iterable)' to return True, however any object with getitem() method works with any code expecting an iterable.
    • MutableSequence, Set, MutableSet, Mapping and MutableMapping ABCs are also ex­tendable. Use '<abc>.__abstractmethods__' to get names of required methods.

    #Enum

    Class of named constants called members.

    from enum import Enum, auto
    @@ -1203,7 +1202,7 @@
     
  • Code inside the 'else' block will only be executed if 'try' block had no exceptions.
  • Code inside the 'finally' block will always be executed (unless a signal is received).
  • All variables that are initialized in executed blocks are also visible in all subsequent blocks, as well as outside the try statement (only the function block delimits scope).
  • -
  • To catch signals use 'signal.signal(signal_number, handler_function)'.
  • +
  • To catch signals use 'signal.signal(signal_number, my_handler_function)'.
  • Catching Exceptions

    except <exception>: ...
     except <exception> as <name>: ...
    @@ -1214,8 +1213,8 @@
     
    • It also catches subclasses, e.g. 'ArithmeticError' is caught by 'except Exception:'.
    • 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 (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.
    • +
    • Use 'print(<name>)' to print just the cause of the exception (its arguments) to stdout.
    • +
    • Use 'logging.exception(<str>)' to log the passed message, followed by the full error message of the caught exception. For details about how to set up the logger see Logging.
    • Use 'sys.exc_info()' to get exception type, object, and traceback of caught exception.

    Raising Exceptions

    raise <exception>
    @@ -2935,7 +2934,7 @@ 

    Format

    Counter

    >>> from collections import Counter
    ->>> counter = Counter(['blue', 'blue', 'blue', 'red', 'red'])
    ->>> counter['yellow'] += 1
    +>>> counter = Counter(['blue', 'blue', 'red'])
    +>>> counter['yellow'] += 3
     >>> print(counter.most_common())
    -[('blue', 3), ('red', 2), ('yellow', 1)]
    +[('yellow', 3), ('blue', 2), ('red', 1)]
     

    #Set

    <set> = {<el_1>, <el_2>, ...}           # Coll. of unique items. Also set(), set(<coll>).
    @@ -1031,7 +1031,7 @@
     
  • With statements only work on objects that have enter() and exit() special methods.
  • Enter() should lock the resources and optionally return an object (file, socket, etc.).
  • Exit() should release the resources (for example close the file, release the lock, etc.).
  • -
  • Any exception that happens inside the with block is passed to exit() method. Exit() method can then suppress that exception by returning a true value (None is false).
  • +
  • Any exception that happens inside the with block is passed to exit() method. Exit() can then suppress the exception by returning a true value (not None, False, 0, etc.).
  • class MyOpen:
         def __init__(self, filename):
             self.filename = filename
    @@ -1246,18 +1246,18 @@
           ├── EOFError                # Raised by `input()` when it hits an end-of-file condition.
           ├── LookupError             # Base class for errors when a collection can't find an item.
           │    ├── IndexError         # Raised when index of a sequence (list/str) is out of range.
    -      │    └── KeyError           # Raised when a dictionary key or a set element is missing.
    +      │    └── KeyError           # Raised when a dictionary's key or a set element is missing.
           ├── MemoryError             # Out of memory. May be too late to start deleting variables.
           ├── NameError               # Raised when nonexistent name (variable/func/class) is used.
    -      │    └── UnboundLocalError  # Raised when local name is used before it is being defined.
    +      │    └── UnboundLocalError  # Raised when a local name is used before it's being defined.
           ├── OSError                 # Errors such as FileExistsError and TimeoutError. See #Open.
           │    └── ConnectionError    # Errors such as BrokenPipeError and ConnectionAbortedError.
           ├── RuntimeError            # Is raised by errors that do not fit into other categories.
           │    ├── NotImplementedEr…  # Can be raised by abstract methods or by an unfinished code.
           │    └── RecursionError     # Raised if max recursion depth is exceeded (3k by default).
           ├── StopIteration           # Raised when exhausted (empty) iterator is passed to next().
    -      ├── TypeError               # When an argument of the wrong type is passed to function.
    -      └── ValueError              # When argument has the right type but inappropriate value.
    +      ├── TypeError               # Raised when argument of wrong type is passed to a function.
    +      └── ValueError              # Raised when it has the right type but inappropriate value.
     

    Collections and their exceptions:

    ┏━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
    @@ -1270,7 +1270,7 @@
     ┗━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
     
    -

    Useful built-in exceptions:

    raise TypeError('Passed argument is of the wrong type!')
    +

    Useful built-in exceptions:

    raise TypeError('Function received argument of the wrong type!')
     raise ValueError('Argument has the right type but its value is off!')
     raise RuntimeError('I am too lazy to define my own exception!')
     
    @@ -1823,7 +1823,7 @@

    Format

    '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.
  • 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>)'.
  • -

    Logger that writes messages to file and sends them to the root's handler that prints warnings or higher:

    >>> logger = log.getLogger('my_module')
    +

    Logger that writes messages to a file and sends them to the root's handler that prints warnings or higher:

    >>> logger = log.getLogger('my_module')
     >>> handler = log.FileHandler('test.log', encoding='utf-8')
     >>> format_str = '%(asctime)s %(levelname)s:%(name)s:%(message)s'
     >>> handler.setFormatter(log.Formatter(format_str))
    @@ -2031,8 +2031,8 @@ 

    Format

    '100', enable_events=True, key='QUANTITY') dropdown = sg.InputCombo(['g', 'kg', 't'], 'kg', readonly=True, enable_events=True, k='UNIT') -label = sg.Text('100 kg is 220.462 lbs.', key='OUTPUT') -window = sg.Window('Weight Converter', [[text_box, dropdown], [label], [sg.Button('Close')]]) +label = sg.Text('100 kg is 220.462 lbs.', key='OUTPUT') +window = sg.Window('GUI App', [[text_box, dropdown], [label], [sg.Button('Close')]]) while True: event, values = window.read() @@ -2934,7 +2934,7 @@

    Format