[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-1339":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":16,"stars7d":17,"stars30d":18,"stars90d":15,"forks30d":15,"starsTrendScore":19,"compositeScore":20,"rankGlobal":10,"rankLanguage":10,"license":10,"archived":21,"fork":21,"defaultBranch":22,"hasWiki":23,"hasPages":23,"topics":24,"createdAt":10,"pushedAt":10,"updatedAt":28,"readmeContent":29,"aiSummary":30,"trendingCount":15,"starSnapshotCount":15,"syncStatus":31,"lastSyncTime":32,"discoverSource":33},1339,"python-cheatsheet","gto76\u002Fpython-cheatsheet","gto76","Comprehensive Python Cheatsheet","https:\u002F\u002Fgto76.github.io\u002Fpython-cheatsheet\u002F",null,"Python",38471,6709,961,0,5,22,78,18,45,false,"main",true,[25,26,5,27],"cheatsheet","python","reference","2026-06-12 02:00:26","Comprehensive Python Cheatsheet\n===============================\n\u003Csup>[Download text file](https:\u002F\u002Fraw.githubusercontent.com\u002Fgto76\u002Fpython-cheatsheet\u002Fmain\u002FREADME.md), [Fork me on GitHub](https:\u002F\u002Fgithub.com\u002Fgto76\u002Fpython-cheatsheet) or [Check out FAQ](https:\u002F\u002Fgithub.com\u002Fgto76\u002Fpython-cheatsheet\u002Fwiki\u002FFrequently-Asked-Questions).\n\u003C\u002Fsup>\n\n![Monty Python](web\u002Fimage_888.jpeg)\n\n\nContents\n--------\n**&nbsp;&nbsp;&nbsp;** **1. Collections:** **&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;** **[`List`](#list)**__,__ **[`Dictionary`](#dictionary)**__,__ **[`Set`](#set)**__,__ **[`Tuple`](#tuple)**__,__ **[`Range`](#range)**__,__ **[`Enumerate`](#enumerate)**__,__ **[`Iterator`](#iterator)**__,__ **[`Generator`](#generator)**__.__  \n**&nbsp;&nbsp;&nbsp;** **2. Data Types:** **&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**  **[`Type`](#type)**__,__ **[`String`](#string)**__,__ **[`Regular_Exp`](#regex)**__,__ **[`Format`](#format)**__,__ **[`Numbers`](#numbers-1)**__,__ **[`Combinatorics`](#combinatorics)**__,__ **[`Datetime`](#datetime)**__.__  \n**&nbsp;&nbsp;&nbsp;** **3. Syntax Rules:** **&nbsp;&nbsp;&nbsp;**  **[`Function`](#function)**__,__ **[`Inline`](#inline)**__,__ **[`Import`](#import)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Type`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Except`](#exceptions)**__.__  \n**&nbsp;&nbsp;&nbsp;** **4. System Calls:** **&nbsp;&nbsp;&nbsp;**  **[`Exit`](#exit)**__,__ **[`Print`](#print)**__,__ **[`Input`](#input)**__,__ **[`Command_Line_Arguments`](#command-line-arguments)**__,__ **[`Open`](#open)**__,__ **[`Path`](#paths)**__,__ **[`OS_Commands`](#os-commands)**__.__  \n**&nbsp;&nbsp;&nbsp;** **5. Data Formats:** **&nbsp;**  **[`JSON`](#json)**__,__ **[`Pickle`](#pickle)**__,__ **[`CSV`](#csv)**__,__ **[`SQLite`](#sqlite)**__,__ **[`Bytes`](#bytes)**__,__ **[`Struct`](#struct)**__,__ **[`Array`](#array)**__,__ **[`Memory_View`](#memory-view)**__,__ **[`Deque`](#deque)**__.__  \n**&nbsp;&nbsp;&nbsp;** **6. Misc Topics:** **&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**  **[`Operator`](#operator)**__,__ **[`Match_Statement`](#match-statement)**__,__ **[`Logging`](#logging)**__,__ **[`Introspection`](#introspection)**__,__ **[`Threads`](#threading)**__,__ **[`Asyncio`](#asyncio)**__.__  \n**&nbsp;&nbsp;&nbsp;** **7. OS Libraries:** **&nbsp;&nbsp;&nbsp;&nbsp;**  **[`Progress_Bar`](#progress-bar)**__,__ **[`Plot`](#plot)**__,__ **[`Table`](#table)**__,__ **[`Console_App`](#console-app)**__,__ **[`GUI`](#gui-app)**__,__ **[`Scraping`](#scraping)**__,__ **[`Web`](#web-app)**__,__ **[`Profile`](#profiling)**__.__  \n**&nbsp;&nbsp;&nbsp;** **8. Multimedia:** **&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**  **[`NumPy`](#numpy)**__,__ **[`Image`](#image)**__,__ **[`Animation`](#animation)**__,__ **[`Audio`](#audio)**__,__ **[`Synthesizer`](#synthesizer)**__,__ **[`Pygame`](#pygame)**__,__ **[`Pandas`](#pandas)**__,__ **[`Plotly`](#plotly)**__.__\n\n\nMain\n----\n```python\nif __name__ == '__main__':      # Skips indented lines of code if file was imported.\n    main()                      # Executes user-defined `def main(): ...` function.\n```\n\n\nList\n----\n```python\n\u003Clist> = [\u003Cel_1>, \u003Cel_2>, ...]  # Creates new list object. E.g. `list_a = [1, 2, 3]`.\n```\n\n```python\n\u003Cel>   = \u003Clist>[index]          # First index is 0, last -1. Also `\u003Clist>[i] = \u003Cel>`.\n\u003Clist> = \u003Clist>[\u003Cslice>]        # Also \u003Clist>[from_inclusive : to_exclusive : ±step].\n```\n\n```python\n\u003Clist>.append(\u003Cel>)             # Appends element to the end. Also `\u003Clist> += [\u003Cel>]`.\n\u003Clist>.extend(\u003Ccollection>)     # Appends multiple elements. Also `\u003Clist> += \u003Ccoll>`.\n```\n\n```python\n\u003Clist>.sort(reverse=False)      # Sorts the elements of the list in ascending order.\n\u003Clist>.reverse()                # Reverses the order of elements. Takes linear time.\n\u003Clist> = sorted(\u003Ccollection>)   # Returns a new sorted list. Accepts `reverse=True`.\n\u003Citer> = reversed(\u003Clist>)       # Returns reversed iterator. Also list(\u003Citerator>).\n```\n\n```python\n\u003Cel>  = max(\u003Ccollection>)       # Returns the largest element. Also min(\u003Cel_1>, ...).\n\u003Cnum> = sum(\u003Ccollection>)       # Returns a sum of elements. Also math.prod(\u003Ccoll>).\n```\n\n```python\nelementwise_sum  = [sum(pair) for pair in zip(list_a, list_b)]\nsorted_by_second = sorted(\u003Ccoll>, key=lambda pair: pair[1])\nsorted_by_both   = sorted(\u003Ccoll>, key=lambda p: (p[1], p[0]))\nflatter_list     = list(itertools.chain.from_iterable(\u003Clist>))\n```\n* **For details about sort(), sorted(), max() and min() see [Sortable](#sortable).**\n* **Module [operator](#operator) has function itemgetter() that can replace listed [lambdas](#lambda).**\n* **This text uses the term collection instead of [iterable](#abstract-base-classes). For rationale see [duck types](#iterable-duck-types).**\n\n```python\n\u003Cint> = len(\u003Clist\u002Fdict\u002Fset\u002F…>)  # Returns number of items. Doesn't accept iterators.\n\u003Cint> = \u003Clist>.count(\u003Cel>)      # Counts occurrences. Also `if \u003Cel> in \u003Ccoll>: ...`.\n\u003Cint> = \u003Clist>.index(\u003Cel>)      # Returns index of first occ. or raises ValueError.\n\u003Cel>  = \u003Clist>.pop()            # Removes item from the end (or at index if passed).\n\u003Clist>.insert(\u003Cint>, \u003Cel>)      # Inserts item at index and shifts remaining items.\n\u003Clist>.remove(\u003Cel>)             # Removes the first occurrence or raises ValueError.\n\u003Clist>.clear()                  # Removes all items. Also provided by dict and set.\n```\n\n\nDictionary\n----------\n```python\n\u003Cdict> = {key_1: val_1, key_2: val_2, ...}      # Use `\u003Cdict>[key]` to get or assign the value.\n```\n\n```python\n\u003Cview> = \u003Cdict>.keys()                          # A collection of keys reflecting all changes.\n\u003Cview> = \u003Cdict>.values()                        # A collection of values that reflects changes.\n\u003Cview> = \u003Cdict>.items()                         # Coll. of tuples. Each contains key and value.\n```\n\n```python\nvalue  = \u003Cdict>.get(key, default=None)          # Returns 'default' argument if key is missing.\nvalue  = \u003Cdict>.setdefault(key, default=None)   # Returns\u002Fwrites 'default' when key is missing.\n\u003Cdict> = collections.defaultdict(\u003Ctype>)        # Dict with automatic default value `\u003Ctype>()`.\n\u003Cdict> = collections.defaultdict(lambda: 1)     # Dictionary with automatic default value `1`.\n```\n\n```python\n\u003Cdict> = dict(\u003Ccollection>)                     # Creates a dict from coll. of key-value pairs.\n\u003Cdict> = dict(zip(keys, values))                # Creates key-value pairs from two collections.\n\u003Cdict> = dict.fromkeys(keys [, value])          # Items get value None if only keys are passed.\n```\n\n```python\n\u003Cdict>.update(\u003Cdict>)                           # Adds items to dict. Passed dict has priority.\nvalue = \u003Cdict>.pop(key)                         # Removes item or raises KeyError when missing.\n{k for k, v in \u003Cdict>.items() if v == 123}      # Returns a set of keys whose value equals 123.\n{k: v for k, v in \u003Cdict>.items() if k in keys}  # Returns a dict of items with specified keys.\n```\n\n### Counter\n```python\n>>> from collections import Counter\n>>> counter = Counter(['blue', 'blue', 'red'])\n>>> counter['yellow'] += 3\n>>> print(counter.most_common())\n[('yellow', 3), ('blue', 2), ('red', 1)]\n```\n\n\nSet\n---\n```python\n\u003Cset> = {\u003Cel_1>, \u003Cel_2>, ...}           # Coll. of unique items. Also set(), set(\u003Ccoll>).\n```\n\n```python\n\u003Cset>.add(\u003Cel>)                         # Adds item to the set. Same as `\u003Cset> |= {\u003Cel>}`.\n\u003Cset>.update(\u003Ccollection> [, ...])      # Adds items to the set. Same as `\u003Cset> |= \u003Cset>`.\n```\n\n```python\n\u003Cset>  = \u003Cset>.union(\u003Ccoll>)            # Returns a set of all items. Also \u003Cset> | \u003Cset>.\n\u003Cset>  = \u003Cset>.intersection(\u003Ccoll>)     # Returns every shared item. Also \u003Cset> & \u003Cset>.\n\u003Cset>  = \u003Cset>.difference(\u003Ccoll>)       # Returns set's unique items. Also \u003Cset> - \u003Cset>.\n\u003Cset>  = \u003Cset>.symmetric_diff…(\u003Ccoll>)  # Returns all nonshared items. Also \u003Cset> ^ \u003Cset>.\n\u003Cbool> = \u003Cset>.issuperset(\u003Ccoll>)       # Returns False when collection has unique items.\n\u003Cbool> = \u003Cset>.issubset(\u003Ccoll>)         # Is collection a superset? Also \u003Cset> \u003C= \u003Cset>.\n```\n\n```python\n\u003Cel> = \u003Cset>.pop()                      # Removes one of items. Raises KeyError if empty.\n\u003Cset>.remove(\u003Cel>)                      # Removes the item or raises KeyError if missing.\n\u003Cset>.discard(\u003Cel>)                     # Same as remove() but it doesn't raise an error.\n```\n\n### Frozen Set\n* **Frozenset is immutable and hashable version of the normal set.**\n* **That means it can be used as a key in a dictionary or as an item in a set.**\n```python\n\u003Cfrozenset> = frozenset(\u003Ccollection>)\n```\n\n\nTuple\n-----\n**Tuple is an immutable and hashable list.**\n```python\n\u003Ctuple> = ()                        # Returns an empty tuple. Also tuple(), tuple(\u003Ccoll>).\n\u003Ctuple> = (\u003Cel>,)                   # Returns a tuple with single element. Same as `\u003Cel>,`.\n\u003Ctuple> = (\u003Cel_1>, \u003Cel_2> [, ...])  # Returns a tuple. Same as `\u003Cel_1>, \u003Cel_2> [, ...]`.\n```\n\n### Named Tuple\n**Tuple's subclass with named elements.**\n```python\n>>> from collections import namedtuple\n>>> Point = namedtuple('Point', 'x y')\n>>> p = Point(1, y=2)\n>>> print(p)\nPoint(x=1, y=2)\n>>> p.x, p[1]\n(1, 2)\n```\n\n\nRange\n-----\n**A sequence of evenly spaced integers.**\n```python\n\u003Crange> = range(stop)                # I.e. range(to_exclusive). Integers from 0 to `stop-1`.\n\u003Crange> = range(start, stop)         # I.e. range(from_inc, to_exc). From start to `stop-1`.\n\u003Crange> = range(start, stop, ±step)  # I.e. range(from_inclusive, to_exclusive, ±step_size).\n```\n\n```python\n>>> [i for i in range(3)]\n[0, 1, 2]\n```\n\n\nEnumerate\n---------\n```python\nfor i, el in enumerate(\u003Ccoll>, start=0):  # Returns next element and its index on each pass.\n    ...\n```\n\n\nIterator\n--------\n**Potentially endless stream of elements.**\n\n```python\n\u003Citer> = iter(\u003Ccollection>)              # Iterator that returns passed elements one by one.\n\u003Citer> = iter(\u003Cfunc>, to_exc)            # Calls `\u003Cfunc>()` until it receives 'to_exc' value.\n\u003Citer> = (\u003Cexpr> for \u003Cname> in \u003Ccoll>)   # E.g. `(i+1 for i in range(3))`. Evaluates lazily.\n\u003Cel>   = next(\u003Citer> [, default])        # Raises StopIteration or returns 'default' on end.\n\u003Clist> = list(\u003Citer>)                    # Returns a list of iterator's remaining elements.\n```\n* **For loops call `'iter(\u003Ccollection>)'` at the start and `'next(\u003Citer>)'` on each pass.**\n* **Calling `'iter(\u003Citer>)'` returns unmodified iterator. For details see [Iterator](#iterator-1) duck type.**\n\n```python\nimport itertools as it\n```\n\n```python\n\u003Citer> = it.count(start=0, step=1)       # Returns updated 'start' endlessly. Accepts floats.\n\u003Citer> = it.repeat(\u003Cobj> [, times])      # Returns passed element endlessly or 'times' times.\n\u003Citer> = it.cycle(\u003Ccollection>)          # Repeats the sequence endlessly. Accepts iterators.\n```\n\n```python\n\u003Citer> = it.chain(\u003Ccoll>, \u003Ccoll>, ...)   # Returns each element of each collection in order.\n\u003Citer> = it.chain.from_iterable(\u003Ccoll>)  # Accepts collection (i.e. iterable) of collections.\n\u003Citer> = it.islice(\u003Ccoll>, stop)         # Also accepts 'start' and 'step'. Args can be None.\n\u003Citer> = it.product(\u003Ccoll>, \u003Ccoll>)      # Same as `((a, b) for a in arg_1 for b in arg_2)`.\n```\n\n\nGenerator\n---------\n* **Any function that contains a yield statement returns a generator.**\n* **Generators and iterators are interchangeable.**\n\n```python\ndef count(start, step):\n    while True:\n        yield start\n        start += step\n```\n\n```python\n>>> counter = count(10, 2)\n>>> next(counter), next(counter), next(counter)\n(10, 12, 14)\n```\n\n\nType\n----\n* **Everything in Python is an object.**\n* **Every object has a certain type.**\n* **Type and class are synonymous.**\n\n```python\n\u003Ctype> = type(\u003Cobj>)                 # Object's type. Same as `\u003Cobj>.__class__`.\n\u003Cbool> = isinstance(\u003Cobj>, \u003Ctype>)   # Same as `issubclass(type(\u003Cobj>), \u003Ctype>)`.\n```\n\n```python\n>>> type('a'), 'a'.__class__, str\n(\u003Cclass 'str'>, \u003Cclass 'str'>, \u003Cclass 'str'>)\n```\n\n#### Some types do not have built-in names, so they must be imported:\n```python\nfrom types import FunctionType, MethodType, LambdaType, GeneratorType\n```\n\n### Abstract Base Classes\n**Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as [subclasses](#subclass) of the ABC, although they are really not. An ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods that class has implemented. For instance, Iterable ABC looks for method iter(), while Collection ABC looks for iter(), contains() and len().**\n\n```python\n>>> from collections.abc import Iterable, Collection, Sequence\n>>> isinstance([1, 2, 3], Iterable)\nTrue\n```\n\n```text\n+------------------+------------+------------+------------+\n|                  |  Iterable  | Collection |  Sequence  |\n+------------------+------------+------------+------------+\n| list, range, str |    yes     |    yes     |    yes     |\n| dict, set        |    yes     |    yes     |            |\n| iter             |    yes     |            |            |\n+------------------+------------+------------+------------+\n```\n\n```python\n>>> from numbers import Number, Complex, Real, Rational, Integral\n>>> isinstance(123, Number)\nTrue\n```\n\n```text\n+--------------------+-----------+-----------+----------+----------+----------+\n|                    |   Number  |  Complex  |   Real   | Rational | Integral |\n+--------------------+-----------+-----------+----------+----------+----------+\n| int                |    yes    |    yes    |   yes    |   yes    |   yes    |\n| fractions.Fraction |    yes    |    yes    |   yes    |   yes    |          |\n| float              |    yes    |    yes    |   yes    |          |          |\n| complex            |    yes    |    yes    |          |          |          |\n| decimal.Decimal    |    yes    |           |          |          |          |\n+--------------------+-----------+-----------+----------+----------+----------+\n```\n\n\nString\n------\n**Immutable sequence of characters.**\n```python\n\u003Cstr>  = 'abc'                              # Also \"abc\". Interprets \\n, \\t, \\x00-\\xff, etc.\n```\n\n```python\n\u003Cstr>  = \u003Cstr>.strip()                      # Strips all whitespace characters from both ends.\n\u003Cstr>  = \u003Cstr>.strip('\u003Cchars>')             # Strips passed characters. Also lstrip\u002Frstrip().\n```\n\n```python\n\u003Clist> = \u003Cstr>.split()                      # Splits it on one or more whitespace characters.\n\u003Clist> = \u003Cstr>.split(\u003Cstr>, maxsplit=-1)    # Splits on passed string at most maxsplit times.\n\u003Clist> = \u003Cstr>.splitlines(keepends=False)   # On [\\n\\r\\f\\v\\x1c-\\x1e\\x85\\u2028\\u2029] and \\r\\n.\n\u003Cstr>  = \u003Cstr>.join(\u003Ccoll_of_strings>)      # Joins items by using the string as a separator.\n```\n\n```python\n\u003Cbool> = \u003Csub_str> in \u003Cstr>                 # Returns True if string contains the substring.\n\u003Cbool> = \u003Cstr>.startswith(\u003Csub_str>)        # Pass tuple of strings to give multiple options.\n\u003Cint>  = \u003Cstr>.find(\u003Csub_str>)              # Returns start index of the first match or `-1`.\n```\n\n```python\n\u003Cstr>  = \u003Cstr>.lower()                      # Lowers the case. Also upper\u002Fcapitalize\u002Ftitle().\n\u003Cstr>  = \u003Cstr>.casefold()                   # Lower() that converts ẞ\u002Fß to ss, Σ\u002Fς to σ, etc.\n\u003Cstr>  = \u003Cstr>.replace(old, new [, count])  # Replaces 'old' with 'new' at most 'count' times.\n\u003Cstr>  = \u003Cstr>.translate(table)             # Get table via str.maketrans(\u003Cchr_to_str_dict>).\n```\n\n```python\n\u003Cstr>  = chr(\u003Cint>)                         # Converts passed integer into Unicode character.\n\u003Cint>  = ord(\u003Cstr>)                         # Converts passed Unicode character into integer.\n```\n* **Use `'unicodedata.normalize(\"NFC\", \u003Cstr>)'` on strings like `'Motörhead'` before comparing them to other strings, because `'ö'` can be stored as one or two characters.**\n* **`'NFC'` converts such characters to a single character, while `'NFD'` converts them to two.**\n\n```python\n\u003Cbool> = \u003Cstr>.isdecimal()                  # Checks all chars for [0-9]. Also [०-९], [٠-٩].\n\u003Cbool> = \u003Cstr>.isdigit()                    # Checks for [²³¹…] and isdecimal(). Also [፩-፱].\n\u003Cbool> = \u003Cstr>.isnumeric()                  # Checks for [¼½¾…] and isdigit(). Also [零〇一…].\n\u003Cbool> = \u003Cstr>.isalnum()                    # Checks for [ABC…] and isnumeric(). Also [ªµº…].\n\u003Cbool> = \u003Cstr>.isprintable()                # Checks for [ !\"#…], basic emojis and isalnum().\n\u003Cbool> = \u003Cstr>.isspace()                    # Checks for [ \\t\\n\\r\\f\\v\\x1c\\x1d\\x1e\\x1f\\x85…].\n```\n\n\nRegex\n-----\n**Functions for regular expression matching.**\n\n```python\nimport re\n\u003Cstr>   = re.sub(r'\u003Cregex>', new, text)  # Substitutes occurrences with string 'new'.\n\u003Clist>  = re.findall(r'\u003Cregex>', text)   # Returns all occurrences as string objects.\n\u003Clist>  = re.split(r'\u003Cregex>', text)     # Add brackets around regex to keep matches.\n\u003CMatch> = re.search(r'\u003Cregex>', text)    # Returns first occ. of the pattern or None.\n\u003CMatch> = re.match(r'\u003Cregex>', text)     # Only searches at the start of the 'text'.\n\u003Citer>  = re.finditer(r'\u003Cregex>', text)  # Returns all occurrences as Match objects.\n```\n\n* **Raw string literals do not interpret escape sequences, thus enabling us to use the regex-specific escape sequences that cause SyntaxWarning in normal string literals (since 3.12).**\n* **Argument `'new'` can also be a function that accepts a Match object and returns a string.**\n* **Argument `'flags=re.IGNORECASE'` can be used with all functions that are listed above.**\n* **Argument `'flags=re.MULTILINE'` makes `'^'` and `'$'` match the start\u002Fend of each line.**\n* **Argument `'flags=re.DOTALL'` makes `'.'` also accept the `'\\n'` (besides all other chars).**\n* **`'re.compile(r\"\u003Cregex>\")'` returns a Pattern object with methods sub(), findall(), etc.**\n\n### Match Object\n```python\n\u003Cstr>   = \u003CMatch>.group()                # Returns the whole match. Also group(0).\n\u003Cstr>   = \u003CMatch>.group(1)               # Returns part inside the first brackets.\n\u003Ctuple> = \u003CMatch>.groups()               # Returns all bracketed parts as strings.\n\u003Cint>   = \u003CMatch>.start()                # Returns start index of the whole match.\n\u003Cint>   = \u003CMatch>.end()                  # Returns the match's end index plus one.\n```\n\n### Special Sequences\n```python\n'\\d' == '[0-9]'                          # Also [०-९…]. Matches decimal character.\n'\\w' == '[a-zA-Z0-9_]'                   # Also [ª²³…]. Matches alphanumeric or _.\n'\\s' == '[ \\t\\n\\r\\f\\v]'                  # Also [\\x1c-\\x1f…]. Matches whitespace.\n```\n* **By default, decimal characters and alphanumerics from all alphabets are matched unless `'flags=re.ASCII'` is used. It restricts special sequence matches to the first 128 Unicode characters and also prevents `'\\s'` from accepting `'\\x1c'`, `'\\x1d'`, `'\\x1e'` and `'\\x1f'` (non-printable characters that divide text into files, tables, rows and fields, respectively).**\n* **Use a capital letter, i.e. `'\\D'`, `'\\W'` or `'\\S'`, for negation. All non-ASCII characters are matched if ASCII flag is used in conjunction with a capital letter.**\n\n\nFormat\n------\n```perl\n\u003Cstr> = f'{\u003Cobj>}, {\u003Cobj>}'            # Brackets can contain any expression.\n\u003Cstr> = '{}, {}'.format(\u003Cobj>, \u003Cobj>)  # Or '{0}, {a}'.format(\u003Cobj>, a=\u003Cobj>).\n\u003Cstr> = '%s, %s' % (\u003Cobj>, \u003Cobj>)      # Old and redundant formatting method.\n```\n\n### Example\n```python\n>>> Person = collections.namedtuple('Person', 'name height')\n>>> person = Person('Jean-Luc', 187)\n>>> f'{person.name} is {person.height \u002F 100} meters tall.'\n'Jean-Luc is 1.87 meters tall.'\n```\n\n### General Options\n```python\n{\u003Cobj>:\u003C10}                            # '\u003Cobj>     '.\n{\u003Cobj>:^10}                            # '  \u003Cobj>   '.\n{\u003Cobj>:>10}                            # '     \u003Cobj>'.\n{\u003Cobj>:.\u003C10}                           # '\u003Cobj>.....'.\n{\u003Cobj>:0}                              # '\u003Cobj>'.\n```\n* **Objects are converted to strings with format() function, e.g. `'format(\u003Cobj>, \"\u003C10\")'`.**\n* **Options can be generated dynamically via nested braces: `f'{\u003Cobj>:{\u003Cstr\u002Fint>}[…]}'`.**\n* **Adding `'='` to the expression prepends it to its result, e.g. `f'{1+1=}'` returns `'1+1=2'`.**\n* **Adding `'!r'` to the expression first calls result's [repr()](#class) method and only then format().**\n\n### Strings\n```python\n{'abcde':10}                           # 'abcde     '.\n{'abcde':10.3}                         # 'abc       '.\n{'abcde':.3}                           # 'abc'.\n{'abcde'!r:10}                         # \"'abcde'   \".\n```\n\n### Numbers\n```python\n{123456:10}                            # '    123456'.\n{123456:10,}                           # '   123,456'.\n{123456:10_}                           # '   123_456'.\n{123456:+10}                           # '   +123456'.\n{123456:=+10}                          # '+   123456'.\n{123456: }                             # ' 123456'.\n{-123456: }                            # '-123456'.\n```\n\n### Floats\n```python\n{1.23456:10.3}                         # '      1.23'.\n{1.23456:10.3f}                        # '     1.235'.\n{1.23456:10.3e}                        # ' 1.235e+00'.\n{1.23456:10.3%}                        # '  123.456%'.\n```\n\n#### Comparison of presentation types:\n```text\n+--------------+----------------+----------------+----------------+----------------+\n|              |    {\u003Cfloat>}   |   {\u003Cfloat>:f}  |   {\u003Cfloat>:e}  |   {\u003Cfloat>:%}  |\n+--------------+----------------+----------------+----------------+----------------+\n|  0.000056789 |   '5.6789e-05' |    '0.000057'  | '5.678900e-05' |    '0.005679%' |\n|  0.00056789  |   '0.00056789' |    '0.000568'  | '5.678900e-04' |    '0.056789%' |\n|  0.0056789   |   '0.0056789'  |    '0.005679'  | '5.678900e-03' |    '0.567890%' |\n|  0.056789    |   '0.056789'   |    '0.056789'  | '5.678900e-02' |    '5.678900%' |\n|  0.56789     |   '0.56789'    |    '0.567890'  | '5.678900e-01' |   '56.789000%' |\n|  5.6789      |   '5.6789'     |    '5.678900'  | '5.678900e+00' |  '567.890000%' |\n| 56.789       |  '56.789'      |   '56.789000'  | '5.678900e+01' | '5678.900000%' |\n+--------------+----------------+----------------+----------------+----------------+\n```\n\n```text\n+--------------+----------------+----------------+----------------+----------------+\n|              |  {\u003Cfloat>:.2}  |  {\u003Cfloat>:.2f} |  {\u003Cfloat>:.2e} |  {\u003Cfloat>:.2%} |\n+--------------+----------------+----------------+----------------+----------------+\n|  0.000056789 |    '5.7e-05'   |      '0.00'    |   '5.68e-05'   |      '0.01%'   |\n|  0.00056789  |    '0.00057'   |      '0.00'    |   '5.68e-04'   |      '0.06%'   |\n|  0.0056789   |    '0.0057'    |      '0.01'    |   '5.68e-03'   |      '0.57%'   |\n|  0.056789    |    '0.057'     |      '0.06'    |   '5.68e-02'   |      '5.68%'   |\n|  0.56789     |    '0.57'      |      '0.57'    |   '5.68e-01'   |     '56.79%'   |\n|  5.6789      |    '5.7'       |      '5.68'    |   '5.68e+00'   |    '567.89%'   |\n| 56.789       |    '5.7e+01'   |     '56.79'    |   '5.68e+01'   |   '5678.90%'   |\n+--------------+----------------+----------------+----------------+----------------+\n```\n* **`'{\u003Cnum>:g}'` is `'{\u003Cfloat>:.6}'` that strips `'.0'` and has exponent starting at `'1e+06'`.**\n* **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'`.**\n* **The last rule only effects numbers that can be represented exactly by a float (`.5`, `.25`, …).**\n\n### Ints\n```python\n{90:b}                                 # Converts 90 to binary number '1011010'.\n{90:x}                                 # Converts 90 to hexadecimal number '5a'.\n{90:c}                                 # Converts 90 to Unicode character 'Z'.\n```\n\n\nNumbers\n-------\n```python\n\u003Cinteger>  = int(\u003Cfloat\u002Fstr\u002Fbool>)             # A whole number. Truncates floats.\n\u003Cfloat>    = float(\u003Cinteger\u002Fstr\u002Fbool>)         # 64-bit decimal. Also \u003Cfl>e±\u003Cint>.\n\u003Ccomplex>  = complex(real=0, imag=0)           # Complex number. Also \u003Cfl> ± \u003Cfl>j.\n\u003CFraction> = fractions.Fraction(numer, denom)  # `\u003CFraction> = \u003CFraction> \u002F \u003Cint>`.\n\u003CDecimal>  = decimal.Decimal(\u003Cstr\u002Fint\u002Ftuple>)  # `Decimal((1, (2,), 3)) == -2000`.\n```\n* **`'int(\u003Cstr>)'` and `'float(\u003Cstr>)'` raise ValueError exception if string is malformed.**\n* **Decimal objects store numbers exactly, unlike most floats where `'1.1 + 2.2 != 3.3'`.**\n* **Floats can be compared with: `'math.isclose(\u003Cfloat>, \u003Cfloat>, rel_tol=1e-9)'`.**\n* **Precision of decimal operations is set with: `'decimal.getcontext().prec = \u003Cint>'`.**\n* **Bools can be used anywhere ints can, since bool is a subclass of int: `'True + 1 == 2'`.**\n\n### Built-in Functions\n```python\n\u003Cnum> = pow(\u003Cnum>, \u003Cnum>)                      # E.g. `pow(3, 4) == 3 ** 4 == 81`.\n\u003Cnum> = abs(\u003Cnum>)                             # E.g. `abs(-50) == abs(50) == 50`.\n\u003Cnum> = round(\u003Cnum> [, ±ndigits])              # E.g. `round(123.45, -1) == 120`.\n\u003Cnum> = min(\u003Ccoll_of_nums>)                    # Also `max(\u003Cnum>, \u003Cnum> [, ...])`.\n\u003Cnum> = sum(\u003Ccoll_of_nums>)                    # Also `math.prod(\u003Ccoll_of_nums>)`.\n```\n\n### Math\n```python\nfrom math import floor, ceil, trunc            # Funcs that convert float into int.\nfrom math import pi, inf, nan, isnan           # `inf*0` and `nan+1` return `nan`.\nfrom math import sqrt, factorial               # `sqrt(-1)` will raise ValueError.\nfrom math import sin, cos, tan                 # Also: degrees, radians, asin, etc.\nfrom math import log, log10, log2              # Log() can accept 'base' argument.\n```\n\n### Statistics\n```python\nfrom statistics import mean, median, mode      # Mode returns most common element.\nfrom statistics import variance, stdev         # Also `cuts = quantiles(data, n)`.\n```\n\n### Random\n```python\nfrom random import random, randint, uniform    # Also: gauss, choice, shuffle, etc.\n```\n\n```python\n\u003Cfloat> = random()                             # Selects random float from [0, 1).\n\u003Cnum>   = randint\u002Funiform(a, b)                # Selects an int\u002Ffloat from [a, b].\n\u003Cfloat> = gauss(mean, stdev)                   # Also triangular(low, high, mode).\n\u003Cel>    = choice(\u003Csequence>)                   # Doesn't mutate. Also sample(p, n).\nshuffle(\u003Clist>)                                # Works with all mutable sequences.\n```\n\n### Hexadecimal Numbers\n```python\n\u003Cint> = 0x\u003Chex>                                # E.g. `0xFf == 255`. Also 0b\u003Cbin>.\n\u003Cint> = int('±\u003Chex>', 16)                      # Also int('±0x\u003Chex>\u002F±0b\u003Cbin>', 0).\n\u003Cstr> = hex(\u003Cint>)                             # Returns '[-]0x\u003Chex>'. Also bin().\n```\n\n### Bitwise Operators\n```python\n\u003Cint> = \u003Cint> & \u003Cint>                          # E.g. `0b1100 & 0b1010 == 0b1000`.\n\u003Cint> = \u003Cint> | \u003Cint>                          # E.g. `0b1100 | 0b1010 == 0b1110`.\n\u003Cint> = \u003Cint> ^ \u003Cint>                          # E.g. `0b1100 ^ 0b1010 == 0b0110`.\n\u003Cint> = \u003Cint> \u003C\u003C n_bits                        # E.g. `0b1111 \u003C\u003C 4 == 0b11110000`.\n\u003Cint> = ~\u003Cint>                                 # E.g. `~100 == -(100+1) == -101`.\n```\n\n\nCombinatorics\n-------------\n```python\nimport itertools as it\n```\n\n```python\n>>> list(it.product('abc', repeat=2))        #   a  b  c\n[('a', 'a'), ('a', 'b'), ('a', 'c'),         # a x  x  x\n ('b', 'a'), ('b', 'b'), ('b', 'c'),         # b x  x  x\n ('c', 'a'), ('c', 'b'), ('c', 'c')]         # c x  x  x\n```\n\n```python\n>>> list(it.permutations('abc', 2))          #   a  b  c\n[('a', 'b'), ('a', 'c'),                     # a .  x  x\n ('b', 'a'), ('b', 'c'),                     # b x  .  x\n ('c', 'a'), ('c', 'b')]                     # c x  x  .\n```\n\n```python\n>>> list(it.combinations('abc', 2))          #   a  b  c\n[('a', 'b'), ('a', 'c'),                     # a .  x  x\n ('b', 'c')                                  # b .  .  x\n]                                            # c .  .  .\n```\n\n\nDatetime\n--------\n**Module that provides date, time, and datetime objects.**\n\n```python\n# $ pip3 install python-dateutil\nfrom datetime import *\nimport zoneinfo, dateutil.tz\n```\n\n```python\n\u003CD>  = date(year, month, day)               # Only accepts valid dates between AD 1 and 9999.\n\u003CT>  = time(hour=0, minute=0, second=0)     # Accepts `microsecond=0, tzinfo=None, fold=0`.\n\u003CDT> = datetime(year, month, day, hour=0)   # Accepts `minute=0, second=0, microsecond=0, …`.\n\u003CTD> = timedelta(weeks=0, days=0, hours=0)  # Accepts `minutes=0, seconds=0, microseconds=0`.\n```\n* **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.**\n* **`'fold=1'` means the second pass in case of time jumping back (usually for one hour).**\n* **Timedelta normalizes arguments to ±days, seconds (\u003C 86 400) and microseconds (\u003C 1M). Its str() method returns `'[±D, ]H:MM:SS[.…]'` and total_seconds() a float of seconds.**\n* **Use `'\u003CD\u002FDT>.weekday()'` to get the day of the week as an int (with Monday being 0).**\n\n### Now\n```python\n\u003CD\u002FDTn> = D\u002FDT.today()                      # Current local date or naive DT. Also DT.now().\n\u003CDTa>   = DT.now(\u003Ctzinfo>)                  # Aware DT from current time in passed timezone.\n```\n* **To extract time use `'\u003CDTn>.time()'`, `'\u003CDTa>.time()'` or `'\u003CDTa>.timetz()'`.**\n\n### Timezones\n```python\n\u003Ctzinfo> = timezone.utc                     # Coordinated universal time. London without DST.\n\u003Ctzinfo> = timezone(\u003Ctimedelta>)            # Timezone with fixed offset from universal time.\n\u003Ctzinfo> = dateutil.tz.tzlocal()            # Local timezone with dynamic offset from the UTC.\n\u003Ctzinfo> = zoneinfo.ZoneInfo('\u003Ciana_key>')  # 'Continent\u002FCity_Name' zone with dynamic offset.\n\u003CDTa>    = \u003CDT>.astimezone(\u003Ctzinfo>)        # Converts to the passed or local fixed timezone.\n\u003CTa\u002FDTa> = \u003CT\u002FDT>.replace(tzinfo=\u003Ctzinfo>)  # Changes the timezone object without conversion.\n```\n* **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.**\n* **To get ZoneInfo() to work on Windows run `'> pip3 install tzdata'`.**\n\n### Encode\n```python\n\u003CD\u002FT\u002FDT> = D\u002FT\u002FDT.fromisoformat(\u003Cstr>)      # Object from the ISO string. Raises ValueError.\n\u003CDT>     = DT.strptime(\u003Cstr>, '\u003Cformat>')   # Naive or aware datetime from the custom string.\n\u003CD\u002FDTn>  = D\u002FDT.fromordinal(\u003Cint>)          # Date or DT from days since the Gregorian NYE 1.\n\u003CDTn>    = DT.fromtimestamp(\u003Cfloat>)        # A local naive DT from seconds since the epoch.\n\u003CDTa>    = DT.fromtimestamp(\u003Cfloat>, \u003Ctz>)  # An aware datetime from seconds since the epoch.\n```\n* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.mmmuuu[±HH:MM]'`, or both separated by an arbitrary character. All parts following the hours are optional.**\n* **Python uses the Unix epoch: `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...**\n\n### Decode\n```python\n\u003Cstr>    = \u003CD\u002FT\u002FDT>.isoformat(sep='T')      # Also `timespec='auto\u002Fhours\u002Fminutes\u002Fseconds\u002F…'`.\n\u003Cstr>    = \u003CD\u002FT\u002FDT>.strftime('\u003Cformat>')    # Returns custom string representation of object.\n\u003Cint>    = \u003CD\u002FDT>.toordinal()               # Days since NYE 1, ignoring DT's time and zone.\n\u003Cfloat>  = \u003CDTn>.timestamp()                # Seconds since the epoch from a local naive DT.\n\u003Cfloat>  = \u003CDTa>.timestamp()                # Seconds since the epoch from an aware datetime.\n```\n\n### Format\n```python\n>>> dta = datetime.strptime('2025-08-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z')\n>>> dta.strftime(\"%dth of %B '%y (%a), %I:%M %p %Z\")\n\"14th of August '25 (Thu), 11:39 PM UTC+02:00\"\n```\n* **`'%z'` accepts `'±HH[:]MM'` and returns `'±HHMM'` or empty string if object is naive.**\n* **`'%Z'` accepts `'UTC\u002FGMT'` and local timezone's code and returns timezone's name, `'UTC[±HH:MM]'` if timezone is nameless, or an empty string if object is naive.**\n\n### Arithmetics\n```python\n\u003Cbool>   = \u003CD\u002FT\u002FDTn> > \u003CD\u002FT\u002FDTn>            # Ignores time jumps (fold attribute). Also `==`.\n\u003Cbool>   = \u003CDTa>     > \u003CDTa>                # Ignores time jumps if they share tzinfo object.\n\u003CTD>     = \u003CD\u002FDTn>   - \u003CD\u002FDTn>              # Ignores jumps. Convert to UTC for actual delta.\n\u003CTD>     = \u003CDTa>     - \u003CDTa>                # Ignores jumps if they share the tzinfo object.\n\u003CD\u002FDT>   = \u003CD\u002FDT>    ± \u003CTD>                 # Returned datetime can fall into a missing hour.\n\u003CTD>     = \u003CTD>      * \u003Cfloat>              # Also `\u003CTD> = \u003CTD> ± \u003CTD>`, `\u003CTD> = abs(\u003CTD>)`.\n\u003Cfloat>  = \u003CTD>      \u002F \u003CTD>                 # Calling divmod(\u003CTD>, \u003CTD>) returns int and TD.\n```\n\n\nFunction\n--------\n**Independent block of code that returns a value when called.**\n\n```python\ndef my_function(\u003Cnondefault_args>): ...                  # E.g. `my_func(x, y):`.\ndef my_function(\u003Cdefault_args>): ...                     # E.g. `my_func(x=0, y=0):`.\ndef my_function(\u003Cnondefault_args>, \u003Cdefault_args>): ...  # E.g. `my_func(x, y=0):`.\n```\n* **Function returns None if it doesn't encounter the `'return \u003Cobject\u002Fexpr>'` statement.**\n* **Run `'global \u003Cvar_name>'` inside the function before assigning to the global variable.**\n* **Value of a default argument is evaluated when function is first encountered in the scope.**\n* **Any mutation of a default argument value will persist between function invocations!**\n\n### Function Call\n\n```python\n\u003Cobj> = \u003Cfunction>(\u003Cpositional_args>)                    # E.g. `my_func(0, 0)`.\n\u003Cobj> = \u003Cfunction>(\u003Ckeyword_args>)                       # E.g. `my_func(x=0, y=0)`.\n\u003Cobj> = \u003Cfunction>(\u003Cpositional_args>, \u003Ckeyword_args>)    # E.g. `my_func(0, y=0)`.\n```\n\n\nSplat Operator\n--------------\n**Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.**\n```python\nargs, kwargs = (1, 2), {'z': 3}\nfunc(*args, **kwargs)\n```\n\n#### Is the same as:\n```python\nfunc(1, 2, z=3)\n```\n\n### Inside Function Definition\n**Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.**\n```python\ndef add(*a):\n    return sum(a)\n```\n\n```python\n>>> add(1, 2, 3)\n6\n```\n\n#### Allowed compositions of arguments and the ways they can be called:\n```text\n+---------------------------+----------------+--------------+--------------+\n|                           | func(x=1, y=2) | func(1, y=2) |  func(1, 2)  |\n+---------------------------+----------------+--------------+--------------+\n| func(x, *args, **kwargs): |      yes       |     yes      |     yes      |\n| func(*args, y, **kwargs): |      yes       |     yes      |              |\n| func(*, x, **kwargs):     |      yes       |              |              |\n+---------------------------+----------------+--------------+--------------+\n```\n\n### Other Uses\n```python\n\u003Clist>  = [*\u003Ccollection> [, ...]]  # Same as `list(\u003Ccoll>) [+ ...]`.\n\u003Ctuple> = (*\u003Ccollection>, [...])   # Same as `tuple(\u003Ccoll>) [+ ...]`.\n\u003Cset>   = {*\u003Ccollection> [, ...]}  # Same as `set(\u003Ccoll>) [| ...]`.\n\u003Cdict>  = {**\u003Cdict> [, ...]}       # Last dict has priority. Also |.\n```\n\n```python\nhead, *body, tail = \u003Ccollection>   # Head or tail can be omitted.\n```\n\n\nInline\n------\n### Lambda\n```python\n\u003Cfunc> = lambda: \u003Creturn_value>                   # A single statement function.\n\u003Cfunc> = lambda \u003Carg_1> [, ...]: \u003Creturn_value>   # Also allows default arguments.\n```\n\n### Comprehensions\n```python\n\u003Clist> = [i+1 for i in range(5)]                  # Returns `[1, 2, 3, 4, 5]`.\n\u003Citer> = (i for i in range(10) if i > 5)          # Returns `iter([6, 7, 8, 9])`.\n\u003Cset>  = {i+5 for i in range(5)}                  # Returns `{5, 6, 7, 8, 9}`.\n\u003Cdict> = {i: i**2 for i in range(1, 4)}           # Returns `{1: 1, 2: 4, 3: 9}`.\n```\n\n```python\n>>> [l+r for l in 'abc' for r in 'abc']           # Inner loop is on right side.\n['aa', 'ab', 'ac', ..., 'cc']\n```\n\n### Map, Filter, Reduce\n```python\nfrom functools import reduce\n```\n\n```python\n\u003Citer> = map(lambda x: x + 1, range(5))           # Returns `iter([1, 2, 3, 4, 5])`.\n\u003Citer> = filter(lambda x: x > 5, range(10))       # Returns `iter([6, 7, 8, 9])`.\n\u003Cobj>  = reduce(lambda out, x: out+x, range(5))   # Returns 10. Accepts 'initial'.\n```\n\n### Any, All\n```python\n\u003Cbool> = any(\u003Ccollection>)                        # Is bool(\u003Cel>) True for any el?\n\u003Cbool> = all(\u003Ccollection>)                        # Is it True for all (or empty)?\n```\n\n### Conditional Expression\n```python\n\u003Cobj> = \u003Cexp> if \u003Ccondition> else \u003Cexp>           # Evaluates only one expression.\n```\n\n```python\n>>> [i if i else 'zero' for i in (0, 1, 2)]       # `any(['', [], None])` is False.\n['zero', 1, 2]\n```\n\n### And, Or\n```python\n\u003Cobj> = \u003Cexp> and \u003Cexp> [and ...]                 # Returns first false or last obj.\n\u003Cobj> = \u003Cexp> or \u003Cexp> [or ...]                   # Returns first true or last obj.\n```\n\n### Walrus Operator\n```python\n>>> [i for ch in '0123' if (i := int(ch)) > 0]    # Assigns to var in mid-sentence.\n[1, 2, 3]\n```\n\n### Named Tuple, Enum, Dataclass\n```python\nfrom collections import namedtuple\nPoint = namedtuple('Point', 'x y')                # Creates tuple's subclass.\npoint = Point(0, 0)                               # Returns its instance.\n\nfrom enum import Enum\nDirection = Enum('Direction', 'N E S W')          # Creates an enumeration.\ndirection = Direction.N                           # Returns its member.\n\nfrom dataclasses import make_dataclass\nPlayer = make_dataclass('Player', ['p', 'd'])     # Creates a normal class.\nplayer = Player(point, direction)                 # Returns its instance.\n```\n\n\nImport\n------\n**Mechanism that makes code in one file available to another file.**\n\n```python\nimport \u003Cmodule>                    # Imports a built-in module or '.\u002F\u003Cmodule>.py'.\nimport \u003Cpackage>                   # Built-in package or '.\u002F\u003Cpackage>\u002F__init__.py'.\nimport \u003Cpackage>.\u003Cmodule>          # Package's module or '.\u002F\u003Cpackage>\u002F\u003Cmodule>.py'.\nfrom \u003Cpkg\u002Fmod>[.…] import \u003Cobj>    # Imports module, function, class or variable.\n```\n* **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.**\n* **`'import \u003Cpackage>'` only exposes modules that are imported inside `'__init__.py'`.**\n* **Directory of the file that is passed to python command serves as the root of local imports.**\n* **Use relative imports, i.e. `'from .[…][\u003Cpkg\u002Fmod>[.…]] import \u003Cobj>'`, 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:\u002F\u002Fpackaging.python.org\u002Fen\u002Flatest\u002Fguides\u002Fwriting-pyproject-toml\u002F#basic-information) to its root, and running `'$ pip3 install -e .'`.**\n\n\nClosure\n-------\n**We have\u002Fget a closure in Python when a nested function references a value of its enclosing function and then the enclosing function returns its nested function (any value that is ref&shy;erenced from within multiple nested functions gets shared).**\n\n```python\ndef get_multiplier(a):\n    def out(b):\n        return a * b\n    return out\n```\n\n```python\n>>> multiply_by_3 = get_multiplier(3)\n>>> multiply_by_3(10)\n30\n```\n\n### Partial\n```python\nfrom functools import partial\n\u003Cfunction> = partial(\u003Cfunction> [, \u003Carg_1> [, ...]])\n```\n\n```python\n>>> def multiply(a, b):\n...     return a * b\n>>> multiply_by_3 = partial(multiply, 3)\n>>> multiply_by_3(10)\n30\n```\n* **Partial is also useful in cases when a function needs to be passed as an argument because it enables us to set its arguments beforehand (`'collections.defaultdict(\u003Cfunc>)'`, `'iter(\u003Cfunc>, to_exc)'` and `'dataclasses.field(default_factory=\u003Cfunc>)'`).**\n\n### Non-Local\n**If variable is being assigned to anywhere in the scope (i.e., body of a function), it is treated as&nbsp;a local variable unless it is declared `'global'` or `'nonlocal'` before its first usage.**\n\n```python\ndef get_counter():\n    i = 0\n    def out():\n        nonlocal i\n        i += 1\n        return i\n    return out\n```\n\n```python\n>>> counter = get_counter()\n>>> counter(), counter(), counter()\n(1, 2, 3)\n```\n\n\nDecorator\n---------\n**A decorator takes a function, adds some functionality and returns it. It can be any [callable](#callable), but is usually implemented as a function that returns a [closure](#closure).**\n\n```python\n@decorator_name\ndef function_that_gets_passed_to_decorator():\n    ...\n```\n\n### Debugger Example\n**Decorator that prints function's name every time that function is called.**\n\n```python\nfrom functools import wraps\n\ndef debug(func):\n    @wraps(func)\n    def out(*args, **kwargs):\n        print(func.__name__)\n        return func(*args, **kwargs)\n    return out\n\n@debug\ndef add(x, y):\n    return x + y\n```\n* **Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is decorating (out). Without it, `'add.__name__'` would return string `'out'`.**\n\n### Cache\n**Decorator that stores return values. All arguments must be hashable.**\n\n```python\nfrom functools import cache\n\n@cache\ndef fibonacci(n):\n    return n if n \u003C 2 else fibonacci(n-2) + fibonacci(n-1)\n```\n* **Potential problem with cache is that it can grow indefinitely. To clear stored values run `'\u003Cfunc>.cache_clear()'`, or use `'@lru_cache(maxsize=\u003Cint>)'` decorator instead.**\n* **CPython interpreter limits recursion depth to 3000 by default. To increase this limit run `'sys.setrecursionlimit(\u003Cint>)'`.**\n\n### Parametrized Decorator\n**Decorator that accepts arguments and returns a normal decorator.**\n```python\nfrom functools import wraps\n\ndef debug(print_result=False):\n    def decorator(func):\n        @wraps(func)\n        def out(*args, **kwargs):\n            result = func(*args, **kwargs)\n            print(func.__name__, result if print_result else '')\n            return result\n        return out\n    return decorator\n\n@debug(print_result=True)\ndef add(x, y):\n    return x + y\n```\n* **Using only `'@debug'` to decorate the add() function would not work here, because debug would then receive the add() function as a 'print_result' argument. Decorators can how&shy;ever manually check if the argument they received is a function and act accordingly.**\n\n\nClass\n-----\n**A template for creating user-defined objects.**\n\n```python\nclass MyClass:\n    def __init__(self, a):\n        self.a = a\n    def __str__(self):\n        return str(self.a)\n    def __repr__(self):\n        class_name = self.__class__.__name__\n        return f'{class_name}({self.a!r})'\n\n    @classmethod\n    def get_class_name(cls):\n        return cls.__name__\n```\n\n```python\n>>> obj = MyClass(1)\n>>> obj.a, str(obj), repr(obj)\n(1, '1', 'MyClass(1)')\n```\n* **Methods whose names start and end with two underscores are called special methods.**\n* **They are executed when object is passed to a built-in function or used as an operand. For&nbsp;example, `'print(a)'` calls `'a.__str__()'` and `'a + b'` calls `'a.__add__(b)'`.**\n* **See module [operator](#operator) to get names of all special methods that are called by operators.**\n* **Methods that are decorated with `'@staticmethod'` receive neither 'self' nor 'cls' arg.**\n* **Return value of str() special method should be readable and of repr() unambiguous.\u003Cbr>All calls to str() special method are dispatched to repr() when only repr() is provided.**\n\n#### Expressions that call str() special method:\n```python\nf'{obj}'\nstr(obj)\nprint(obj)\n```\n\n#### Expressions that call repr() special method:\n```python\nf'{obj!r}'\nstr\u002Frepr\u002Fprint([obj])\nstr\u002Frepr\u002Fprint({obj: obj})\nstr\u002Frepr\u002Fprint(MyDataClass(obj))\n```\n\n### Subclass\n* **Inheritance is a mechanism that enables a class to extend some other class (i.e. sub&shy;class&nbsp;to extend its parent), and by doing so inherit all of its methods and attributes.**\n* **Subclass can then add its own methods and attributes or override inherited ones by reusing their names.**\n\n```python\nclass Person:\n    def __init__(self, name):\n        self.name = name\n    def __repr__(self):\n        return f'Person({self.name!r})'\n    def __lt__(self, other):\n        return self.name \u003C other.name\n\nclass Employee(Person):\n    def __init__(self, name, staff_num):\n        super().__init__(name)\n        self.staff_num = staff_num\n    def __repr__(self):\n        return f'Employee({self.name!r}, {self.staff_num})'\n```\n\n```python\n>>> people = [Person('Bob'), Employee('Ann', 0)]\n>>> sorted(people)\n[Employee('Ann', 0), Person('Bob')]\n```\n\n### Type Annotations\n* **They add type hints to variables, arguments and functions (`'def f() -> \u003Ctype>:'`).**\n* **Hints are used by type checkers like [mypy](https:\u002F\u002Fpypi.org\u002Fproject\u002Fmypy\u002F), data validation libraries such as [Pydantic](https:\u002F\u002Fpypi.org\u002Fproject\u002Fpydantic\u002F) and lately also by [Cython](https:\u002F\u002Fpypi.org\u002Fproject\u002FCython\u002F) compiler. However, they are not enforced by CPython interpreter.**\n```python\nfrom collections import abc\n\n\u003Cname>: \u003Ctype> [| ...] [= \u003Cobj>]\n\u003Cname>: list\u002Fset\u002Fabc.Iterable\u002Fabc.Sequence[\u003Ctype>] [= \u003Cobj>]\n\u003Cname>: tuple\u002Fdict[\u003Ctype>, ...] [= \u003Cobj>]\n```\n\n### Dataclass\n**Decorator that uses class variables to generate init(), repr() and eq() special methods.**\n```python\nimport dataclasses as dc\n\n@dc.dataclass(order=False, frozen=False)\nclass MyClass:\n    \u003Cattr_name>: \u003Ctype>\n    \u003Cattr_name>: \u003Ctype> = \u003Cobj>\n    \u003Cattr_name>: list = dc.field(default_factory=list)\n```\n* **Objects can be made [sortable](#sortable) with `'order=True'` and immutable with `'frozen=True'`.**\n* **For object to be [hashable](#hashable), all attributes must be hashable and `'frozen'` must be `'True'`.**\n* **Function field() is needed because `'\u003Cattr_name>: list = []'` would make a list that is&nbsp;shared among all instances. Its 'default_factory' argument accepts any [callable](#callable) object.**\n* **For attributes and arguments of arbitrary type use `'\u003Cattr_name>: typing.Any'`.**\n\n#### Inline:\n```python\nP = dc.make_dataclass('P', ['x', 'y'])\nP = dc.make_dataclass('P', [('x', float), ('y', float)])\nP = dc.make_dataclass('P', [('x', float, 0), ('y', float, 0)])\n```\n\n### Property\n**Pythonic way of implementing getters and setters.**\n```python\nclass Person:\n    @property\n    def name(self):\n        return ' '.join(self._name)\n\n    @name.setter\n    def name(self, value):\n        self._name = value.split()\n```\n\n```python\n>>> person = Person()\n>>> person.name = '\\t Guido  van Rossum \\n'\n>>> person.name\n'Guido van Rossum'\n```\n\n### Slots\n**Mechanism that restricts objects to listed attributes.**\n\n```python\nclass Point:\n    __slots__ = ['x', 'y']\n```\n\n### Copy\n```python\nfrom copy import copy, deepcopy\n\u003Cobject> = copy\u002Fdeepcopy(\u003Cobject>)\n```\n\n\nDuck Types\n----------\n**A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type.**\n\n### Comparable\n* **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`. That means all user-defined objects compare not equal by default (because id() returns object's memory address that is guaranteed to be unique).**\n* **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. Result is False if both return NotImplemented.**\n* **Method ne() (called by `'!='`) automatically works on any object that has eq() defined.**\n\n```python\nclass MyComparable:\n    def __init__(self, a):\n        self.a = a\n    def __eq__(self, other):\n        if isinstance(other, type(self)):\n            return self.a == other.a\n        return NotImplemented\n```\n\n### Hashable\n* **Hashable object needs hash() and eq() methods and its hash value must never change.**\n* **Hashable objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do. That is why Python automatically makes classes unhashable if you only implement the eq() method.**\n\n```python\nclass MyHashable:\n    def __init__(self, a):\n        self._a = a\n    @property\n    def a(self):\n        return self._a\n    def __eq__(self, other):\n        if isinstance(other, type(self)):\n            return self.a == other.a\n        return NotImplemented\n    def __hash__(self):\n        return hash(self.a)\n```\n\n### Sortable\n* **With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods (called by \u003C, >, \u003C=, >=) and the rest will be automatically generated.**\n* **Built-in functions sorted() and min() only require lt() method, while max() only requires gt(). However, it's best to define them all so that confusion doesn't arise in other contexts.**\n* **When two lists, strings, or data classes are compared, their values get compared one by one until a pair of unequal values is found. The comparison of this two values is then re&shy;turned. The shorter sequence is considered smaller in case of all their values being equal.**\n* **To sort collection of strings in proper alphabetical order pass `'key=locale.strxfrm'` to sorted() after running `'locale.setlocale(locale.LC_COLLATE, \"en_US.UTF-8\")'`.**\n\n```python\nfrom functools import total_ordering\n\n@total_ordering\nclass MySortable:\n    def __init__(self, a):\n        self.a = a\n    def __eq__(self, other):\n        if isinstance(other, type(self)):\n            return self.a == other.a\n        return NotImplemented\n    def __lt__(self, other):\n        if isinstance(other, type(self)):\n            return self.a \u003C other.a\n        return NotImplemented\n```\n\n### Iterator\n* **Any object that has special methods next() and iter() is an iterator.**\n* **Next() should return the next item or raise StopIteration exception.**\n* **Iter() should return an unmodified iterator, i.e. the 'self' argument.**\n* **Any object that has iter() special method can be used in a for loop.**\n```python\nclass Counter:\n    def __init__(self):\n        self.i = 0\n    def __next__(self):\n        self.i += 1\n        return self.i\n    def __iter__(self):\n        return self\n```\n\n```python\n>>> counter = Counter()\n>>> next(counter), next(counter), next(counter)\n(1, 2, 3)\n```\n\n#### Python has many different iterator objects:\n* **Sequence iterators returned by the [iter()](#iterator) function, such as 'list\\_iterator'.**\n* **Objects returned by the [itertools](#itertools) module, such as count, repeat and cycle.**\n* **Generator objects returned by the generator [functions](#generator) and [expressions](#comprehensions).**\n* **File objects returned by the [open()](#open) function, [SQLite](#sqlite) cursor objects, etc.**\n\n### Callable\n* **All functions and classes have a call() method that is executed when they are called.**\n* **Use `'callable(\u003Cobj>)'` or `'isinstance(\u003Cobj>, collections.abc.Callable)'` to&nbsp;check if object is callable and `'inspect.signature(\u003Cobj>)'` for info about args.**\n* **When this text uses `'\u003Cfunction>'` as an argument, it actually means `'\u003Ccallable>'`.**\n```python\nclass Counter:\n    def __init__(self):\n        self.i = 0\n    def __call__(self):\n        self.i += 1\n        return self.i\n```\n\n```python\n>>> counter = Counter()\n>>> counter(), counter(), counter()\n(1, 2, 3)\n```\n\n### Context Manager\n* **With statements only work on objects that have enter() and exit() special methods.**\n* **Enter() should lock the resources and optionally return an object (file, socket, etc.).**\n* **Exit() should release the resources (for example close the file, release the lock, etc.).**\n* **Any exception that happens inside the with block is passed to exit() method. Exit() can&nbsp;then suppress this exception by returning a true value (not None, False, 0, etc.).**\n```python\nclass MyOpen:\n    def __init__(self, filename):\n        self.filename = filename\n    def __enter__(self):\n        self.file = open(self.filename)\n        return self.file\n    def __exit__(self, exc_type, exception, traceback):\n        self.file.close()\n```\n\n```python\n>>> with open('test.txt', 'w') as file:\n...     file.write('Hello World!')\n>>> with MyOpen('test.txt') as file:\n...     print(file.read())\nHello World!\n```\n\n\nIterable Duck Types\n-------------------\n### Iterable\n* **Only required special method is iter(). It should return an iterator of object's items.**\n* **Special method contains() automatically works on any object that has iter() defined.**\n```python\nclass MyIterable:\n    def __init__(self, a):\n        self.a = a\n    def __iter__(self):\n        return iter(self.a)\n    def __contains__(self, el):\n        return el in self.a\n```\n\n```python\n>>> obj = MyIterable([1, 2, 3])\n>>> [el for el in obj]\n[1, 2, 3]\n>>> 1 in obj\nTrue\n```\n\n### Collection\n* **Only required methods are iter() and len(). Len() should return the length of collection.**\n* **This text refers to all iterable objects as collections, which is technically incorrect. The term _iterable_ was avoided because it sounds scarier and more vague than _collection_. The main drawback of this decision is that the reader could think a certain function doesn't accept iterators when it actually does, since iterators are the only built-in objects that are&nbsp;iterable but are not collections.**\n```python\nclass MyCollection:\n    def __init__(self, a):\n        self.a = a\n    def __iter__(self):\n        return iter(self.a)\n    def __contains__(self, el):\n        return el in self.a\n    def __len__(self):\n        return len(self.a)\n```\n\n### Sequence\n* **Only required methods are getitem() and len(). Getitem() should return an item at the passed index or raise IndexError (it may also support negative indices and\u002For slices).**\n* **Iter() and contains() automatically work on any object with defined getitem() method.**\n* **Reversed() automatically works on any object that has getitem() and len() defined. It returns reversed iterator of object's items.**\n```python\nclass MySequence:\n    def __init__(self, a):\n        self.a = a\n    def __iter__(self):\n        return iter(self.a)\n    def __contains__(self, el):\n        return el in self.a\n    def __len__(self):\n        return len(self.a)\n    def __getitem__(self, i):\n        return self.a[i]\n    def __reversed__(self):\n        return reversed(self.a)\n```\n\n#### Discrepancies between glossary definitions and abstract base classes:\n* **Python's glossary defines iterable as any object with special methods iter() or getitem(), and sequence as any object with getitem() and len(). It doesn't define the term _collection_.**\n* **Passing ABC Iterable to isinstance() or issubclass() only checks whether object\u002Fclass has special method iter(), while ABC Collection checks for iter(), contains() and len().**\n\n### ABC Sequence\n* **It's a richer interface than the basic sequence that also requires just getitem() and len().**\n* **Extending it generates iter(), contains(), reversed(), index() and count() special methods.**\n* **Unlike `'abc.Iterable'` and `'abc.Collection'`, it is not a duck type. That is why exp. `'issubclass(MySequence, abc.Sequence)'` would return False even if MySequence had all methods defined. It however recognizes list, tuple, range, string, bytes, bytearray, array, memoryview and deque, since they are registered as Sequence's virtual subclasses.**\n```python\nfrom collections import abc\n\nclass MyAbcSequence(abc.Sequence):\n    def __init__(self, a):\n        self.a = a\n    def __len__(self):\n        return len(self.a)\n    def __getitem__(self, i):\n        return self.a[i]\n```\n\n#### Table of required and automatically available special methods:\n```text\n+------------+------------+------------+------------+--------------+\n|            |  Iterable  | Collection |  Sequence  | abc.Sequence |\n+------------+------------+------------+------------+--------------+\n| iter()     |    REQ     |    REQ     |    Yes     |     Yes      |\n| contains() |    Yes     |    Yes     |    Yes     |     Yes      |\n| len()      |            |    REQ     |    REQ     |     REQ      |\n| getitem()  |            |            |    REQ     |     REQ      |\n| reversed() |            |            |    Yes     |     Yes      |\n| index()    |            |            |            |     Yes      |\n| count()    |            |            |            |     Yes      |\n+------------+------------+------------+------------+--------------+\n```\n* **Method iter() is required for `'isinstance(\u003Cobj>, abc.Iterable)'` to return True, however any object with getitem() method works with any code expecting an iterable.**\n* **MutableSequence, Set, MutableSet, Mapping and MutableMapping ABCs are also ex&shy;tendable. Use `'\u003Cabc>.__abstractmethods__'` to get names of required methods.**\n\n\nEnum\n----\n**Class of named constants called members.**\n\n```python\nfrom enum import Enum, auto\n```\n\n```python\nclass MyEnum(Enum):\n    \u003Cmember_name> = auto()              # An increment of last numeric value or 1.\n    \u003Cmember_name> = \u003Cvalue>             # Values don't have to be hashable\u002Funique.\n    \u003Cmember_name> = \u003Cel_1>, \u003Cel_2>      # Value can be a collection, e.g. a tuple.\n```\n* **Methods receive the member they were called on as the 'self' argument.**\n* **Accessing a member named after a reserved keyword causes SyntaxError.**\n\n```python\n\u003Cmember> = \u003Cenum>.\u003Cmember_name>         # Accesses a member via enum's attribute.\n\u003Cmember> = \u003Cenum>['\u003Cmember_name>']      # Returns the member or raises KeyError.\n\u003Cmember> = \u003Cenum>(\u003Cvalue>)              # Returns the member or raises ValueError.\n\u003Cstr>    = \u003Cmember>.name                # Returns the member's name as a string.\n\u003Cobj>    = \u003Cmember>.value               # Value can't be a user-defined function.\n```\n\n```python\n\u003Clist>   = list(\u003Cenum>)                 # Returns a list containing every member.\n\u003Clist>   = \u003Cenum>._member_names_        # Returns a list containing member names.\n\u003Clist>   = [m.value for m in \u003Cenum>]    # Returns a list containing member values.\n```\n\n```python\n\u003Cenum>   = type(\u003Cmember>)               # Returns an enum. Also \u003Cmemb>.__class__.\n\u003Citer>   = itertools.cycle(\u003Cenum>)      # Returns an endless iterator of members.\n\u003Cmember> = random.choice(list(\u003Cenum>))  # Randomly selects one of enum's members.\n```\n\n### Inline\n```python\nCutlery = Enum('Cutlery', 'FORK KNIFE SPOON')\nCutlery = Enum('Cutlery', ['FORK', 'KNIFE', 'SPOON'])\nCutlery = Enum('Cutlery', {'FORK': 1, 'KNIFE': 2, 'SPOON': 3})\n```\n\n#### User-defined functions cannot be values, so they must be wrapped:\n```python\nfrom functools import partial\nLogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),\n                           'OR':  partial(lambda l, r: l or r)})\n```\n\n\nExceptions\n----------\n```python\ntry:\n    \u003Ccode>\nexcept \u003Cexception>:\n    \u003Ccode>\n```\n\n### Complex Example\n```python\ntry:\n    \u003Ccode_1>\nexcept \u003Cexception_a>:\n    \u003Ccode_2_a>\nexcept \u003Cexception_b>:\n    \u003Ccode_2_b>\nelse:\n    \u003Ccode_2_c>\nfinally:\n    \u003Ccode_3>\n```\n* **Code inside the `'else'` block will only be executed if `'try'` block had no exceptions.**\n* **Code inside the `'finally'` block will always be executed (unless a signal is received).**\n* **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).**\n* **To catch signals use `'signal.signal(signal_number, my_handler_function)'`.**\n\n### Catching Exceptions\n```python\nexcept \u003Cexception>: ...\nexcept \u003Cexception> as \u003Cname>: ...\nexcept (\u003Cexception>, [...]): ...\nexcept (\u003Cexception>, [...]) as \u003Cname>: ...\n```\n* **It also catches subclasses, e.g. `'ArithmeticError'` is caught by `'except Exception:'`.**\n* **Use `'traceback.print_exc()'` to print the full error message to standard error stream.**\n* **Use `'print(\u003Cname>)'` to print just the cause of the exception (its arguments) to stdout.**\n* **Use `'logging.exception(\u003Cstr>)'` 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](#logging).**\n* **`'sys.exc_info()'` returns type, object and traceback of the caught exception as a tuple.**\n\n### Raising Exceptions\n```python\nraise \u003Cexception>\nraise \u003Cexception>()\nraise \u003Cexception>(\u003Cobj> [, ...])\n```\n\n#### Re-raising caught exception:\n```python\nexcept \u003Cexception> [as \u003Cname>]:\n    ...\n    raise\n```\n\n### Exception Object\n```python\narguments = \u003Cname>.args\nexc_type  = \u003Cname>.__class__\nfilename  = \u003Cname>.__traceback__.tb_frame.f_code.co_filename\nfunc_name = \u003Cname>.__traceback__.tb_frame.f_code.co_name\nline_str  = linecache.getline(filename, \u003Cname>.__traceback__.tb_lineno)\ntrace_str = ''.join(traceback.format_tb(\u003Cname>.__traceback__))\nerror_msg = ''.join(traceback.format_exception(*sys.exc_info()))\n```\n\n### Built-in Exceptions\n```text\nBaseException\n +-- SystemExit                   # Raised when `sys.exit()` is called. See #Exit for details.\n +-- KeyboardInterrupt            # Raised when the user hits the interrupt key, i.e. `ctrl-c`.\n +-- Exception                    # User-defined exceptions should be derived from this class.\n      +-- ArithmeticError         # Base class for arithmetic errors such as ZeroDivisionError.\n      +-- AssertionError          # Raised by `assert \u003Cexp>` if expression returns false value.\n      +-- AttributeError          # Raised when object doesn't have requested attribute\u002Fmethod.\n      +-- EOFError                # Raised by `input()` when it hits an end-of-file condition.\n      +-- LookupError             # Base class for errors when a collection can't find an item.\n      |    +-- IndexError         # Raised when index of a sequence (list\u002Fstr) is out of range.\n      |    +-- KeyError           # Raised when a dictionary's key or a set element is missing.\n      +-- MemoryError             # Out of memory. May be too late to start deleting variables.\n      +-- NameError               # Raised when nonexistent name (variable\u002Ffunc\u002Fclass) is used.\n      |    +-- UnboundLocalError  # Raised when a local name is used before it's being defined.\n      +-- OSError                 # Errors such as FileExistsError and TimeoutError. See #Open.\n      |    +-- ConnectionError    # Errors such as BrokenPipeError and ConnectionAbortedError.\n      +-- RuntimeError            # Is raised by errors that do not fit into other categories.\n      |    +-- NotImplementedEr…  # Can be raised by abstract methods or by an unfinished code.\n      |    +-- RecursionError     # Raised if max recursion depth is exceeded (3k by default).\n      +-- StopIteration           # Raised when exhausted (empty) iterator is passed to next().\n      +-- TypeError               # Raised when argument of wrong type is passed to a function.\n      +-- ValueError              # Raised when it has the right type but inappropriate value.\n```\n\n#### Collections and their exceptions:\n```text\n+-----------+------------+------------+------------+\n|           |    List    |    Set     |    Dict    |\n+-----------+------------+------------+------------+\n| getitem() | IndexError |            |  KeyError  |\n| pop()     | IndexError |  KeyError  |  KeyError  |\n| remove()  | ValueError |  KeyError  |            |\n| index()   | ValueError |            |            |\n+-----------+------------+------------+------------+\n```\n\n#### Useful built-in exceptions:\n```python\nraise TypeError('Function received argument of the wrong type!')\nraise ValueError('Argument has the right type but its value is off!')\nraise RuntimeError('I am too lazy to define my own exception!')\n```\n\n### User-defined Exceptions\n```python\nclass MyError(Exception): pass\nclass MyInputError(MyError): pass\n```\n\n\nExit\n----\n**Exits the interpreter by raising SystemExit exception.**\n```python\nimport sys\nsys.exit()                     # Exits with exit code 0 (success).\nsys.exit(\u003Cint>)                # Exits with the passed exit code.\nsys.exit(\u003Cobj>)                # Prints to stderr and exits with 1.\n```\n\n\nPrint\n-----\n```python\nprint(\u003Cel_1>, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n```\n* **Use `'file=sys.stderr'` or `'sys.stderr.write(\u003Cstr>)'` for messages about errors.**\n* **Stdout and stderr streams hold output in a buffer until they receive a string containing '\\n' or '\\r', buffer reaches 4096 characters, `'flush=True'` is used, or the program exits.**\n\n### Pretty Print\n```python\nfrom pprint import pprint\npprint(\u003Ccollection>, width=80, depth=None, compact=False, sort_dicts=True)\n```\n* **Each item is printed on its own line if collection exceeds 'width' characters.**\n* **Nested collections that are `'depth=\u003Cint>'` levels deep get printed as `'...'`.**\n\n\nInput\n-----\n```python\n\u003Cstr> = input()\n```\n* **Reads a line from the user input or pipe if present (trailing newline gets stripped).**\n* **If argument is passed, it gets printed to the standard output before input is read.**\n* **EOFError is raised if user hits EOF (ctrl-d\u002Fctrl-z⏎) or stream is already exhausted.**\n\n\nCommand Line Arguments\n----------------------\n```python\nimport sys\nscripts_path = sys.argv[0]\narguments    = sys.argv[1:]\n```\n\n### Argument Parser\n```python\nfrom argparse import ArgumentParser\np = ArgumentParser(description=\u003Cstr>)                       # Also accepts 'usage' str.\np.add_argument('-\u003Cchar>', '--\u003Cname>', action='store_true')  # Flag (defaults to False).\np.add_argument('-\u003Cchar>', '--\u003Cname>', type=\u003Ctype>)          # Option (defaults to None).\np.add_argument('\u003Cname>', type=\u003Ctype>, nargs=1)              # Mandatory first argument.\np.add_argument('\u003Cname>', type=\u003Ctype>, nargs='+')            # Mandatory remaining args.\np.add_argument('\u003Cname>', type=\u003Ctype>, nargs='?')            # Optional argument. Also *.\nargs  = p.parse_args()                                      # Exits on a parsing error.\n\u003Cobj> = args.\u003Cname>                                         # Returns `\u003Ctype>(\u003Carg>)`.\n```\n* **Use `'help=\u003Cstr>'` to set argument description that is used by `'-h'`.**\n* **Use `'default=\u003Cobj>'` to set option's or argument's default value.**\n\n\nOpen\n----\n**Opens a file and returns the corresponding file object.**\n\n```python\n\u003Cfile> = open(\u003Cpath>, mode='r', encoding=None, newline=None)\n```\n* **`'encoding=None'` means that a default enc","该项目是一个全面的Python速查表，旨在帮助开发者快速查找和回顾Python编程中的各种语法、数据类型及常用库。其核心功能包括对Python基础数据结构（如列表、字典等）、数据类型、语法规则、系统调用、数据格式处理以及多媒体应用等方面的详细说明，并且还涵盖了异步编程、线程管理等高级主题。技术特点上，该速查表以简洁明了的方式组织内容，便于不同水平的Python程序员查阅使用。适合于日常开发中遇到具体问题时快速查找解决方案，或是作为学习Python时的一个参考手册来加深理解。",2,"2026-06-11 02:43:08","top_all"]