Contents
1. Collections: List , Dictionary , Set , Tuple , Range , Enumerate , Iterator , Generator .
2. Types: Type , String , Regular_Exp , Format , Numbers , Combinatorics , Datetime .
3. Syntax: Args , Inline , Closure , Decorator , Class , Duck_Types , Enum , Exceptions .
4. System: Print , Input , Command_Line_Arguments , Open , Path , Command_Execution .
5. Data: JSON , Pickle , CSV , SQLite , Bytes , Struct , Array , MemoryView , Deque .
6. Advanced: Threading , Operator , Introspection , Metaprograming , Eval , Coroutine .
7. Libraries: Progress_Bar , Plot , Table , Curses , Logging , Scraping , Web , Profile ,
NumPy , Image , Animation , Audio , Synthesizer .
Main
1 | if __name__ == '__main__': # Runs main() if file wasn't imported. |
List
1 | <list> = <list>[from_inclusive : to_exclusive : ±step_size] |
Dictionary
1 | <view> = <dict>.keys() # Coll. of keys that reflects changes. |
Counter
1 | from collections import Counter |
Set
1 | <set> = set() |
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.
1 | <frozenset> = frozenset(<collection>) |
Tuple
Tuple is an immutable and hashable list.
1 | <tuple> = () |
Named Tuple
Tuple’s subclass with named elements.
1 | from collections import namedtuple |
Range
1 | <range> = range(to_exclusive) |
Enumerate
1 | for i, el in enumerate(<collection> [, i_start]): |
Iterator
1 | <iter> = iter(<collection>) # `iter(<iter>)` returns unmodified iterator. |
Itertools
1 | from itertools import count, repeat, cycle, chain, islice |
Generator
- Any function that contains a yield statement returns a generator.
- Generators and iterators are interchangeable.
1 | def count(start, step): |
Type
- Everything is an object.
- Every object has a type.
- Type and class are synonymous.
1 | <type> = type(<el>) # Or: <el>.__class__ |
Some types do not have built-in names, so they must be imported:
1 | from types import FunctionType, MethodType, LambdaType, GeneratorType |
ABC
An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().
1 | >>> from collections.abc import Sequence, Collection, Iterable |
String
1 | <str> = <str>.strip() # Strips all whitespace characters from both ends. |
- Also: ‘lstrip()’, ‘rstrip()’.
- Also: ‘lower()’, ‘upper()’, ‘capitalize()’ and ‘title()’.
Char
1 | <str> = chr(<int>) # Converts int to unicode char. |
Regex
1 | import re |
- Search() and match() return None if they can’t find a match.
- Argument ‘flags=re.IGNORECASE’ can be used with all functions.
- Argument ‘flags=re.MULTILINE’ makes ‘^’ and ‘$’ match the start/end of each line.
- Argument ‘flags=re.DOTALL’ makes dot also accept newline.
- Use r’\1’ or ‘\1’ for backreference.
- Add ‘?’ after an operator to make it non-greedy.
Match Object
1 | <str> = <Match>.group() # Whole match. Also group(0). |
Special Sequences
- By default digits, whitespaces and alphanumerics from all alphabets are matched, unless ‘flags=re.ASCII’ argument is used.
- Use capital letter for negation.
1 | '\d' == '[0-9]' |
Format
1 | <str> = f'{<el_1>}, {<el_2>}' |
Attributes
1 | > from collections import namedtuple |
General Options
1 | {<el>:<10} |
Strings
‘!r’ calls object’s repr() method, instead of str(), to get a string.
1 | {'abcde'!r:<10} |
Numbers
1 | { 123456:10,} |
Floats
1 | {1.23456:10.3} # ' 1.23' |
Comparison of float presentation types:
1 | +----------------+----------------+---------------+----------------+-----------------+ |
Ints
1 | {90:c} |
Numbers
Types
1 | <int> = int(<float/str/bool>) # Or: math.floor(<float>) |
- ‘int(
)’ and ‘float( )’ raise ValueError on malformed strings. - Decimal numbers can be represented exactly, unlike floats where ‘1.1 + 2.2 != 3.3’.
- Their precision can be adjusted with ‘decimal.getcontext().prec =
‘.
Basic Functions
1 | <num> = pow(<num>, <num>) # Or: <num> ** <num> |
Math
1 | from math import e, pi, inf, nan |
Statistics
1 | from statistics import mean, median, variance, pvariance, pstdev |
Random
1 | from random import random, randint, choice, shuffle |
Bin, Hex
1 | <int> = 0b<bin> # Or: 0x<hex> |
Bitwise Operators
1 | <int> = <int> & <int> |
Combinatorics
- Every function returns an iterator.
- If you want to print the iterator, you need to pass it to the list() function!
1 | from itertools import product, combinations, combinations_with_replacement, permutations |
Datetime
- Module ‘datetime’ provides ‘date’
, ‘time’ , ‘datetime’ - and ‘timedelta’
classes. All are immutable and hashable. - and ‘timedelta’
- Time and datetime can be ‘aware’ , meaning they have defined timezone, or ‘naive’
, meaning they don’t. - If object is naive it is presumed to be in the system’s timezone.
1 | from datetime import date, time, datetime, timedelta |
Constructors
1 | <D> = date(year, month, day) |
- 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
1 | <D/DTn> = D/DT.today() # Current local date or naive datetime. |
- To extract time use ‘
.time()’, ‘ .time()’ or ‘ .timetz()’.
Timezone
1 | <tzinfo> = UTC # UTC timezone. London without DST. |
Encode
1 | <D/T/DT> = D/T/DT.fromisoformat('<iso>') # Object from ISO string. Raises ValueError. |
- ISO strings come in following forms: ‘YYYY-MM-DD’, ‘HH:MM:SS.ffffff[±
]’, or both separated by a space or a ‘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
1 | <str> = <D/T/DT>.isoformat() # ISO string representation. |
Format
1 | >>> from datetime import datetime |
- When parsing, ‘%z’ also accepts ‘±HH:MM’.
- For abbreviated weekday and month use ‘%a’ and ‘%b’.
Arithmetics
1 | <TD> = <D/DT> - <D/DT> |
Arguments
Inside Function Call
1 | <function>(<positional_args>) # f(0, 0) |
Inside Function Definition
1 | def f(<nondefault_args>): # def f(x, y): |
Splat Operator
Inside Function Call
Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.
1 | args = (1, 2) |
Is the same as:
1 | func(1, 2, x=3, y=4, z=5) |
Inside Function Definition
Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.
1 | def add(*a): |
Legal argument combinations:
1 | def f(x, y, z): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) |
Other Uses
1 | <list> = [*<collection> [, ...]] |
Inline
Lambda
1 | <function> = lambda: <return_value> |
Comprehension
1 | <list> = [i+1 for i in range(10)] # [1, 2, ..., 10] |
Is the same as:
1 | out = [] |
Map, Filter, Reduce
1 | from functools import reduce |
Any, All
1 | <bool> = any(<collection>) # False if empty. |
If - Else
1 | <expression_if_true> if <condition> else <expression_if_false> |
Namedtuple, Enum, Dataclass
1 | from collections import namedtuple |
Closure
We have a closure in Python when:
- A nested function references a value of its enclosing function and then
- the enclosing function returns the nested function.
1 | def get_multiplier(a): |
- If multiple nested functions within enclosing function reference the same value, that value gets shared.
- To dynamically access function’s first free variable use ‘
.closure[0].cell_contents’.
Partial
1 | from functools import 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(
)’, ‘iter( , to_exclusive)’ and dataclass’s ‘field(default_factory= )’.
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’.
1 | def get_counter(): |
Decorator
A decorator takes a function, adds some functionality and returns it.
1 | @decorator_name |
Debugger Example
Decorator that prints function’s name every time it gets called.
1 | from functools import wraps |
- Wraps is a helper decorator that copies the metadata of a passed function (func) to the function it is wrapping (out).
- Without it ‘add.name‘ would return ‘out’.
LRU Cache
Decorator that caches function’s return values. All function’s arguments must be hashable.
1 | from functools import lru_cache |
- Recursion depth is limited to 1000 by default. To increase it use ‘sys.setrecursionlimit(
)’.
Parametrized Decorator
A decorator that accepts arguments and returns a normal decorator that accepts a function.
1 | from functools import wraps |
Class
1 | class <name>: |
- Return value of repr() should be unambiguous and of str() readable.
- If only repr() is defined, it will also be used for str().
Str() use cases:
1 | print(<el>) |
Repr() use cases:
1 | print( ) |
Constructor Overloading
1 | class <name>: |
Inheritance
1 | class Person: |
Multiple Inheritance
1 | class A: pass |
MRO determines the order in which parent classes are traversed when searching for a method:
1 | > C.mro() |
Property
1 | class MyClass: |
Dataclass
Decorator that automatically generates init(), repr() and eq() special methods.
1 | from dataclasses import dataclass, field |
- Objects can be made sortable with ‘order=True’ and/or immutable and hashable with ‘frozen=True’.
- Function field() is needed because ‘
: list = []’ would make a list that is shared among all instances. - Default_factory can be any callable.
Inline:
1 | from dataclasses import make_dataclass |
Slots
Mechanism that restricts objects to attributes listed in ‘slots’ and significantly reduces their memory footprint.
1 | class MyClassWithSlots: |
Copy
1 | from copy import copy, deepcopy |
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.
Comparable
- If eq() method is not overridden, it returns ‘id(self) == id(other)’, which is the same as ‘self is other’.
- That means all objects compare not equal by default.
- Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.
1 | class MyComparable: |
Hashable
- Hashable object needs both hash() and eq() methods and its hash value should never change.
- 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 eq().
1 | class MyHashable: |
Sortable
- With total_ordering decorator you only need to provide eq() and one of lt(), gt(), le() or ge() special methods.
1 | from functools import total_ordering |
Iterator
- Any object that defines methods next() and iter() is an iterator.
- Next() should return next item or raise StopIteration.
- Iter() should return ‘self’.
1 | class Counter: |
Python has many different iterator objects:
- Iterators returned by the iter() function, such as list_iterator and set_iterator.
- Objects returned by the itertools module, such as count, repeat and cycle.
- Generators returned by the generator functions and generator expressions.
- All file objects, etc.
Callable
- All functions and classes have a call() method, hence are callable.
- When this cheatsheet uses ‘
‘ for an argument, it actually means ‘ ‘.
1 | class Counter: |
Context Manager
- Enter() should lock the resources and return an object.
- Exit() should release the resources.
1 | class MyOpen(): |
Iterable Duck Types
Iterable
- Only required method is iter(). It should return an iterator of object’s items.
- Contains() automatically works on any object that has iter() defined.
1 | class MyIterable: |
Collection
- Only required methods are iter() and len().
- This cheatsheet actually means ‘
‘ when it uses ‘ ‘. - I chose not to use the name ‘iterable’ because it sounds scarier and more vague than ‘collection’.
1 | class MyCollection: |
Sequence
- Only required methods are len() and getitem().
- Getitem() should return an item at index or raise IndexError.
- Iter() and contains() automatically work on any object that has getitem() defined.
- Reversed() automatically works on any object that has getitem() and len() defined.
1 | class MySequence: |
Collections.abc.Sequence
- It’s a richer interface than the basic sequence.
- Extending it generates iter(), contains(), reversed(), index(), and count().
- Unlike ‘abc.Iterable’ and ‘abc.Collection’, it is not a duck type. That is why ‘issubclass(MySequence, collections.abc.Sequence)’ would return False even if MySequence had all the methods defined.
1 | class MyAbcSequence(collections.abc.Sequence): |
Table of required and available special methods:
1 | +------------+----------+------------+----------+--------------+ |
- Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.
- Names of their required methods are stored in ‘
.abstractmethods‘.
Enum
1 | from enum import Enum, auto |
- If there are no numeric values before auto(), it returns 1.
- Otherwise it returns an increment of last numeric value.
1 | <member> = <enum>.<member_name> # Returns a member. |
Inline
1 | Cutlery = Enum('Cutlery', ['fork', 'knife', 'spoon']) |
Functions can not be values, so they must be wrapped:
1 | from functools import partial |
- Another solution in this particular case, is to use ‘and_’ and ‘or_’ functions from module operator.
Exceptions
Basic Example
1 | try: |
Complex Example
1 | try: |
Catching Exceptions
1 | except <exception>: |
- Also catches subclasses of the exception.
Raising Exceptions
1 | raise <exception> |
Useful built-in exceptions:
1 | raise ValueError('Argument is of right type but inappropriate value!') |
Re-raising caught exception:
1 | except <exception>: |
Common Built-in Exceptions
1 | BaseException |
Collections and their exceptions:
1 | +-----------+------------+----------+----------+ |
User-defined Exceptions
1 | class MyError(Exception): |
1 | print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False) |
- Use ‘file=sys.stderr’ for errors.
- Use ‘flush=True’ to forcibly flush the stream.
Pretty Print
1 | from pprint import pprint |
- Levels deeper than ‘depth’ get replaced by ‘…’.
Input
Reads a line from user input or pipe if present.
1 | <str> = input(prompt=None) |
- Trailing newline gets stripped.
- Prompt string is printed to the standard output before reading input.
- Raises EOFError when user hits EOF or input stream gets exhausted.
Command Line Arguments
1 | import sys |
Argparse
1 | from argparse import ArgumentParser, FileType |
- Use ‘help=
‘ to set argument description. - Use ‘default=
‘ to set the default value. - Use ‘type=FileType(
)’ for files.
Open
Opens the file and returns a corresponding file object.
1 | <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.
- ‘newline=None’ means all different end of line combinations are converted to ‘\n’ on read, while on write all ‘\n’ characters are converted to system’s default line separator.
- ‘newline=””‘ means no conversions take place, but input is still broken into chunks by readline() and readlines() on either ‘\n’, ‘\r’ or ‘\r\n’.
Modes
- ‘r’ - Read (default).
- ‘w’ - Write (truncate).
- ‘x’ - Write or fail if the file already exists.
- ‘a’ - Append.
- ‘w+’ - Read and write (truncate).
- ‘r+’ - Read and write from the start.
- ‘a+’ - Read and write from the end.
- ‘t’ - Text mode (default).
- ‘b’ - Binary mode.
Exceptions
- ‘FileNotFoundError’ can be risen when reading with ‘r’ or ‘r+’.
- ‘FileExistsError’ can be risen when writing with ‘x’.
- ‘IsADirectoryError’ and ‘PermissionError’ can be risen by any.
- ‘OSError’ is the parent class of all listed exceptions.
File
1 | <file>.seek(0) # Moves to the start of the file. |
- Methods do not add or strip trailing newlines, even writelines().
Read Text from File
1 | def read_file( ): |
Write Text to File
1 | def write_to_file(filename, text): |
Path
1 | from os import path, listdir |
Pathlib
1 | from pathlib import Path |
OS Commands
Files and Directories
- Paths can be either strings, Paths, or DirEntry objects.
- Functions report OS related errors by raising either OSError or one of its subclasses.
1 | import os, shutil |
DirEntry:
1 | <bool> = <DirEntry>.is_file() |
Shell Commands
1 | import os |
Using subprocess:
1 | >>> import subprocess, shlex |
JSON
Text file format for storing collections of strings and numbers.
1 | import json |
Read Object from JSON File
1 | def read_json_file(filename): |
Write Object to JSON File
1 | def write_to_json_file(filename, an_object): |
Pickle
Binary file format for storing objects.
1 | import pickle |
Read Object from File
1 | def read_pickle_file(filename): |
Write Object to File
1 | def write_to_pickle_file( , an_object): |
CSV
Text file format for storing spreadsheets.
1 | import csv |
Read
1 | <reader> = csv.reader(<file>, dialect='excel', delimiter=',') |
- File must be opened with ‘newline=””‘ argument, or newlines embedded inside quoted fields will not be interpreted correctly!
Write
1 | <writer> = csv.writer(<file>, dialect='excel', delimiter=',') |
- File must be opened with ‘newline=””‘ argument, or an extra ‘\r’ will be added on platforms that use ‘\r\n’ linendings!
Parameters
- ‘dialect’ - Master parameter that sets the default values.
- ‘delimiter’ - A one-character string used to separate fields.
- ‘quotechar’ - Character for quoting fields that contain special characters.
- ‘doublequote’ - Whether quotechars inside fields get doubled or escaped.
- ‘skipinitialspace’ - Whether whitespace after delimiter gets stripped.
- ‘lineterminator’ - How does writer terminate lines.
- ‘quoting’ - Controls the amount of quoting: 0 - as necessary, 1 - all.
- ‘escapechar’ - Character for escaping ‘quotechar’ if ‘doublequote’ is false.
Dialects
1 | +------------------+-----------+-----------+--------------+ |
Read Rows from CSV File
1 | def read_csv_file(filename): |
Write Rows to CSV File
1 | def write_to_csv_file(filename, rows): |
SQLite
Server-less database engine that stores each database into separate file.
Connect
Opens a connection to the database file. Creates a new file if path doesn’t exist.
1 | import sqlite3 |
Read
Returned values can be of type str, int, float, bytes or None.
1 | <cursor> = db.execute('<query>') # Can raise sqlite3.OperationalError. |
Write
1 | db.execute('<query>') |
Or:
1 | with db: |
Placeholders
- Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.
- Bools will be stored and returned as ints and dates as ISO formatted strings.
1 | db.execute('<query>', <list/tuple>) # Replaces '?'s in query with values. |
Example
In this example values are not actually saved because ‘db.commit()’ is omitted!
1 | 'test.db') > db = sqlite3.connect( |
MySQL
Has a very similar interface, with differences listed below.
1 | # $ pip3 install mysql-connector |
Bytes
Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.
1 | <bytes> = b'<str>' # Only accepts ASCII characters and \x00 - \xff. |
Encode
1 | <bytes> = bytes(<coll_of_ints>) # Ints must be in range from 0 to 255. |
Decode
1 | <list> = list(<bytes>) # Returns ints in range from 0 to 255. |
Read Bytes from File
1 | def read_bytes(filename): |
Write Bytes to File
1 | def write_bytes(filename, bytes_obj): |
Struct
- Module that performs conversions between a sequence of numbers and a bytes object.
- Machine’s native type sizes and byte order are used by default.
1 | from struct import pack, unpack, iter_unpack |
Example
1 | >>> pack('>hhl', 1, 2, 3) |
Format
For standard sizes start format string with:
- ‘=’ - native byte order
- ‘<’ - little-endian
- ‘>’ - big-endian
Integer types. Use capital letter for unsigned type. Standard sizes are in brackets:
- ‘x’ - pad byte
- ‘b’ - char (1)
- ‘h’ - short (2)
- ‘i’ - int (4)
- ‘l’ - long (4)
- ‘q’ - long long (8)
Floating point types:
- ‘f’ - float (4)
- ‘d’ - double (8)
Array
List that can only hold numbers of a predefined type. Available types and their sizes in bytes are listed above.
1 | from array import array |
Memory View
- A sequence object that points to the memory of another object.
- Each element can reference a single or multiple consecutive bytes, depending on format.
- Order and number of elements can be changed with slicing.
1 | <mview> = memoryview(<bytes/bytearray/array>) |
Deque
A thread-safe list with efficient appends and pops from either side. Pronounced “deck”.
1 | from collections import deque |
Threading
- CPython interpreter can only run a single thread at a time.
- That is why using multiple threads won’t result in a faster execution, unless there is an I/O operation in the thread.
1 | from threading import Thread, RLock |
Thread
1 | thread = Thread(target=<function>, args=(<first_arg>, )) |
- Use ‘kwargs=
‘ to pass keyword arguments to the function. - Use ‘daemon=True’, or the program will not be able to exit while the thread is alive.
Lock
1 | lock = RLock() |
Or:
1 | lock = RLock() |
Thread Pool Executor
1 | from concurrent.futures import ThreadPoolExecutor |
Queue
A thread-safe FIFO queue. For LIFO queue use LifoQueue.
1 | from queue import Queue |
Operator
Module of functions that provide the functionality of operators.
1 | from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs |
Introspection
Inspecting code at runtime.
Variables
1 | <list> = dir() # Names of variables in current scope. |
Attributes
1 | <dict> = vars(<object>) |
Parameters
1 | from inspect import signature |
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.
1 | <class> = type(<class_name>, <parents_tuple>, <attributes_dict>) |
Meta Class
Class that creates classes.
1 | def my_meta_class(name, parents, attrs): |
Or:
1 | class MyMetaClass(type): |
- New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a ‘self’ argument.
- It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance (MyMetaClass in our case).
- New() can also be called directly, usually from a new() method of a child class (
def __new__(cls): return super().__new__(cls)
), in which case init() is not called.
Metaclass Attribute
Right before a class is created it checks if it has a ‘metaclass’ attribute defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type().
1 | class MyClass(metaclass=MyMetaClass): |
Type Diagram
1 | type(MyClass) == MyMetaClass # MyClass is an instance of MyMetaClass. |
Inheritance Diagram
1 | MyClass.__base__ == object # MyClass is a subclass of object. |
Eval
1 | > from ast import literal_eval |
Coroutine
- Any function that contains a ‘(yield)’ expression returns a coroutine.
- Coroutines are similar to iterators, but data needs to be pulled out of an iterator by calling ‘next(
)’, while we push data into the coroutine by calling ‘ .send( )’. - Coroutines provide more powerful data routing possibilities than iterators.
Helper Decorator
- All coroutines must first be “primed” by calling ‘next(
)’. - Remembering to call next() is easy to forget.
- Solved by wrapping coroutine functions with the following decorator:
1 | def coroutine(func): |
Pipeline Example
1 | def reader(target): |
Libraries
Progress Bar
1 | # $ pip3 install tqdm |
Plot
1 | # $ pip3 install matplotlib |
Table
Prints a CSV file as an ASCII table:
1 | # $ pip3 install tabulate |
Curses
Clears the terminal, prints a message and waits for an ESC key press:
1 | from curses import wrapper, curs_set, ascii |
Logging
1 | # $ pip3 install loguru |
- Levels: ‘debug’, ‘info’, ‘success’, ‘warning’, ‘error’, ‘critical’.
Exceptions
Exception description, stack trace and values of variables are appended automatically.
1 | try: |
Rotation
Argument that sets a condition when a new log file is created.
1 | rotation=<int>|<datetime.timedelta>|<datetime.time>|<str> |
- ‘
‘ - Max file size in bytes. - ‘
‘ - Max age of a file. - ‘
- ‘
‘ - Any of above as a string: ‘100 MB’, ‘1 month’, ‘monday at 12:00’, …
Retention
Sets a condition which old log files get deleted.
1 | retention=<int>|<datetime.timedelta>|<str> |
- ‘
‘ - Max number of files. - ‘
‘ - Max age of a file. - ‘
‘ - Max age as a string: ‘1 week, 3 days’, ‘2 months’, …
Scraping
Scrapes Python’s URL, version number and logo from Wikipedia page:
1 | # $ pip3 install requests beautifulsoup4 |
Web
1 |
|
Run
1 | run(host='localhost', port=8080) |
Static Request
1 | @route('/img/<image>') |
Dynamic Request
1 | @route('/<sport>') |
REST Request
1 | @post('/odds/<sport>') |
Test:
1 | # $ pip3 install requests |
Profiling
Stopwatch
1 | from time import time |
High performance:
1 | from time import perf_counter |
Timing a Snippet
1 | >>> from timeit import timeit |
Profiling by Line
1 | # $ pip3 install line_profiler memory_profiler |
Call Graph
Generates a PNG image of a call graph with highlighted bottlenecks:
1 | # $ pip3 install pycallgraph |
NumPy
Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.
1 | # $ pip3 install numpy |
- Shape is a tuple of dimension sizes.
- Axis is an index of dimension that gets collapsed. Leftmost dimension has index 0.
Indexing
1 | <el> = <2d_array>[0, 0] # First element. |
- If row and column indexes differ in shape, they are combined with broadcasting.
Broadcasting
Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.
1 | left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) |
1. If array shapes differ in length, left-pad the shorter shape with ones:
1 | left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) |
2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
1 | left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- ! |
3. If neither non-matching dimension has size 1, rise an error.
Example
For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]
):
1 | >>> points = np.array([0.1, 0.6, 0.8]) |
Image
1 | # $ pip3 install pillow |
Modes
- ‘1’ - 1-bit pixels, black and white, stored with one pixel per byte.
- ‘L’ - 8-bit pixels, greyscale.
- ‘RGB’ - 3x8-bit pixels, true color.
- ‘RGBA’ - 4x8-bit pixels, true color with transparency mask.
- ‘HSV’ - 3x8-bit pixels, Hue, Saturation, Value color space.
Examples
Creates a PNG image of a rainbow gradient:
1 | WIDTH, HEIGHT = 100, 100 |
Adds noise to a PNG image:
1 | from random import randint |
ImageDraw
1 | from PIL import ImageDraw |
- Use ‘fill=
‘ to set the primary color. - Use ‘outline=
‘ to set the secondary color. - Color can be specified as a tuple, int, ‘#rrggbb’ string or a color name.
Animation
Creates a GIF of a bouncing ball:
1 | # $ pip3 install pillow imageio |
Audio
1 | import wave |
- Bytes object contains a sequence of frames, each consisting of one or more samples.
- In stereo signal first sample of a frame belongs to the left channel.
- Each sample consists of one or more bytes that, when converted to an integer, indicate the displacement of a speaker membrane at a given moment.
- If sample width is one, then the integer should be encoded unsigned.
- For all other sizes the integer should be encoded signed with little-endian byte order.
Sample Values
1 | +-----------+-------------+------+-------------+ |
Read Float Samples from WAV File
1 | def read_wav_file(filename): |
Write Float Samples to WAV File
1 | def write_to_wav_file(filename, float_samples, nchannels=1, sampwidth=2, framerate=44100): |
Examples
Saves a sine wave to a mono WAV file:
1 | from math import pi, sin |
Adds noise to a mono WAV file:
1 | from random import random |
Synthesizer
Plays Popcorn by Gershon Kingsley:
1 | # $ pip3 install simpleaudio |
Basic Script Template
1 | #!/usr/bin/env python3 |