diff --git a/index.html b/index.html index b2a7d2aee..0a91d67ae 100644 --- a/index.html +++ b/index.html @@ -219,47 +219,47 @@
<list> = <list>[from_inclusive : to_exclusive : ±step_size]
+<list> = <list>[from_inclusive : to_exclusive : ±step_size]
-<list>.append(<el>) # Or: <list> += [<el>]
-<list>.extend(<collection>) # Or: <list> += <collection>
+<list>.append(<el>) # Or: <list> += [<el>]
+<list>.extend(<collection>) # Or: <list> += <collection>
-<list>.sort()
-<list>.reverse()
-<list> = sorted(<collection>)
-<iter> = reversed(<list>)
+<list>.sort()
+<list>.reverse()
+<list> = sorted(<collection>)
+<iter> = reversed(<list>)
-sum_of_elements = sum(<collection>)
+sum_of_elements = sum(<collection>)
elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
-sorted_by_second = sorted(<collection>, key=lambda el: el[1])
-sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
-flatter_list = list(itertools.chain.from_iterable(<list>))
-product_of_elems = functools.reduce(lambda out, x: out * x, <collection>)
-list_of_chars = list(<str>)
-
-index = <list>.index(<el>) # Returns index of first occurrence or raises ValueError.
-<list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
-<el> = <list>.pop([index]) # Removes and returns item at index or from the end.
-<list>.remove(<el>) # Removes first occurrence of item or raises ValueError.
-<list>.clear() # Removes all items. Also works on dict and set.
+sorted_by_second = sorted(<collection>, key=lambda el: el[1])
+sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
+flatter_list = list(itertools.chain.from_iterable(<list>))
+product_of_elems = functools.reduce(lambda out, x: out * x, <collection>)
+list_of_chars = list(<str>)
+
+index = <list>.index(<el>) # Returns index of first occurrence or raises ValueError.
+<list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
+<el> = <list>.pop([index]) # Removes and returns item at index or from the end.
+<list>.remove(<el>) # Removes first occurrence of item or raises ValueError.
+<list>.clear() # Removes all items. Also works on dict and set.
#Dictionary
-<view> = <dict>.keys() # Coll. of keys that reflects changes.
-<view> = <dict>.values() # Coll. of values that reflects changes.
-<view> = <dict>.items() # Coll. of key-value tuples.
+<view> = <dict>.keys() # Coll. of keys that reflects changes.
+<view> = <dict>.values() # Coll. of values that reflects changes.
+<view> = <dict>.items() # Coll. of key-value tuples.
-value = <dict>.get(key, default=None) # Returns default if key does not exist.
-value = <dict>.setdefault(key, default=None) # Same, but also adds default to dict.
-<dict> = collections.defaultdict(<type>) # Creates a dict with default value of type.
-<dict> = collections.defaultdict(lambda: 1) # Creates a dict with default value 1.
+value = <dict>.get(key, default=None) # Returns default if key does not exist.
+value = <dict>.setdefault(key, default=None) # Same, but also adds default to dict.
+<dict> = collections.defaultdict(<type>) # Creates a dict with default value of type.
+<dict> = collections.defaultdict(lambda: 1) # Creates a dict with default value 1.
-<dict>.update(<dict>)
-<dict> = dict(<collection>) # Creates a dict from coll. of key-value pairs.
-<dict> = dict(zip(keys, values)) # Creates a dict from two collections.
-<dict> = dict.fromkeys(keys [, value]) # Creates a dict from collection of keys.
+<dict>.update(<dict>)
+<dict> = dict(<collection>) # Creates a dict from coll. of key-value pairs.
+<dict> = dict(zip(keys, values)) # Creates a dict from two collections.
+<dict> = dict.fromkeys(keys [, value]) # Creates a dict from collection of keys.
-value = <dict>.pop(key) # Removes item from dictionary.
-{k: v for k, v in <dict>.items() if k in keys} # Filters dictionary by keys.
+value = <dict>.pop(key) # Removes item from dictionary.
+{k: v for k, v in <dict>.items() if k in keys} # Filters dictionary by keys.
Counter
>>> from collections import Counter
@@ -270,33 +270,33 @@ Counter
('blue', 3)
#Set
-<set> = set()
+<set> = set()
-<set>.add(<el>) # Or: <set> |= {<el>}
-<set>.update(<collection>) # Or: <set> |= <set>
+<set>.add(<el>) # Or: <set> |= {<el>}
+<set>.update(<collection>) # Or: <set> |= <set>
-<set> = <set>.union(<coll.>) # Or: <set> | <set>
-<set> = <set>.intersection(<coll.>) # Or: <set> & <set>
-<set> = <set>.difference(<coll.>) # Or: <set> - <set>
-<set> = <set>.symmetric_difference(<coll.>) # Or: <set> ^ <set>
-<bool> = <set>.issubset(<coll.>) # Or: <set> <= <set>
-<bool> = <set>.issuperset(<coll.>) # Or: <set> >= <set>
+<set> = <set>.union(<coll.>) # Or: <set> | <set>
+<set> = <set>.intersection(<coll.>) # Or: <set> & <set>
+<set> = <set>.difference(<coll.>) # Or: <set> - <set>
+<set> = <set>.symmetric_difference(<coll.>) # Or: <set> ^ <set>
+<bool> = <set>.issubset(<coll.>) # Or: <set> <= <set>
+<bool> = <set>.issuperset(<coll.>) # Or: <set> >= <set>
-<set>.remove(<el>) # Raises KeyError.
-<set>.discard(<el>) # Doesn't raise an error.
+<set>.remove(<el>) # Raises KeyError.
+<set>.discard(<el>) # Doesn't raise an error.
Frozen Set
- Is immutable and hashable.
- That means it can be used as a key in a dictionary or as an element in a set.
-<frozenset> = frozenset(<collection>)
+<frozenset> = frozenset(<collection>)
#Tuple
Tuple is an immutable and hashable list.
-<tuple> = ()
-<tuple> = (<el>, )
-<tuple> = (<el_1>, <el_2>, ...)
+<tuple> = ()
+<tuple> = (<el>, )
+<tuple> = (<el_1>, <el_2>, ...)
Named Tuple
Tuple's subclass with named elements.
@@ -314,35 +314,35 @@ Named Tuple
('x', 'y')
#Range
-<range> = range(to_exclusive)
-<range> = range(from_inclusive, to_exclusive)
-<range> = range(from_inclusive, to_exclusive, ±step_size)
+<range> = range(to_exclusive)
+<range> = range(from_inclusive, to_exclusive)
+<range> = range(from_inclusive, to_exclusive, ±step_size)
-from_inclusive = <range>.start
-to_exclusive = <range>.stop
+from_inclusive = <range>.start
+to_exclusive = <range>.stop
#Enumerate
-for i, el in enumerate(<collection> [, i_start]):
+for i, el in enumerate(<collection> [, i_start]):
...
#Iterator
-<iter> = iter(<collection>) # Calling `iter(<iter>)` returns unmodified iterator.
-<iter> = iter(<function>, to_exclusive) # Sequence of return values until 'to_exclusive'.
-<el> = next(<iter> [, default]) # Raises StopIteration or returns 'default' on end.
+<iter> = iter(<collection>) # Calling `iter(<iter>)` returns unmodified iterator.
+<iter> = iter(<function>, to_exclusive) # Sequence of return values until 'to_exclusive'.
+<el> = next(<iter> [, default]) # Raises StopIteration or returns 'default' on end.
Itertools
from itertools import count, repeat, cycle, chain, islice
-<iter> = count(start=0, step=1) # Returns incremented value endlessly.
-<iter> = repeat(<el> [, times]) # Returns element endlessly or 'times' times.
-<iter> = cycle(<collection>) # Repeats the sequence indefinitely.
+<iter> = count(start=0, step=1) # Returns incremented value endlessly.
+<iter> = repeat(<el> [, times]) # Returns element endlessly or 'times' times.
+<iter> = cycle(<collection>) # Repeats the sequence indefinitely.
-<iter> = chain(<coll.>, <coll.> [, ...]) # Empties collections in order.
-<iter> = chain.from_iterable(<collection>) # Empties collections inside a collection in order.
+<iter> = chain(<coll.>, <coll.> [, ...]) # Empties collections in order.
+<iter> = chain.from_iterable(<collection>) # Empties collections inside a collection in order.
-<iter> = islice(<collection>, to_exclusive)
-<iter> = islice(<collection>, from_inclusive, to_exclusive)
-<iter> = islice(<collection>, from_inclusive, to_exclusive, +step_size)
+<iter> = islice(<collection>, to_exclusive)
+<iter> = islice(<collection>, from_inclusive, to_exclusive)
+<iter> = islice(<collection>, from_inclusive, to_exclusive, +step_size)
#Generator
@@ -365,8 +365,8 @@ #Type
- Every object has a type.
- Type and class are synonymous.
-<type> = type(<el>) # Or: <el>.__class__
-<bool> = isinstance(<el>, <type>) # Or: issubclass(type(<el>), <type>)
+<type> = type(<el>) # Or: <el>.__class__
+<bool> = isinstance(<el>, <type>) # Or: issubclass(type(<el>), <type>)
>>> type('a'), 'a'.__class__, str
(<class 'str'>, <class 'str'>, <class 'str'>)
@@ -402,31 +402,31 @@ ABC
+--------------------+----------+----------+------+---------+--------+
#String
-<str> = <str>.strip() # Strips all whitespace characters from both ends.
-<str> = <str>.strip('<chars>') # Strips all passed characters from both ends.
+<str> = <str>.strip() # Strips all whitespace characters from both ends.
+<str> = <str>.strip('<chars>') # Strips all passed characters from both ends.
-<list> = <str>.split() # Splits on one or more whitespace characters.
-<list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
-<list> = <str>.splitlines(keepends=False) # Splits on line breaks. Keeps them if 'keepends'.
-<str> = <str>.join(<coll_of_strings>) # Joins elements using string as separator.
+<list> = <str>.split() # Splits on one or more whitespace characters.
+<list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
+<list> = <str>.splitlines(keepends=False) # Splits on line breaks. Keeps them if 'keepends'.
+<str> = <str>.join(<coll_of_strings>) # Joins elements using string as separator.
-<bool> = <sub_str> in <str> # Checks if string contains a substring.
-<bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
-<bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
-<int> = <str>.find(<sub_str>) # Returns start index of first match or -1.
-<int> = <str>.index(<sub_str>) # Same but raises ValueError.
+<bool> = <sub_str> in <str> # Checks if string contains a substring.
+<bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
+<bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
+<int> = <str>.find(<sub_str>) # Returns start index of first match or -1.
+<int> = <str>.index(<sub_str>) # Same but raises ValueError.
-<str> = <str>.replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
-<bool> = <str>.isnumeric() # True if str contains only numeric characters.
-<list> = textwrap.wrap(<str>, width) # Nicely breaks string into lines.
+<str> = <str>.replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
+<bool> = <str>.isnumeric() # True if str contains only numeric characters.
+<list> = textwrap.wrap(<str>, width) # Nicely breaks string into lines.
- Also:
'lstrip()'
, 'rstrip()'
.
- Also:
'lower()'
, 'upper()'
, 'capitalize()'
and 'title()'
.
Char
-<str> = chr(<int>) # Converts int to unicode char.
-<int> = ord(<str>) # Converts unicode char to int.
+<str> = chr(<int>) # Converts int to unicode char.
+<int> = ord(<str>) # Converts unicode char to int.
>>> ord('0'), ord('9')
(48, 57)
@@ -437,12 +437,12 @@ Char
#Regex
import re
-<str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences.
-<list> = re.findall(<regex>, text) # Returns all occurrences.
-<list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
-<Match> = re.search(<regex>, text) # Searches for first occurrence of pattern.
-<Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
-<iter> = re.finditer(<regex>, text) # Returns all occurrences as match objects.
+<str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences.
+<list> = re.findall(<regex>, text) # Returns all occurrences.
+<list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
+<Match> = re.search(<regex>, text) # Searches for first occurrence of pattern.
+<Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
+<iter> = re.finditer(<regex>, text) # Returns all occurrences as match objects.
- Argument
'flags=re.IGNORECASE'
can be used with all functions.
@@ -452,11 +452,11 @@ #Regex
- Use
'?'
to make an operator non-greedy.
Match Object
-<str> = <Match>.group() # Whole match. Also group(0).
-<str> = <Match>.group(1) # Part in first bracket.
-<tuple> = <Match>.groups() # All bracketed parts.
-<int> = <Match>.start() # Start index of a match.
-<int> = <Match>.end() # Exclusive end index of a match.
+<str> = <Match>.group() # Whole match. Also group(0).
+<str> = <Match>.group(1) # Part in first bracket.
+<tuple> = <Match>.groups() # All bracketed parts.
+<int> = <Match>.start() # Start index of a match.
+<int> = <Match>.end() # Exclusive end index of a match.
Special Sequences
@@ -468,8 +468,8 @@ Special Sequences
'\w' == '[a-zA-Z0-9_]' # Alphanumeric
#Format
-<str> = f'{<el_1>}, {<el_2>}'
-<str> = '{}, {}'.format(<el_1>, <el_2>)
+<str> = f'{<el_1>}, {<el_2>}'
+<str> = '{}, {}'.format(<el_1>, <el_2>)
Attributes
>>> from collections import namedtuple
@@ -481,12 +481,12 @@ Attributes
'187'
General Options
-{<el>:<10} # '<el> '
-{<el>:^10} # ' <el> '
-{<el>:>10} # ' <el>'
+{<el>:<10} # '<el> '
+{<el>:^10} # ' <el> '
+{<el>:>10} # ' <el>'
-{<el>:.<10} # '<el>......'
-{<el>:>0} # '<el>'
+{<el>:.<10} # '<el>......'
+{<el>:>0} # '<el>'
Strings
'!r'
calls object's repr() method, instead of str(), to get a string.
@@ -541,19 +541,19 @@ Ints
{90:b} # '1011010'
#Numbers
-<int> = int(<float/str/bool>) # Or: math.floor(<float>)
-<float> = float(<int/str/bool>)
-<complex> = complex(real=0, imag=0) # Or: <real> + <real>j
-<Fraction> = fractions.Fraction(numerator=0, denominator=1)
+<int> = int(<float/str/bool>) # Or: math.floor(<float>)
+<float> = float(<int/str/bool>)
+<complex> = complex(real=0, imag=0) # Or: <real> + <real>j
+<Fraction> = fractions.Fraction(numerator=0, denominator=1)
-'int(<str>)'
and 'float(<str>)'
raise 'ValueError' on malformed strings.
+'int(<str>)'
and 'float(<str>)'
raise 'ValueError' on malformed strings.
Basic Functions
-<num> = pow(<num>, <num>) # Or: <num> ** <num>
-<real> = abs(<num>)
-<int> = round(<real>)
-<real> = round(<real>, ±ndigits) # `round(126, -1) == 130`
+<num> = pow(<num>, <num>) # Or: <num> ** <num>
+<real> = abs(<num>)
+<int> = round(<real>)
+<real> = round(<real>, ±ndigits) # `round(126, -1) == 130`
Math
from math import e, pi, inf, nan
@@ -565,24 +565,24 @@ Statistics
Random
from random import random, randint, choice, shuffle
-<float> = random()
-<int> = randint(from_inclusive, to_inclusive)
-<el> = choice(<list>)
-shuffle(<list>)
+<float> = random()
+<int> = randint(from_inclusive, to_inclusive)
+<el> = choice(<list>)
+shuffle(<list>)
Bin, Hex
-<int> = 0b<bin> # Or: 0x<hex>
-<int> = int('0b<bin>', 0) # Or: int('0x<hex>', 0)
-<int> = int('<bin>', 2) # Or: int('<hex>', 16)
-'0b<bin>' = bin(<int>) # Or: '0x<hex>' = hex(<int>)
+<int> = 0b<bin> # Or: 0x<hex>
+<int> = int('0b<bin>', 0) # Or: int('0x<hex>', 0)
+<int> = int('<bin>', 2) # Or: int('<hex>', 16)
+'0b<bin>' = bin(<int>) # Or: '0x<hex>' = hex(<int>)
Bitwise Operators
-<int> = <int> & <int> # And
-<int> = <int> | <int> # Or
-<int> = <int> ^ <int> # Xor (0 if both bits equal)
-<int> = <int> << n_bits # Shift left
-<int> = <int> >> n_bits # Shift right
-<int> = ~<int> # Compliment (flips bits)
+<int> = <int> & <int> # And
+<int> = <int> | <int> # Or
+<int> = <int> ^ <int> # Xor (0 if both bits equal)
+<int> = <int> << n_bits # Shift left
+<int> = <int> >> n_bits # Shift right
+<int> = ~<int> # Compliment (flips bits)
#Combinatorics
@@ -622,49 +622,49 @@ #Datetime
from dateutil.tz import UTC, tzlocal, gettz
Constructors
-<D> = date(year, month, day)
-<T> = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)
-<DT> = datetime(year, month, day, hour=0, minute=0, second=0, ...)
-<TD> = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
+<D> = date(year, month, day)
+<T> = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)
+<DT> = datetime(year, month, day, hour=0, minute=0, second=0, ...)
+<TD> = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
minutes=0, hours=0, weeks=0)
-- Use
'<D/DT>.weekday()'
to get the day of the week (Mon == 0).
+- Use
'<D/DT>.weekday()'
to get the day of the week (Mon == 0).
'fold=1'
means second pass in case of time jumping back for one hour.
Now
-<D/DTn> = D/DT.today() # Current local date or naive datetime.
-<DTn> = DT.utcnow() # Naive datetime from current UTC time.
-<DTa> = DT.now(<tzinfo>) # Aware datetime from current tz time.
+<D/DTn> = D/DT.today() # Current local date or naive datetime.
+<DTn> = DT.utcnow() # Naive datetime from current UTC time.
+<DTa> = DT.now(<tzinfo>) # Aware datetime from current tz time.
-- To extract time use
'<DTn>.time()'
, '<DTa>.time()'
or '<DTa>.timetz()'
.
+- To extract time use
'<DTn>.time()'
, '<DTa>.time()'
or '<DTa>.timetz()'
.
Timezone
-<tzinfo> = UTC # UTC timezone. London without DST.
-<tzinfo> = tzlocal() # Local timezone. Also gettz().
-<tzinfo> = gettz('<Cont.>/<City>') # Timezone from 'Continent/City_Name' str.
+<tzinfo> = UTC # UTC timezone. London without DST.
+<tzinfo> = tzlocal() # Local timezone. Also gettz().
+<tzinfo> = gettz('<Cont.>/<City>') # Timezone from 'Continent/City_Name' str.
-<DTa> = <DT>.astimezone(<tzinfo>) # Datetime, converted to passed timezone.
-<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>) # Unconverted object with new timezone.
+<DTa> = <DT>.astimezone(<tzinfo>) # Datetime, converted to passed timezone.
+<Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>) # Unconverted object with new timezone.
Encode
-<D/T/DT> = D/T/DT.fromisoformat('<iso>') # Object from ISO string.
-<DT> = DT.strptime(<str>, '<format>') # Datetime from str, according to format.
-<D/DTn> = D/DT.fromordinal(<int>) # D/DTn from days since Christ, at midnight.
-<DTn> = DT.fromtimestamp(<real>) # Local time DTn from seconds since Epoch.
-<DTa> = DT.fromtimestamp(<real>, <tz.>) # Aware datetime from seconds since Epoch.
+<D/T/DT> = D/T/DT.fromisoformat('<iso>') # Object from ISO string.
+<DT> = DT.strptime(<str>, '<format>') # Datetime from str, according to format.
+<D/DTn> = D/DT.fromordinal(<int>) # D/DTn from days since Christ, at midnight.
+<DTn> = DT.fromtimestamp(<real>) # Local time DTn from seconds since Epoch.
+<DTa> = DT.fromtimestamp(<real>, <tz.>) # Aware datetime from seconds since Epoch.
-- ISO strings come in following forms:
'YYYY-MM-DD'
, 'HH:MM:SS.ffffff[±<offset>]'
, or both separated by 'T'
. Offset is formatted as: 'HH:MM'
.
+- ISO strings come in following forms:
'YYYY-MM-DD'
, 'HH:MM:SS.ffffff[±<offset>]'
, or both separated by 'T'
. Offset is formatted as: 'HH:MM'
.
- On Unix systems Epoch is
'1970-01-01 00:00 UTC'
, '1970-01-01 01:00 CET'
, …
Decode
-<str> = <D/T/DT>.isoformat() # ISO string representation.
-<str> = <D/T/DT>.strftime('<format>') # Custom string representation.
-<int> = <D/DT>.toordinal() # Days since Christ, ignoring time and tz.
-<float> = <DTn>.timestamp() # Seconds since Epoch from DTn in local time.
-<float> = <DTa>.timestamp() # Seconds since Epoch from DTa.
+<str> = <D/T/DT>.isoformat() # ISO string representation.
+<str> = <D/T/DT>.strftime('<format>') # Custom string representation.
+<int> = <D/DT>.toordinal() # Days since Christ, ignoring time and tz.
+<float> = <DTn>.timestamp() # Seconds since Epoch from DTn in local time.
+<float> = <DTa>.timestamp() # Seconds since Epoch from DTa.
Format
>>> from datetime import datetime
@@ -677,21 +677,21 @@ Format
When parsing, '%z'
also accepts '±HH:MM'
.
Arithmetics
-<D/DT> = <D/DT> ± <TD>
-<TD> = <TD> ± <TD>
-<TD> = <TD> */ <real>
-<float> = <TD> / <TD>
+<D/DT> = <D/DT> ± <TD>
+<TD> = <TD> ± <TD>
+<TD> = <TD> */ <real>
+<float> = <TD> / <TD>
#Arguments
Inside Function Call
-<function>(<positional_args>) # f(0, 0)
-<function>(<keyword_args>) # f(x=0, y=0)
-<function>(<positional_args>, <keyword_args>) # f(0, y=0)
+<function>(<positional_args>) # f(0, 0)
+<function>(<keyword_args>) # f(x=0, y=0)
+<function>(<positional_args>, <keyword_args>) # f(0, y=0)
Inside Function Definition
-def f(<nondefault_args>): # def f(x, y):
-def f(<default_args>): # def f(x=0, y=0):
-def f(<nondefault_args>, <default_args>): # def f(x, y=0):
+def f(<nondefault_args>): # def f(x, y):
+def f(<default_args>): # def f(x=0, y=0):
+def f(<nondefault_args>, <default_args>): # def f(x, y=0):
#Splat Operator
Inside Function Call
@@ -732,23 +732,23 @@ Legal argument combinations:
def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
Other Uses
-<list> = [*<collection> [, ...]]
-<set> = {*<collection> [, ...]}
-<tuple> = (*<collection>, [...])
-<dict> = {**<dict> [, ...]}
+<list> = [*<collection> [, ...]]
+<set> = {*<collection> [, ...]}
+<tuple> = (*<collection>, [...])
+<dict> = {**<dict> [, ...]}
-head, *body, tail = <collection>
+head, *body, tail = <collection>
#Inline
Lambda
-<function> = lambda: <return_value>
-<function> = lambda <argument_1>, <argument_2>: <return_value>
+<function> = lambda: <return_value>
+<function> = lambda <argument_1>, <argument_2>: <return_value>
Comprehension
-<list> = [i+1 for i in range(10)] # [1, 2, ..., 10]
-<set> = {i for i in range(10) if i > 5} # {6, 7, 8, 9}
-<iter> = (i+5 for i in range(10)) # (5, 6, ..., 14)
-<dict> = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
+<list> = [i+1 for i in range(10)] # [1, 2, ..., 10]
+<set> = {i for i in range(10) if i > 5} # {6, 7, 8, 9}
+<iter> = (i+5 for i in range(10)) # (5, 6, ..., 14)
+<dict> = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
out = [i+j for i in range(10) for j in range(10)]
@@ -760,16 +760,16 @@ Is the same as:
Map, Filter, Reduce
from functools import reduce
-<iter> = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10)
-<iter> = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9)
-<int> = reduce(lambda out, x: out + x, range(10)) # 45
+<iter> = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10)
+<iter> = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9)
+<int> = reduce(lambda out, x: out + x, range(10)) # 45
Any, All
-<bool> = any(<collection>) # False if empty.
-<bool> = all(el[1] for el in <collection>) # True if empty.
+<bool> = any(<collection>) # False if empty.
+<bool> = all(el[1] for el in <collection>) # True if empty.
If - Else
-<expression_if_true> if <condition> else <expression_if_false>
+<expression_if_true> if <condition> else <expression_if_false>
>>> [a if a else 'zero' for a in (0, 1, 0, 3)]
['zero', 1, 'zero', 3]
@@ -804,11 +804,11 @@ #Closure
- If multiple nested functions within enclosing function reference the same value, that value gets shared.
-- To dynamically access function's first free variable use
'<function>.__closure__[0].cell_contents'
.
+- To dynamically access function's first free variable use
'<function>.__closure__[0].cell_contents'
.
Partial
from functools import partial
-<function> = partial(<function> [, <arg_1>, <arg_2>, ...])
+<function> = partial(<function> [, <arg_1>, <arg_2>, ...])
>>> import operator as op
>>> multiply_by_3 = partial(op.mul, 3)
@@ -817,7 +817,7 @@ Partial
- 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.
-- A few examples being
'defaultdict(<function>)'
, 'iter(<function>, to_exclusive)'
and dataclass's 'field(default_factory=<function>)'
.
+- A few examples being
'defaultdict(<function>)'
, 'iter(<function>, to_exclusive)'
and dataclass's 'field(default_factory=<function>)'
.
Nonlocal
If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or a 'nonlocal'.
@@ -867,7 +867,7 @@ LRU Cache
return n if n < 2 else fib(n-2) + fib(n-1)
-- Recursion depth is limited to 1000 by default. To increase it use
'sys.setrecursionlimit(<depth>)'
.
+- Recursion depth is limited to 1000 by default. To increase it use
'sys.setrecursionlimit(<depth>)'
.
Parametrized Decorator
A decorator that accepts arguments and returns a normal decorator that accepts a function.
@@ -906,18 +906,18 @@ #Class
If only repr() is defined, it will be also used for str().
Str() use cases:
-print(<el>)
-print(f'{<el>}')
-raise Exception(<el>)
-logging.debug(<el>)
-csv.writer(<file>).writerow([<el>])
+print(<el>)
+print(f'{<el>}')
+raise Exception(<el>)
+logging.debug(<el>)
+csv.writer(<file>).writerow([<el>])
Repr() use cases:
-print([<el>])
-print(f'{<el>!r}')
->>> <el>
+print([<el>])
+print(f'{<el>!r}')
+>>> <el>
loguru.logger.exception()
-Z = dataclasses.make_dataclass('Z', ['a']); print(Z(<el>))
+Z = dataclasses.make_dataclass('Z', ['a']); print(Z(<el>))
Constructor Overloading
class <name>:
@@ -965,13 +965,13 @@ Dataclass
@dataclass(order=False, frozen=False)
class <class_name>:
- <attr_name_1>: <type>
- <attr_name_2>: <type> = <default_value>
- <attr_name_3>: list/dict/set = field(default_factory=list/dict/set)
+ <attr_name_1>: <type>
+ <attr_name_2>: <type> = <default_value>
+ <attr_name_3>: list/dict/set = field(default_factory=list/dict/set)
- An object can be made sortable with
'order=True'
or immutable with 'frozen=True'
.
-- Function field() is needed because
'<attr_name>: list = []'
would make a list that is shared among all instances.
+- Function field() is needed because
'<attr_name>: list = []'
would make a list that is shared among all instances.
- Default_factory can be any callable.
Slots
@@ -983,8 +983,8 @@ Slots
Copy
from copy import copy, deepcopy
-<object> = copy(<object>)
-<object> = deepcopy(<object>)
+<object> = copy(<object>)
+<object> = deepcopy(<object>)
#Duck Types
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.
@@ -1087,10 +1087,10 @@ Context Manager
Hello World!
List of existing context managers:
-with open('<path>', ...) as file: ...
-with wave.open('<path>', ...) as wave_file: ...
-with memoryview(<bytes/bytearray/array>) as view: ...
-db = sqlite3.connect('<path>'); with db: db.execute('<insert_query>')
+with open('<path>', ...) as file: ...
+with wave.open('<path>', ...) as wave_file: ...
+with memoryview(<bytes/bytearray/array>) as view: ...
+db = sqlite3.connect('<path>'); with db: db.execute('<insert_query>')
lock = threading.RLock(); with lock: ...
#Iterable Duck Types
@@ -1115,7 +1115,7 @@ Iterable
Collection
- Only required methods are iter() and len().
-- This cheatsheet actually means
'<iterable>'
when it uses '<collection>'
.
+- This cheatsheet actually means
'<iterable>'
when it uses '<collection>'
.
- I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'.
class MyCollection:
@@ -1184,9 +1184,9 @@ #Enum
from enum import Enum, auto
class <enum_name>(Enum):
- <member_name_1> = <value_1>
- <member_name_2> = <value_2_a>, <value_2_b>
- <member_name_3> = auto()
+ <member_name_1> = <value_1>
+ <member_name_2> = <value_2_a>, <value_2_b>
+ <member_name_3> = auto()
@classmethod
def get_member_names(cls):
@@ -1196,16 +1196,16 @@ #Enum
If there are no numeric values before auto(), it returns 1.
Otherwise it returns an increment of last numeric value.
-<member> = <enum>.<member_name>
-<member> = <enum>['<member_name>']
-<member> = <enum>(<value>)
-name = <member>.name
-value = <member>.value
+<member> = <enum>.<member_name>
+<member> = <enum>['<member_name>']
+<member> = <enum>(<value>)
+name = <member>.name
+value = <member>.value
-list_of_members = list(<enum>)
-member_names = [a.name for a in <enum>]
-member_values = [a.value for a in <enum>]
-random_member = random.choice(list(<enum>))
+list_of_members = list(<enum>)
+member_names = [a.name for a in <enum>]
+member_values = [a.value for a in <enum>]
+random_member = random.choice(list(<enum>))
Inline
Cutlery = Enum('Cutlery', ['fork', 'knife', 'spoon'])
@@ -1223,36 +1223,36 @@ Functions can not be values,
#Exceptions
Basic Example
try:
- <code>
-except <exception>:
- <code>
+ <code>
+except <exception>:
+ <code>
Complex Example
try:
- <code_1>
-except <exception_a>:
- <code_2_a>
-except <exception_b>:
- <code_2_b>
+ <code_1>
+except <exception_a>:
+ <code_2_a>
+except <exception_b>:
+ <code_2_b>
else:
- <code_2_c>
+ <code_2_c>
finally:
- <code_3>
+ <code_3>
Catching Exceptions
-except <exception>:
-except <exception> as <name>:
-except (<exception_1>, <exception_2>, ...):
-except (<exception_1>, <exception_2>, ...) as <name>:
+except <exception>:
+except <exception> as <name>:
+except (<exception_1>, <exception_2>, ...):
+except (<exception_1>, <exception_2>, ...) as <name>:
- Also catches subclasses of the exception.
Raising Exceptions
-raise <exception>
-raise <exception>()
-raise <exception>(<el>)
-raise <exception>(<el_1>, <el_2>, ...)
+raise <exception>
+raise <exception>()
+raise <exception>(<el>)
+raise <exception>(<el_1>, <el_2>, ...)
Useful built-in exceptions:
raise ValueError('Argument is of right type but inappropriate value!')
@@ -1260,8 +1260,8 @@ Useful built-in exceptions:
raise RuntimeError('None of above!')
Re-raising caught exception:
-except <exception>:
- <code>
+except <exception>:
+ <code>
raise
Common Built-in Exceptions
@@ -1284,7 +1284,7 @@ Common Built-in Exceptions
| +-- RecursionError # Raised when the the maximum recursion depth is exceeded.
+-- TypeError # Raised when an argument is of wrong type.
+-- ValueError # When an argument is of right type but inappropriate value.
- +-- UnicodeError # Raised when encoding/decoding strings from/to bytes fails.
+ +-- UnicodeError # Raised when encoding/decoding strings from/to bytes fails.
User-defined Exceptions
class MyError(Exception):
@@ -1294,7 +1294,7 @@ User-defined Exceptions
pass
#Print
-print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
+print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
- Use
'file=sys.stderr'
for errors.
@@ -1313,7 +1313,7 @@ #Input
- Trailing newline gets stripped.
- Prompt string is printed to the standard output before reading input.
-<str> = input(prompt=None)
+<str> = input(prompt=None)
Prints lines until EOF:
while True:
@@ -1329,21 +1329,21 @@ Argparse
from argparse import ArgumentParser, FileType
-p = ArgumentParser(description=<str>)
-p.add_argument('-<short_name>', '--<name>', action='store_true') # Flag
-p.add_argument('-<short_name>', '--<name>', type=<type>) # Option
-p.add_argument('<name>', type=<type>, nargs=1) # Argument
-p.add_argument('<name>', type=<type>, nargs='+') # Arguments
+p = ArgumentParser(description=<str>)
+p.add_argument('-<short_name>', '--<name>', action='store_true') # Flag
+p.add_argument('-<short_name>', '--<name>', type=<type>) # Option
+p.add_argument('<name>', type=<type>, nargs=1) # Argument
+p.add_argument('<name>', type=<type>, nargs='+') # Arguments
args = p.parse_args()
-value = args.<name>
+value = args.<name>
-- Use
'help=<str>'
for argument description.
-- Use
'type=FileType(<mode>)'
for files.
+- Use
'help=<str>'
for argument description.
+- Use
'type=FileType(<mode>)'
for files.
#Open
Opens a file and returns a corresponding file object.
-<file> = open('<path>', mode='r', encoding=None, newline=None)
+<file> = open('<path>', mode='r', encoding=None, newline=None)
'encoding=None'
means default encoding is used, which is platform dependent. Best practice is to use 'encoding="utf-8"'
whenever possible.
@@ -1370,19 +1370,19 @@ Exceptions
'OSError'
is the parent class of all listed exceptions.
File
-<file>.seek(0) # Moves to the start of the file.
-<file>.seek(offset) # Moves 'offset' chars/bytes from the start.
-<file>.seek(0, 2) # Moves to the end of the file.
-<bin_file>.seek(±offset, <anchor>) # Anchor: 0 start, 1 current pos., 2 end.
+<file>.seek(0) # Moves to the start of the file.
+<file>.seek(offset) # Moves 'offset' chars/bytes from the start.
+<file>.seek(0, 2) # Moves to the end of the file.
+<bin_file>.seek(±offset, <anchor>) # Anchor: 0 start, 1 current pos., 2 end.
-<str/bytes> = <file>.read(size=-1) # Reads 'size' chars/bytes or until EOF.
-<str/bytes> = <file>.readline() # Returns a line or empty string on EOF.
-<list> = <file>.readlines() # Returns a list of lines or empty list.
-<str/bytes> = next(<file>) # Returns a line using buffer. Do not mix.
+<str/bytes> = <file>.read(size=-1) # Reads 'size' chars/bytes or until EOF.
+<str/bytes> = <file>.readline() # Returns a line or empty string on EOF.
+<list> = <file>.readlines() # Returns a list of lines or empty list.
+<str/bytes> = next(<file>) # Returns a line using buffer. Do not mix.
-<file>.write(<str/bytes>) # Writes a string or bytes object.
-<file>.writelines(<coll.>) # Writes a coll. of strings or bytes objects.
-<file>.flush() # Flushes write buffer.
+<file>.write(<str/bytes>) # Writes a string or bytes object.
+<file>.writelines(<coll.>) # Writes a coll. of strings or bytes objects.
+<file>.flush() # Flushes write buffer.
- Methods do not add or strip trailing newlines, even writelines().
@@ -1401,35 +1401,35 @@ #Path
from os import path, listdir
from glob import glob
-<bool> = path.exists('<path>')
-<bool> = path.isfile('<path>')
-<bool> = path.isdir('<path>')
+<bool> = path.exists('<path>')
+<bool> = path.isfile('<path>')
+<bool> = path.isdir('<path>')
-<list> = listdir('<path>') # List of filenames located at 'path'.
-<list> = glob('<pattern>') # Filenames matching the wildcard pattern.
+<list> = listdir('<path>') # List of filenames located at 'path'.
+<list> = glob('<pattern>') # Filenames matching the wildcard pattern.
Pathlib
from pathlib import Path
cwd = Path()
-<Path> = Path('<path>' [, '<path>', <Path>, ...])
-<Path> = <Path> / '<dir>' / '<file>'
+<Path> = Path('<path>' [, '<path>', <Path>, ...])
+<Path> = <Path> / '<dir>' / '<file>'
-<bool> = <Path>.exists()
-<bool> = <Path>.is_file()
-<bool> = <Path>.is_dir()
+<bool> = <Path>.exists()
+<bool> = <Path>.is_file()
+<bool> = <Path>.is_dir()
-<iter> = <Path>.iterdir() # Iterator of filenames located at path.
-<iter> = <Path>.glob('<pattern>') # Filenames matching the wildcard pattern.
+<iter> = <Path>.iterdir() # Iterator of filenames located at path.
+<iter> = <Path>.glob('<pattern>') # Filenames matching the wildcard pattern.
-<str> = str(<Path>) # Returns path as a string.
-<tup.> = <Path>.parts # Returns all components as strings.
-<Path> = <Path>.resolve() # Returns absolute Path without symlinks.
+<str> = str(<Path>) # Returns path as a string.
+<tup.> = <Path>.parts # Returns all components as strings.
+<Path> = <Path>.resolve() # Returns absolute Path without symlinks.
-<str> = <Path>.name # Final component.
-<str> = <Path>.stem # Final component without extension.
-<str> = <Path>.suffix # Final component's extension.
-<Path> = <Path>.parent # Path without final component.
+<str> = <Path>.name # Final component.
+<str> = <Path>.stem # Final component without extension.
+<str> = <Path>.suffix # Final component's extension.
+<Path> = <Path>.parent # Path without final component.
#Command Execution
Files and Directories Commands
@@ -1438,18 +1438,18 @@ Files and Directories Commands
All exceptions are either 'OSError' or its subclasses.
import os
-os.chdir(<path>) # Changes the current working directory.
-<str> = os.getcwd() # Returns current working directory.
+os.chdir(<path>) # Changes the current working directory.
+<str> = os.getcwd() # Returns current working directory.
-os.remove(<path>) # Deletes the file.
-os.rmdir(<path>) # Deletes empty directory.
-shutil.rmtree(<path>) # Deletes an entire directory tree.
+os.remove(<path>) # Deletes the file.
+os.rmdir(<path>) # Deletes empty directory.
+shutil.rmtree(<path>) # Deletes an entire directory tree.
os.rename(from, to) # Renames the file or directory.
os.replace(from, to) # Same, but overwrites 'to' if it exists.
-os.mkdir(<path>, mode=0o777) # Creates a directory.
-<iter> = os.scandir(path='.') # Returns os.DirEntry objects located at path.
+os.mkdir(<path>, mode=0o777) # Creates a directory.
+<iter> = os.scandir(path='.') # Returns os.DirEntry objects located at path.
DirEntry:
<str> = <DirEntry>.name # Final component of the path.
@@ -1462,7 +1462,7 @@ DirEntry:
Shell Commands
import os
-<str> = os.popen('<shell_command>').read()
+<str> = os.popen('<shell_command>').read()
Using subprocess:
>>> import subprocess, shlex
@@ -1521,8 +1521,8 @@ Write Rows to CSV File
#JSON
import json
-<str> = json.dumps(<object>, ensure_ascii=True, indent=None)
-<object> = json.loads(<str>)
+<str> = json.dumps(<object>, ensure_ascii=True, indent=None)
+<object> = json.loads(<str>)
Read Object from JSON File
def read_json_file(filename):
@@ -1536,8 +1536,8 @@ Write Object to JSON File
#Pickle
import pickle
-<bytes> = pickle.dumps(<object>)
-<object> = pickle.loads(<bytes>)
+<bytes> = pickle.dumps(<object>)
+<object> = pickle.loads(<bytes>)
Read Object from File
def read_pickle_file(filename):
@@ -1552,7 +1552,7 @@ Write Object to File
#SQLite
Server-less database engine that stores each database into separate file.
import sqlite3
-db = sqlite3.connect('<path>') # Also ':memory:'.
+db = sqlite3.connect('<path>') # Also ':memory:'.
...
db.close()
@@ -1560,22 +1560,22 @@ #SQLite
New database will be created if path doesn't exist.
Read
-cursor = db.execute('<query>')
+cursor = db.execute('<query>')
if cursor:
- <tuple> = cursor.fetchone() # First row.
- <list> = cursor.fetchall() # Remaining rows.
+ <tuple> = cursor.fetchone() # First row.
+ <list> = cursor.fetchall() # Remaining rows.
- Returned values can be of type str, int, float, bytes or None.
Write
-db.execute('<query>')
+db.execute('<query>')
db.commit()
Placeholders
-db.execute('<query>', <list/tuple>) # Replaces '?'s in query with values.
-db.execute('<query>', <dict/namedtuple>) # Replaces ':<key>'s with values.
-db.executemany('<query>', <coll_of_above>) # Runs execute() many times.
+db.execute('<query>', <list/tuple>) # Replaces '?'s in query with values.
+db.execute('<query>', <dict/namedtuple>) # Replaces ':<key>'s with values.
+db.executemany('<query>', <coll_of_above>) # Runs execute() many times.
- Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.
@@ -1584,30 +1584,30 @@ MySQL
Has a very similar interface, with differences listed below.
# $ pip3 install mysql-connector
from mysql import connector
-db = connector.connect(host=<str>, user=<str>, password=<str>, database=<str>)
+db = connector.connect(host=<str>, user=<str>, password=<str>, database=<str>)
cursor = db.cursor()
-cursor.execute('<query>') # Connector doesn't have execute method.
-cursor.execute('<query>', <list/tuple>) # Replaces '%s's in query with values.
-cursor.execute('<query>', <dict/namedtuple>) # Replaces '%(<key>)s's with values.
+cursor.execute('<query>') # Connector doesn't have execute method.
+cursor.execute('<query>', <list/tuple>) # Replaces '%s's in query with values.
+cursor.execute('<query>', <dict/namedtuple>) # Replaces '%(<key>)s's with values.
#Bytes
Bytes object is an immutable sequence of single bytes. Mutable version is called 'bytearray'.
-<bytes> = b'<str>' # Only accepts ASCII characters and \x00 - \xff.
-<int> = <bytes>[<index>] # Returns int in range from 0 to 255.
-<bytes> = <bytes>[<slice>] # Returns bytes even if it has only one element.
-<bytes> = <bytes>.join(<coll_of_bytes>) # Joins elements using bytes object as separator.
+<bytes> = b'<str>' # Only accepts ASCII characters and \x00 - \xff.
+<int> = <bytes>[<index>] # Returns int in range from 0 to 255.
+<bytes> = <bytes>[<slice>] # Returns bytes even if it has only one element.
+<bytes> = <bytes>.join(<coll_of_bytes>) # Joins elements using bytes object as separator.
Encode
-<bytes> = <str>.encode('utf-8') # Or: bytes(<str>, 'utf-8')
-<bytes> = bytes(<coll_of_ints>) # Ints must be in range from 0 to 255.
-<bytes> = <int>.to_bytes(<length>, byteorder='big|little', signed=False)
-<bytes> = bytes.fromhex('<hex>')
+<bytes> = <str>.encode('utf-8') # Or: bytes(<str>, 'utf-8')
+<bytes> = bytes(<coll_of_ints>) # Ints must be in range from 0 to 255.
+<bytes> = <int>.to_bytes(<length>, byteorder='big|little', signed=False)
+<bytes> = bytes.fromhex('<hex>')
Decode
-<str> = <bytes>.decode('utf-8') # Or: str(<bytes>, 'utf-8')
-<list> = list(<bytes>) # Returns ints in range from 0 to 255.
-<int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
-'<hex>' = <bytes>.hex()
+<str> = <bytes>.decode('utf-8') # Or: str(<bytes>, 'utf-8')
+<list> = list(<bytes>) # Returns ints in range from 0 to 255.
+<int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
+'<hex>' = <bytes>.hex()
Read Bytes from File
def read_bytes(filename):
@@ -1625,9 +1625,9 @@ #Struct
Machine’s native type sizes and byte order are used by default.
from struct import pack, unpack, iter_unpack, calcsize
-<bytes> = pack('<format>', <num_1> [, <num_2>, ...])
-<tuple> = unpack('<format>', <bytes>)
-<tuples> = iter_unpack('<format>', <bytes>)
+<bytes> = pack('<format>', <num_1> [, <num_2>, ...])
+<tuple> = unpack('<format>', <bytes>)
+<tuples> = iter_unpack('<format>', <bytes>)
Example
>>> pack('>hhl', 1, 2, 3)
@@ -1661,22 +1661,22 @@ Floating point types:
#Array
List that can only hold numbers of predefined type. Available types and their sizes in bytes are listed above.
from array import array
-<array> = array('<typecode>' [, <collection>])
+<array> = array('<typecode>' [, <collection>])
#Memory View
Used for accessing the internal data of an object that supports the buffer protocol.
-<memoryview> = memoryview(<bytes> / <bytearray> / <array>)
-<memoryview>.release()
+<memoryview> = memoryview(<bytes> / <bytearray> / <array>)
+<memoryview>.release()
#Deque
A thread-safe list with efficient appends and pops from either side. Pronounced "deck".
from collections import deque
-<deque> = deque(<collection>, maxlen=None)
+<deque> = deque(<collection>, maxlen=None)
-<deque>.appendleft(<el>)
-<el> = <deque>.popleft()
-<deque>.extendleft(<collection>) # Collection gets reversed.
-<deque>.rotate(n=1) # Rotates elements to the right.
+<deque>.appendleft(<el>)
+<el> = <deque>.popleft()
+<deque>.extendleft(<collection>) # Collection gets reversed.
+<deque>.rotate(n=1) # Rotates elements to the right.
>>> a = deque([1, 2, 3], maxlen=3)
>>> a.append(4)
@@ -1690,7 +1690,7 @@ #Threading
from threading import Thread, RLock
Thread
-thread = Thread(target=<function>, args=(<first_arg>, ))
+thread = Thread(target=<function>, args=(<first_arg>, ))
thread.start()
...
thread.join()
@@ -1709,27 +1709,27 @@ Or:
#Introspection
Inspecting code at runtime.
Variables
-<list> = dir() # Names of variables in current scope.
-<dict> = locals() # Dict of local variables. Also vars().
-<dict> = globals() # Dict of global variables.
+<list> = dir() # Names of variables in current scope.
+<dict> = locals() # Dict of local variables. Also vars().
+<dict> = globals() # Dict of global variables.
Attributes
-<dict> = vars(<object>)
-<bool> = hasattr(<object>, '<attr_name>')
-value = getattr(<object>, '<attr_name>')
-setattr(<object>, '<attr_name>', value)
+<dict> = vars(<object>)
+<bool> = hasattr(<object>, '<attr_name>')
+value = getattr(<object>, '<attr_name>')
+setattr(<object>, '<attr_name>', value)
Parameters
from inspect import signature
-<sig> = signature(<function>)
-no_of_params = len(<sig>.parameters)
-param_names = list(<sig>.parameters.keys())
+<sig> = signature(<function>)
+no_of_params = len(<sig>.parameters)
+param_names = list(<sig>.parameters.keys())
#Metaprograming
Code that generates code.
Type
Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.
-<class> = type(<class_name>, <parents_tuple>, <attributes_dict>)
+<class> = type(<class_name>, <parents_tuple>, <attributes_dict>)
>>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
>>> z = Z()
@@ -1794,11 +1794,11 @@ #Operator
from operator import itemgetter, attrgetter, methodcaller
import operator as op
-sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
-sorted_by_both = sorted(<collection>, key=op.itemgetter(1, 0))
-product_of_elems = functools.reduce(op.mul, <collection>)
+sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
+sorted_by_both = sorted(<collection>, key=op.itemgetter(1, 0))
+product_of_elems = functools.reduce(op.mul, <collection>)
LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_})
-last_el = op.methodcaller('pop')(<list>)
+last_el = op.methodcaller('pop')(<list>)
#Eval
>>> from ast import literal_eval
@@ -1862,8 +1862,8 @@ #Progress Bar
#Plot
# $ pip3 install matplotlib
from matplotlib import pyplot
-pyplot.plot(<data_1> [, <data_2>, ...]) # Or: hist(<data>).
-pyplot.savefig(<filename>)
+pyplot.plot(<data_1> [, <data_2>, ...]) # Or: hist(<data>).
+pyplot.savefig(<filename>)
pyplot.show()
pyplot.clf() # Clears figure.
@@ -1872,7 +1872,7 @@ Prints a CSV file as an ASCII table:
# $ pip3 install tabulate
from tabulate import tabulate
import csv
-with open(<filename>, encoding='utf-8', newline='') as file:
+with open(<filename>, encoding='utf-8', newline='') as file:
lines = csv.reader(file)
headers = [header.title() for header in next(lines)]
table = tabulate(lines, headers)
@@ -1905,7 +1905,7 @@ #Logging
logger.add('debug_{time}.log', colorize=True) # Connects a log file.
logger.add('error_{time}.log', level='ERROR') # Another file for errors or higher.
-logger.<level>('A logging message.')
+logger.<level>('A logging message.')
- Levels:
'debug'
, 'info'
, 'success'
, 'warning'
, 'error'
, 'critical'
.
@@ -1914,27 +1914,27 @@ Exceptions
Error description, stack trace and values of variables are appended automatically.
try:
...
-except <exception>:
+except <exception>:
logger.exception('An error happened.')
Rotation
Argument that sets a condition when a new log file is created.
-rotation=<int>|<datetime.timedelta>|<datetime.time>|<str>
+rotation=<int>|<datetime.timedelta>|<datetime.time>|<str>
-'<int>'
- Max file size in bytes.
-'<timedelta>'
- Max age of a file.
-'<time>'
- Time of day.
-'<str>'
- Any of above as a string: '100 MB'
, '1 month'
, 'monday at 12:00'
, …
+'<int>'
- Max file size in bytes.
+'<timedelta>'
- Max age of a file.
+'<time>'
- Time of day.
+'<str>'
- Any of above as a string: '100 MB'
, '1 month'
, 'monday at 12:00'
, …
Retention
Sets a condition which old log files are deleted.
-retention=<int>|<datetime.timedelta>|<str>
+retention=<int>|<datetime.timedelta>|<str>
-'<int>'
- Max number of files.
-'<timedelta>'
- Max age of a file.
-'<str>'
- Max age as a string: '1 week, 3 days'
, '2 months'
, …
+'<int>'
- Max number of files.
+'<timedelta>'
- Max age of a file.
+'<str>'
- Max age as a string: '1 week, 3 days'
, '2 months'
, …
#Scraping
Scrapes and prints Python's URL and version number from Wikipedia:
@@ -1960,17 +1960,17 @@ Run
run(host='0.0.0.0', port=80, server='cherrypy')
Static Request
-@route('/img/<image>')
+@route('/img/<image>')
def send_image(image):
return static_file(image, 'images/', mimetype='image/png')
Dynamic Request
-@route('/<sport>')
+@route('/<sport>')
def send_page(sport):
- return template('<h1>{{title}}</h1>', title=sport)
+ return template('<h1>{{title}}</h1>', title=sport)
REST Request
-@post('/odds/<sport>')
+@post('/odds/<sport>')
def odds_handler(sport):
team = request.forms.get('team')
home_odds, away_odds = 2.44, 3.29
@@ -2032,24 +2032,24 @@ Generates a PN
filename = f'profile-{time_str}.png'
drawer = output.GraphvizOutput(output_file=filename)
with PyCallGraph(drawer):
- <code_to_be_profiled>
+ <code_to_be_profiled>
#NumPy
Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.
# $ pip3 install numpy
import numpy as np
-<array> = np.array(<list>)
-<array> = np.arange(from_inclusive, to_exclusive, ±step_size)
-<array> = np.ones(<shape>)
-<array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
+<array> = np.array(<list>)
+<array> = np.arange(from_inclusive, to_exclusive, ±step_size)
+<array> = np.ones(<shape>)
+<array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
-<array>.shape = <shape>
-<view> = <array>.reshape(<shape>)
-<view> = np.broadcast_to(<array>, <shape>)
+<array>.shape = <shape>
+<view> = <array>.reshape(<shape>)
+<view> = np.broadcast_to(<array>, <shape>)
-<array> = <array>.sum(axis)
-indexes = <array>.argmin(axis)
+<array> = <array>.sum(axis)
+indexes = <array>.argmin(axis)
- Shape is a tuple of dimension sizes.
@@ -2215,7 +2215,7 @@ if
__name__ == '__main__':
main()
-
+
\n';
-const DIAGRAM_1_A =
+const DIAGRAM_1_A =
'+---------+-------------+\n' +
'| Classes | Metaclasses |\n' +
'+---------+-------------|\n' +
@@ -236,7 +236,7 @@ function modifyPage() {
addToc();
insertLinks();
unindentBanner();
- highlightCode();
+ highlightCode();
}
function removeOrigToc() {
@@ -272,6 +272,14 @@ function highlightCode() {
$('code').not('.python').not('.text').not('.bash').not('.apache').addClass('python');
$('code').each(function(index) {
hljs.highlightBlock(this);
+ if (this.result && this.result.language === "python") {
+ // now wrap e.g. <type> with
+ const plainHTML = $(this).html();
+ const typingRegex = /<[a-z1-9._\/]*>/ig;
+ const replacementString = '$&';
+ const typedHTML = plainHTML.replace(typingRegex, replacementString);
+ $(this).html(typedHTML);
+ }
});
fixClasses()
}
@@ -288,7 +296,7 @@ function fixClasses() {
}
function readFile(filename) {
- try {
+ try {
return fs.readFileSync(filename, 'utf8');
} catch(e) {
console.error('Error:', e.stack);
@@ -296,7 +304,7 @@ function readFile(filename) {
}
function writeToFile(filename, text) {
- try {
+ try {
return fs.writeFileSync(filename, text, 'utf8');
} catch(e) {
console.error('Error:', e.stack);
diff --git a/web/default.min.css b/web/default.min.css
index f2b2eb9c1..89eef3ed6 100644
--- a/web/default.min.css
+++ b/web/default.min.css
@@ -1 +1 @@
-.hljs{overflow-x:auto}.hljs,.hljs-subst{}.hljs-comment{color:#888888}.hljs-keyword,.hljs-attribute,.hljs-selector-tag,.hljs-meta-keyword,.hljs-doctag,.hljs-name{font-weight:bold;color:#3182bd}.hljs-type,.hljs-string,.hljs-number,.hljs-selector-id,.hljs-selector-class,.hljs-quote,.hljs-template-tag,.hljs-deletion{color:#880000}.hljs-title,.hljs-section{color:#880000;font-weight:bold}.hljs-regexp,.hljs-symbol,.hljs-variable,.hljs-template-variable,.hljs-link,.hljs-selector-attr,.hljs-selector-pseudo{color:#BC6060}.hljs-literal{color:#78A960}.hljs-meta{color:#1f7199}.hljs-meta-string{color:#4d99bf}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:bold}
\ No newline at end of file
+.hljs{overflow-x:auto}.hljs,.hljs-subst{}.hljs-comment{color:#888888}.hljs-keyword,.hljs-attribute,.hljs-selector-tag,.hljs-meta-keyword,.hljs-doctag,.hljs-name{font-weight:bold;color:#3182bd}.hljs-type{font-weight:bold}.hljs-string,.hljs-number,.hljs-selector-id,.hljs-selector-class,.hljs-quote,.hljs-template-tag,.hljs-deletion{color:#880000}.hljs-title,.hljs-section{color:#880000;font-weight:bold}.hljs-regexp,.hljs-symbol,.hljs-variable,.hljs-template-variable,.hljs-link,.hljs-selector-attr,.hljs-selector-pseudo{color:#BC6060}.hljs-literal{color:#78A960}.hljs-meta{color:#1f7199}.hljs-meta-string{color:#4d99bf}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:bold}