Comprehensive Python Cheatsheet
Comprehensive Python Cheatsheet
# Contents
ToC = {
'1. Collections': [List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator],
'3. Syntax': [Args, Inline, Closure, Decorator, Class, Duck_Type, Enum, Exception],
'5. Data': [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],
'7. Libraries': [Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile,
# Main
main()
# List
<list>.sort()
<list>.reverse()
<list> = sorted(<collection>)
<iter> = reversed(<list>)
https://gto76.github.io/python-cheatsheet/ 1/60
7/10/2021 Comprehensive Python Cheatsheet
sum_of_elements = sum(<collection>)
flatter_list = list(itertools.chain.from_iterable(<list>))
list_of_chars = list(<str>)
Module operator provides functions itemgetter() and mul() that offer the same
functionality as lambda expressions above.
<list>.insert(<int>, <el>) # Inserts item at index and moves the rest to the right.
<el> = <list>.pop([<int>]) # Returns and removes item at index or from the end.
# Dictionary
{k for k, v in <dict>.items() if v == value} # Returns set of keys that point to the value.
Counter
>>> counter['yellow'] += 1
>>> counter.most_common()[0]
('blue', 3)
# Set
<set> = set()
https://gto76.github.io/python-cheatsheet/ 2/60
7/10/2021 Comprehensive Python Cheatsheet
<set> = <set>.union(<coll.>) # Or: <set> | <set>
Frozen Set
<frozenset> = frozenset(<collection>)
# Tuple
Tuple is an immutable and hashable list.
<tuple> = ()
Named Tuple
Point(x=1, y=2)
>>> p[0]
>>> p.x
('x', 'y')
# Range
<range> = range(to_exclusive)
from_inclusive = <range>.start
to_exclusive = <range>.stop
https://gto76.github.io/python-cheatsheet/ 3/60
7/10/2021 Comprehensive Python Cheatsheet
# Enumerate
...
# Iterator
Itertools
# Generator
Any function that contains a yield statement returns a generator.
Generators and iterators are interchangeable.
while True:
yield start
start += step
# Type
Everything is an object.
Every object has a type.
Type and class are synonymous.
https://gto76.github.io/python-cheatsheet/ 4/60
7/10/2021 Comprehensive Python Cheatsheet
Some types do not have built-in names, so they must be imported:
Each abstract base class specifies a set of virtual subclasses. These classes are then recognized
by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC
can also manually decide whether or not a specific class is its virtual subclass, usually based
on which methods the class has implemented. For instance, Iterable ABC looks for method
iter() while Collection ABC looks for methods iter(), contains() and len().
True
┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
┠──────────────────┼────────────┼────────────┼────────────┨
┃ dict, set │ │ ✓ │ ✓ ┃
┃ iter │ │ │ ✓ ┃
┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
True
┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ fractions.Fraction │ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ float │ │ │ ✓ │ ✓ │ ✓ ┃
┃ complex │ │ │ │ ✓ │ ✓ ┃
┃ decimal.Decimal │ │ │ │ │ ✓ ┃
┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
# String
<str> = <str>.replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times.
https://gto76.github.io/python-cheatsheet/ 5/60
7/10/2021 Comprehensive Python Cheatsheet
<str> = chr(<int>) # Converts int to Unicode char.
Property Methods
┏━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
┠───────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
┃ isprintable() │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ isalnum() │ │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ isnumeric() │ │ │ ✓ │ ✓ │ ✓ ┃
┃ isdigit() │ │ │ │ ✓ │ ✓ ┃
┃ isdecimal() │ │ │ │ │ ✓ ┃
┗━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
# Regex
import re
<str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences with 'new'.
<list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to include the matches.
Match Object
Special Sequences
By default, decimal characters, alphanumerics and whitespaces from all alphabets are
matched unless 'flags=re.ASCII' argument is used.
As shown below, it restricts special sequence matches to the first 128 characters and
prevents '\s' from accepting '[\x1c-\x1f]'.
Use a capital letter for negation.
https://gto76.github.io/python-cheatsheet/ 6/60
7/10/2021 Comprehensive Python Cheatsheet
# Format
Attributes
>>> f'{person.height}'
'187'
>>> '{p.height}'.format(p=person)
'187'
General Options
{<el>:.<10} # '<el>......'
{<el>:0} # '<el>'
Strings
{'abcde':.3} # 'abc'
Numbers
{-123456: } # '-123456'
Floats
https://gto76.github.io/python-cheatsheet/ 7/60
7/10/2021 Comprehensive Python Cheatsheet
Comparison of presentation types:
┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨
┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨
┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
When both rounding up and rounding down are possible, the one that returns result with
even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
Ints
{90:c} # 'Z'
{90:b} # '1011010'
{90:X} # '5A'
# Numbers
Types
Basic Functions
https://gto76.github.io/python-cheatsheet/ 8/60
7/10/2021 Comprehensive Python Cheatsheet
Math
from math import sin, cos, tan, asin, acos, atan, degrees, radians
Statistics
Random
Bin, Hex
Bitwise Operators
# Combinatorics
Every function returns an iterator.
If you want to print the iterator, you need to pass it to the list() function first!
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), ..., (1, 1, 1)]
>>> combinations('abc', 2) # a b c
('b', 'c')] # b . . x
https://gto76.github.io/python-cheatsheet/ 9/60
7/10/2021 Comprehensive Python Cheatsheet
>>> combinations_with_replacement('abc', 2) # a b c
('c', 'c')] # c . . x
>>> permutations('abc', 2) # a b c
# Datetime
Module 'datetime' provides 'date' <D>, 'time' <T>, 'datetime' <DT> and 'timedelta' <TD>
classes. All are immutable and hashable.
Time and datetime objects can be 'aware' <a>, meaning they have defined timezone, or
'naive' <n>, meaning they don't.
If object is naive, it is presumed to be in the system's timezone.
Constructors
Now
Timezone
Encode
<DTn> = DT.fromtimestamp(<real>) # Local time DTn from seconds since the Epoch.
<DTa> = DT.fromtimestamp(<real>, <tz.>) # Aware datetime from seconds since the Epoch.
https://gto76.github.io/python-cheatsheet/ 10/60
7/10/2021 Comprehensive Python Cheatsheet
ISO strings come in following forms: 'YYYY-MM-DD', 'HH:MM:SS.ffffff[±<offset>]',
or both separated by an arbitrary character. Offset is formatted as: 'HH:MM'.
Epoch on Unix systems is: '1970-01-01 00:00 UTC', '1970-01-01 01:00 CET', …
Decode
<int> = <D/DT>.toordinal() # Days since Gregorian NYE 1, ignoring time and tz.
<float> = <DTn>.timestamp() # Seconds since the Epoch, from DTn in local tz.
Format
Arithmetics
<D/DT> = <D/DT> ± <TD> # Returned datetime can fall into missing hour.
<TD> = <DTa> - <DTa> # Ignores time jumps if they share tzinfo object.
<TD> = <DT_UTC> - <DT_UTC> # Convert DTs to UTC to get the actual delta.
# Arguments
Inside Function Call
<function>(<positional_args>) # f(0, 0)
# Splat Operator
Inside Function Call
Splat expands a collection into positional arguments, while splatty-splat expands a dictionary
into keyword arguments.
args = (1, 2)
func(*args, **kwargs)
https://gto76.github.io/python-cheatsheet/ 11/60
7/10/2021 Comprehensive Python Cheatsheet
Is the same as:
Splat combines zero or more positional arguments into a tuple, while splatty-splat combines
zero or more keyword arguments into a dictionary.
def add(*a):
return sum(a)
>>> add(1, 2, 3)
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)
def f(x, y, *, z): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
def f(*args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
def f(x, *args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
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
# Inline
Lambda
https://gto76.github.io/python-cheatsheet/ 12/60
7/10/2021 Comprehensive Python Cheatsheet
Comprehensions
Any, All
Conditional Expression
['zero', 1, 2, 3]
point = Point(0, 0)
direction = Direction.n
# Closure
We have a closure in Python when:
def get_multiplier(a):
def out(b):
return a * b
return out
https://gto76.github.io/python-cheatsheet/ 13/60
7/10/2021 Comprehensive Python Cheatsheet
>>> multiply_by_3 = get_multiplier(3)
>>> multiply_by_3(10)
30
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'.
Partial
>>> multiply_by_3(10)
30
Partial is also useful in cases when 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>)'.
Non-Local
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'.
def get_counter():
i = 0
def out():
nonlocal i
i += 1
return i
return out
(1, 2, 3)
https://gto76.github.io/python-cheatsheet/ 14/60
7/10/2021 Comprehensive Python Cheatsheet
# Decorator
A decorator takes a function, adds some functionality and returns it.
@decorator_name
def function_that_gets_passed_to_decorator():
...
Debugger Example
def debug(func):
@wraps(func)
print(func.__name__)
return out
@debug
return x + y
Wraps is a helper decorator that copies the metadata of the 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.
@lru_cache(maxsize=None)
def fib(n):
Parametrized Decorator
A decorator that accepts arguments and returns a normal decorator that accepts a function.
def debug(print_result=False):
def decorator(func):
@wraps(func)
return result
return out
return decorator
@debug(print_result=True)
return x + y
https://gto76.github.io/python-cheatsheet/ 15/60
7/10/2021 Comprehensive Python Cheatsheet
# Class
class <name>:
self.a = a
def __repr__(self):
class_name = self.__class__.__name__
return f'{class_name}({self.a!r})'
def __str__(self):
return str(self.a)
@classmethod
def get_class_name(cls):
return cls.__name__
print(<el>)
print(f'{<el>}')
raise Exception(<el>)
loguru.logger.debug(<el>)
csv.writer(<file>).writerow([<el>])
print([<el>])
print(f'{<el>!r}')
>>> <el>
loguru.logger.exception()
Constructor Overloading
class <name>:
self.a = a
Inheritance
class Person:
self.name = name
self.age = age
class Employee(Person):
super().__init__(name, age)
self.staff_num = staff_num
Multiple Inheritance
class A: pass
class B: pass
https://gto76.github.io/python-cheatsheet/ 16/60
7/10/2021 Comprehensive Python Cheatsheet
MRO determines the order in which parent classes are traversed when searching for a
method:
>>> C.mro()
Property
class MyClass:
@property
def a(self):
return self._a
@a.setter
self._a = value
>>> el = MyClass()
>>> el.a
123
Dataclass
Decorator that automatically generates init(), repr() and eq() special methods.
@dataclass(order=False, frozen=False)
class <class_name>:
<attr_name_1>: <type>
Objects can be made sortable with 'order=True' and immutable with 'frozen=True'.
For object to be hashable, all attributes must be hashable and frozen must be True.
Function field() is needed because '<attr_name>: list = []' would make a list that is
shared among all instances.
Default_factory can be any callable.
Inline:
Slots
Mechanism that restricts objects to attributes listed in 'slots' and significantly reduces their
memory footprint.
class MyClassWithSlots:
__slots__ = ['a']
def __init__(self):
self.a = 1
https://gto76.github.io/python-cheatsheet/ 17/60
7/10/2021 Comprehensive Python Cheatsheet
Copy
<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.
Comparable
class MyComparable:
def __init__(self, a):
self.a = a
if isinstance(other, type(self)):
return NotImplemented
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().
class MyHashable:
self._a = a
@property
def a(self):
return self._a
if isinstance(other, type(self)):
return NotImplemented
def __hash__(self):
return hash(self.a)
https://gto76.github.io/python-cheatsheet/ 18/60
7/10/2021 Comprehensive Python Cheatsheet
Sortable
With total_ordering decorator, you only need to provide eq() and one of lt(), gt(), le() or
ge() special methods.
@total_ordering
class MySortable:
self.a = a
if isinstance(other, type(self)):
return NotImplemented
if isinstance(other, type(self)):
return NotImplemented
Iterator
class Counter:
def __init__(self):
self.i = 0
def __next__(self):
self.i += 1
return self.i
def __iter__(self):
return self
(1, 2, 3)
Sequence 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.
File objects returned by the open() function, etc.
Callable
All functions and classes have a call() method, hence are callable.
When this cheatsheet uses '<function>' as an argument, it actually means
'<callable>'.
class Counter:
def __init__(self):
self.i = 0
def __call__(self):
self.i += 1
return self.i
https://gto76.github.io/python-cheatsheet/ 19/60
7/10/2021 Comprehensive Python Cheatsheet
>>> counter = Counter()
(1, 2, 3)
Context Manager
class MyOpen:
self.filename = filename
def __enter__(self):
self.file = open(self.filename)
return self.file
self.file.close()
... print(file.read())
Hello World!
class MyIterable:
self.a = a
def __iter__(self):
return iter(self.a)
return el in self.a
[1, 2, 3]
>>> 1 in obj
True
https://gto76.github.io/python-cheatsheet/ 20/60
7/10/2021 Comprehensive Python Cheatsheet
Collection
class MyCollection:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
return el in self.a
def __len__(self):
return len(self.a)
Sequence
class MySequence:
self.a = a
def __iter__(self):
return iter(self.a)
return el in self.a
def __len__(self):
return len(self.a)
return self.a[i]
def __reversed__(self):
return reversed(self.a)
ABC Sequence
class MyAbcSequence(abc.Sequence):
self.a = a
def __len__(self):
return len(self.a)
return self.a[i]
https://gto76.github.io/python-cheatsheet/ 21/60
7/10/2021 Comprehensive Python Cheatsheet
Table of required and automatically available special methods:
┏━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
┠────────────┼────────────┼────────────┼────────────┼──────────────┨
┃ iter() │ ! │ ! │ ✓ │ ✓ ┃
┃ contains() │ ✓ │ ✓ │ ✓ │ ✓ ┃
┃ len() │ │ ! │ ! │ ! ┃
┃ getitem() │ │ │ ! │ ! ┃
┃ reversed() │ │ │ ✓ │ ✓ ┃
┃ index() │ │ │ │ ✓ ┃
┃ count() │ │ │ │ ✓ ┃
┗━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet,
Mapping and MutableMapping.
Names of their required methods are stored in '<abc>.__abstractmethods__'.
# Enum
class <enum_name>(Enum):
<member_name_1> = <value_1>
<member_name_3> = auto()
list_of_members = list(<enum>)
random_member = random.choice(list(<enum>))
def get_next_member(member):
members = list(member.__class__)
return members[index]
Inline
https://gto76.github.io/python-cheatsheet/ 22/60
7/10/2021 Comprehensive Python Cheatsheet
Another solution in this particular case is to use functions and_() and or_() from the
module operator.
# Exceptions
Basic Example
try:
<code>
except <exception>:
<code>
Complex Example
try:
<code_1>
except <exception_a>:
<code_2_a>
except <exception_b>:
<code_2_b>
else:
<code_2_c>
finally:
<code_3>
Code inside the 'else' block will only be executed if 'try' block had no exceptions.
Code inside the 'finally' block will always be executed.
Catching Exceptions
except <exception>:
Raising Exceptions
raise <exception>
raise <exception>()
...
raise
https://gto76.github.io/python-cheatsheet/ 23/60
7/10/2021 Comprehensive Python Cheatsheet
Exception Object
arguments = <name>.args
exc_type = <name>.__class__
filename = <name>.__traceback__.tb_frame.f_code.co_filename
func_name = <name>.__traceback__.tb_frame.f_code.co_name
Built-in Exceptions
BaseException
├── KeyboardInterrupt # Raised when the user hits the interrupt key (ctrl-c).
│ └── KeyError # Raised when a dictionary key or set element is not found.
├── OSError # Errors such as “file not found” or “disk full” (see Open).
┏━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
┠───────────┼────────────┼────────────┼────────────┨
┃ index() │ ValueError │ │ ┃
┗━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
User-defined Exceptions
class MyError(Exception):
pass
class MyInputError(MyError):
pass
https://gto76.github.io/python-cheatsheet/ 24/60
7/10/2021 Comprehensive Python Cheatsheet
# Exit
Exits the interpreter by raising SystemExit exception.
import sys
Pretty Print
# Input
Reads a line from user input or pipe if present.
<str> = input(prompt=None)
import sys
scripts_path = sys.argv[0]
arguments = sys.argv[1:]
Argument Parser
p = ArgumentParser(description=<str>)
value = args.<name>
# Open
Opens the file and returns a corresponding file object.
'encoding=None' means that the 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
Exceptions
File Object
https://gto76.github.io/python-cheatsheet/ 26/60
7/10/2021 Comprehensive Python Cheatsheet
def read_file(filename):
return file.readlines()
file.write(text)
# Paths
DirEntry
Using scandir() instead of listdir() can significantly increase the performance of code that also
needs file type information.
Path Object
<Path> = <path> / <path> [/ ...] # One of the paths must be a Path object.
https://gto76.github.io/python-cheatsheet/ 27/60
7/10/2021 Comprehensive Python Cheatsheet
<Path> = <Path>.parent # Returns Path without final component.
# OS Commands
Files and Directories
Shell Commands
import os
<str> = os.popen('<shell_command>').read()
Sends '1 + 1' to the basic calculator and captures its output:
Sends test.in to the basic calculator running in standard mode and saves its output to test.out:
>>> open('test.out').read()
'2\n'
https://gto76.github.io/python-cheatsheet/ 28/60
7/10/2021 Comprehensive Python Cheatsheet
# JSON
Text file format for storing collections of strings and numbers.
import json
<object> = json.loads(<str>)
def read_json_file(filename):
return json.load(file)
# Pickle
Binary file format for storing objects.
import pickle
<bytes> = pickle.dumps(<object>)
<object> = pickle.loads(<bytes>)
def read_pickle_file(filename):
return pickle.load(file)
pickle.dump(an_object, file)
# CSV
Text file format for storing spreadsheets.
import csv
Read
https://gto76.github.io/python-cheatsheet/ 29/60
7/10/2021 Comprehensive Python Cheatsheet
File must be opened with a 'newline=""' argument, or newlines embedded inside
quoted fields will not be interpreted correctly!
Write
File must be opened with a 'newline=""' argument, or '\r' will be added in front of every
'\n' on platforms that use '\r\n' line endings!
Parameters
Dialects
┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
┠──────────────────┼──────────────┼──────────────┼──────────────┨
┃ quoting │ 0 │ 0 │ 1 ┃
┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
def read_csv_file(filename):
return list(csv.reader(file))
writer = csv.writer(file)
writer.writerows(rows)
https://gto76.github.io/python-cheatsheet/ 30/60
7/10/2021 Comprehensive Python Cheatsheet
# SQLite
Server-less database engine that stores each database into a separate file.
Connect
Opens a connection to the database file. Creates a new file if path doesn't exist.
import sqlite3
Read
Write
Or:
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.
Example
In this example values are not actually saved because 'conn.commit()' is omitted!
>>> conn.execute('CREATE TABLE person (person_id INTEGER PRIMARY KEY, name, height)')
https://gto76.github.io/python-cheatsheet/ 31/60
7/10/2021 Comprehensive Python Cheatsheet
MySQL
# Bytes
Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.
Encode
Decode
def read_bytes(filename):
return file.read()
file.write(bytes_obj)
# Struct
Module that performs conversions between a sequence of numbers and a bytes object.
System’s type sizes and byte order are used by default.
https://gto76.github.io/python-cheatsheet/ 32/60
7/10/2021 Comprehensive Python Cheatsheet
<bytes> = pack('<format>', <num_1> [, <num_2>, ...])
Example
>>> pack('>hhl', 1, 2, 3)
b'\x00\x01\x00\x02\x00\x00\x00\x03'
(1, 2, 3)
Format
Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:
# Array
List that can only hold numbers of a predefined type. Available types and their minimum
sizes in bytes are listed above. Sizes and byte order are always determined by the system.
https://gto76.github.io/python-cheatsheet/ 33/60
7/10/2021 Comprehensive Python Cheatsheet
# 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.
Casting only works between char and other types and uses system's sizes and byte order.
Decode
# Deque
A thread-safe list with efficient appends and pops from either side. Pronounced "deck".
# 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 at least one
of the threads contains an I/O operation.
Thread
https://gto76.github.io/python-cheatsheet/ 34/60
7/10/2021 Comprehensive Python Cheatsheet
Use 'daemon=True', or the program will not be able to exit while the thread is alive.
Lock
Or:
<Futr> = <Exec>.submit(<func>, <arg_1>, ...) # Starts a thread and returns its Future object.
Queue
<Queue> = Queue(maxsize=0)
# Operator
Module of functions that provide the functionality of operators.
from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs
https://gto76.github.io/python-cheatsheet/ 35/60
7/10/2021 Comprehensive Python Cheatsheet
import operator as op
last_el = op.methodcaller('pop')(<list>)
# Introspection
Inspecting code at runtime.
Variables
Attributes
Parameters
# Metaprogramming
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.
>>> z = Z()
https://gto76.github.io/python-cheatsheet/ 36/60
7/10/2021 Comprehensive Python Cheatsheet
Meta Class
attrs['a'] = 'abcde'
Or:
class MyMetaClass(type):
attrs['a'] = 'abcde'
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
type of the returned instance (MyMetaClass in our case).
Like 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)).
The only difference between the examples above is that my_meta_class() returns a class of
type type, while MyMetaClass() returns a class of type MyMetaClass.
Metaclass Attribute
Right before a class is created it checks if it has the 'metaclass' attribute defined. If not, it
recursively checks if any of his parents has it defined and eventually comes to type().
class MyClass(metaclass=MyMetaClass):
b = 12345
('abcde', 12345)
Type Diagram
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┓
┃ Classes │ Metaclasses ┃
┠─────────────┼─────────────┨
┃ │ ↓ ┃
┃ │ ↑ ╰──╯ ┃
┃ str ──────────╯ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┛
Inheritance Diagram
https://gto76.github.io/python-cheatsheet/ 37/60
7/10/2021 Comprehensive Python Cheatsheet
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┓
┃ Classes │ Metaclasses ┃
┠─────────────┼─────────────┨
┃ MyClass │ MyMetaClass ┃
┃ ↓ │ ↓ ┃
┃ ↑ │ ┃
┃ str │ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┛
# Eval
[1, 2, 3]
https://gto76.github.io/python-cheatsheet/ 38/60
7/10/2021 Comprehensive Python Cheatsheet
# Coroutines
Coroutines have a lot in common with threads, but unlike threads, they only give up
control when they call another coroutine and they don’t use as much memory.
Coroutine definition starts with 'async' and its call with 'await'.
'asyncio.run(<coroutine>)' is the main entry point for asynchronous programs.
Functions wait(), gather() and as_completed() can be used when multiple coroutines need
to be started at the same time.
Asyncio module also provides its own Queue, Event, Lock and Semaphore classes.
Runs a terminal game where you control an asterisk that must avoid numbers:
def main(screen):
state = {'*': P(0, 0), **{id_: P(30, 10) for id_ in range(10)}}
moves = asyncio.Queue()
human_controller(screen, moves),
view(state, screen))
while True:
d = random.choice(list(D))
moves.put_nowait((id_, d))
await asyncio.sleep(random.random() / 2)
while True:
ch = screen.getch()
if ch in key_mappings:
moves.put_nowait(('*', key_mappings[ch]))
await asyncio.sleep(0.01)
p = state[id_]
deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)}
state[id_] = new_p
while True:
screen.clear()
await asyncio.sleep(0.01)
if __name__ == '__main__':
curses.wrapper(main)
https://gto76.github.io/python-cheatsheet/ 39/60
7/10/2021 Comprehensive Python Cheatsheet
Libraries
# Progress Bar
... sleep(1)
# Plot
# Table
Prints a CSV file as an ASCII table:
rows = csv.reader(file)
print(table)
https://gto76.github.io/python-cheatsheet/ 40/60
7/10/2021 Comprehensive Python Cheatsheet
# Curses
Runs a basic file explorer in the terminal:
from curses import wrapper, ascii, A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER
def main(screen):
while ch != ascii.ESC:
height, _ = screen.getmaxyx()
screen.clear()
ch = screen.getch()
if path.isdir(new_dir):
chdir(new_dir)
if __name__ == '__main__':
wrapper(main)
# Logging
Exceptions
Exception description, stack trace and values of variables are appended automatically.
try:
...
except <exception>:
Rotation
rotation=<int>|<datetime.timedelta>|<datetime.time>|<str>
https://gto76.github.io/python-cheatsheet/ 41/60
7/10/2021 Comprehensive Python Cheatsheet
Retention
retention=<int>|<datetime.timedelta>|<str>
# Scraping
Scrapes Python's URL, version number and logo from its Wikipedia page:
WIKI_URL = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
try:
html = requests.get(WIKI_URL).text
logo_url = table.find('img')['src']
logo = requests.get(f'https:{logo_url}').content
file.write(logo)
print(python_url, version)
except requests.exceptions.ConnectionError:
# Web
from bottle import run, route, static_file, template, post, request, response
import json
Run
Static Request
@route('/img/<image>')
def send_image(image):
Dynamic Request
@route('/<sport>')
def send_page(sport):
https://gto76.github.io/python-cheatsheet/ 42/60
7/10/2021 Comprehensive Python Cheatsheet
REST Request
@post('/<sport>/odds')
def odds_handler(sport):
team = request.forms.get('team')
response.headers['Content-Type'] = 'application/json'
response.headers['Cache-Control'] = 'no-cache'
Test:
>>> response.json()
# Profiling
Stopwatch
...
High performance:
...
Timing a Snippet
0.34986
Profiling by Line
@profile
def main():
a = [*range(10000)]
b = {*range(10000)}
main()
https://gto76.github.io/python-cheatsheet/ 43/60
7/10/2021 Comprehensive Python Cheatsheet
$ kernprof -lv test.py
=======================================================
1 @profile
2 def main():
=======================================================
2 def main():
Call Graph
filename = f'profile-{datetime.now():%Y%m%d%H%M%S}.png'
drawer = output.GraphvizOutput(output_file=filename)
with PyCallGraph(drawer):
<code_to_be_profiled>
# NumPy
Array manipulation mini-language. It can run up to one hundred times faster than the
equivalent Python code. An even faster alternative that runs on a GPU is called CuPy.
import numpy as np
<array> = np.array(<list>)
<array> = np.ones(<shape>)
<array>.shape = <shape>
<view> = <array>.reshape(<shape>)
<array> = <array>.sum(axis)
indexes = <array>.argmin(axis)
Indexing
<1d_view> = <2d_array>[row_index]
https://gto76.github.io/python-cheatsheet/ 44/60
7/10/2021 Comprehensive Python Cheatsheet
<1d_array> = <2d_array>[row_indexes, column_indexes]
<2d_array> = <2d_array>[row_indexes]
<1d_array> = <2d_array>[<2d_bools>]
Broadcasting
Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes
and/or dimensions.
1. If array shapes differ in length, left-pad the shorter shape with ones:
2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
Example
For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]):
[[ 0.1],
[ 0.6],
[ 0.8]]
[[ 0. , -0.5, -0.7],
[ 0.5, 0. , -0.2],
[ 0.7, 0.2, 0. ]]
[[ 0. , 0.5, 0.7],
[ 0.5, 0. , 0.2],
[ 0.7, 0.2, 0. ]]
>>> i = np.arange(3)
[0, 1, 2]
>>> distances.argmin(1)
[1, 2, 1]
# Image
https://gto76.github.io/python-cheatsheet/ 45/60
7/10/2021 Comprehensive Python Cheatsheet
<Image> = Image.new('<mode>', (width, height)) # Also: `color=<int/tuple/str>`.
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
img.convert('RGB').save('test.png')
img.convert('RGB').save('test.png')
Image Draw
<ImageDraw> = ImageDraw.Draw(<Image>)
https://gto76.github.io/python-cheatsheet/ 46/60
7/10/2021 Comprehensive Python Cheatsheet
# Animation
Creates a GIF of a bouncing ball:
import imageio
WIDTH, R = 126, 10
frames = []
y = sum(range(velocity))
draw = ImageDraw.Draw(frame)
frames.append(frame)
frames += reversed(frames[1:-1])
# Audio
import wave
Bytes object contains a sequence of frames, each consisting of one or more samples.
In a stereo signal, the 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 │ 0 │ 128 │ 255 ┃
┃ 2 │ -32768 │ 0 │ 32767 ┃
┃ 3 │ -8388608 │ 0 │ 8388607 ┃
┃ 4 │ -2147483648 │ 0 │ 2147483647 ┃
┗━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━┷━━━━━━━━━━━━━┛
https://gto76.github.io/python-cheatsheet/ 47/60
7/10/2021 Comprehensive Python Cheatsheet
def read_wav_file(filename):
def get_int(bytes_obj):
sampwidth = file.getsampwidth()
frames = file.readframes(-1)
def get_bytes(a_float):
a_float += sampwidth == 1
file.setnchannels(nchannels)
file.setsampwidth(sampwidth)
file.setframerate(framerate)
Examples
write_to_wav_file('test.wav', samples_f)
write_to_wav_file('test.wav', samples_f)
p = file.getparams()
frames = file.readframes(-1)
Text to Speech
import pyttsx3
engine = pyttsx3.init()
engine.runAndWait()
https://gto76.github.io/python-cheatsheet/ 48/60
7/10/2021 Comprehensive Python Cheatsheet
# Synthesizer
Plays Popcorn by Gershon Kingsley:
F = 44100
P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,,'
P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,,'
simpleaudio.play_buffer(samples_b, 1, 2, F)
# Pygame
Basic Example
import pygame as pg
pg.init()
deltas = {pg.K_UP: (0, -1), pg.K_RIGHT: (1, 0), pg.K_DOWN: (0, 1), pg.K_LEFT: (-1, 0)}
screen.fill((0, 0, 0))
pg.display.flip()
Rectangle
Surface
<Surf> = pg.Surface((width, height), …) # New RGB surface. Add `pg.SRCALPHA` for RGBA.
https://gto76.github.io/python-cheatsheet/ 49/60
7/10/2021 Comprehensive Python Cheatsheet
<Surf>.fill(color) # Tuple, Color('#rrggbb[aa]') or Color(<name>).
line(<Surf>, color, (x1, y1), (x2, y2), width) # Draws a line to the surface.
Font
<Font> = pg.font.Font('<path>', size) # Loads the TTF file. Pass None for default.
<Surf> = <Font>.render(text, antialias, color) # Background color can be specified at the end.
Sound
https://gto76.github.io/python-cheatsheet/ 50/60
7/10/2021 Comprehensive Python Cheatsheet
https://gto76.github.io/python-cheatsheet/ 51/60
7/10/2021 Comprehensive Python Cheatsheet
import collections, dataclasses, enum, io, itertools as it, pygame as pg, urllib.request
def main():
def get_screen():
pg.init()
def get_images():
url = 'https://gto76.github.io/python-cheatsheet/web/mario_bros.png'
img = pg.image.load(io.BytesIO(urllib.request.urlopen(url).read()))
def get_mario():
def get_tiles():
clock = pg.time.Clock()
update_position(mario, tiles)
clock.tick(28)
x, y = mario.spd
x -= x // abs(x) if x else 0
x, y = mario.rect.topleft
for _ in range(n_steps):
x, y = x + mario.spd.x/n_steps, y + mario.spd.y/n_steps
mario.rect.topleft = x, y
deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)}
return P(x=0 if (D.w in bounds and spd.x < 0) or (D.e in bounds and spd.x > 0) else spd.x,
y=0 if (D.n in bounds and spd.y < 0) or (D.s in bounds and spd.y > 0) else spd.y)
def get_frame_index():
return 4
https://gto76.github.io/python-cheatsheet/ 52/60
7/10/2021 Comprehensive Python Cheatsheet
pg.display.flip()
if __name__ == '__main__':
main()
# Pandas
import pandas as pd
Series
x 1
y 2
<Sr> = Series(<dict/Series>, index=<list>) # Only keeps items with keys specified in index.
<Sr> = <Sr> +-*/ <el/Sr> # Items with non-matching keys get value NaN.
The way 'aggregate()' and 'transform()' find out whether the passed function
accepts an element or the whole Series is by passing it a single value at first and if it
raises an error, then they pass it the whole Series.
x 1
y 2
https://gto76.github.io/python-cheatsheet/ 53/60
7/10/2021 Comprehensive Python Cheatsheet
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
┠─────────────┼─────────────┼─────────────┼───────────────┨
┃ sr.apply(…) │ 3 │ sum 3 │ s 3 ┃
┃ sr.agg(…) │ │ │ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
┠─────────────┼─────────────┼─────────────┼───────────────┨
┃ sr.apply(…) │ │ rank │ ┃
┃ sr.agg(…) │ x 1 │ x 1 │ r x 1 ┃
┃ sr.trans(…) │ y 2 │ y 2 │ y 2 ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
Last result has a hierarchical index. Use '<Sr>[key_1, key_2]' to get its values.
DataFrame
x y
a 1 2
b 3 4
<DF> = <DF> +-*/ <el/Sr/DF> # Items with non-matching keys get value NaN.
<DF> = <DF>.filter('<regex>', axis=1) # Only keeps columns whose key matches the regex.
x y
a 1 2
b 3 4
y z
b 4 5
c 6 7
https://gto76.github.io/python-cheatsheet/ 54/60
7/10/2021 Comprehensive Python Cheatsheet
┏━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨
┃ │ 1 3 4 5 │ │ 3 4 5 │ right_on parameters. ┃
┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨
┃ how=…) │ b 3 4 4 5 │ 3 4 4 5 │ 3 4 4 5 │ If r is a series, it is ┃
┃ │ c . . 6 7 │ │ │ treated as a column. ┃
┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨
┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨
┃ │ c . . 6 7 │ │ │ treated as a column. ┃
┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨
┃ │ c . 6 7 │ │ │ R must be a DataFrame. ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━┛
All operations operate on columns by default. Use 'axis=1' parameter to process the
rows instead.
x y
a 1 2
b 3 4
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
┠─────────────┼─────────────┼─────────────┼───────────────┨
┃ df.apply(…) │ │ x y │ ┃
┃ df.agg(…) │ x 4 │ sum 4 6 │ x 4 ┃
┃ │ y 6 │ │ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
┠─────────────┼─────────────┼─────────────┼───────────────┨
┃ df.apply(…) │ x y │ x y │ x ┃
┃ df.trans(…) │ b 2 2 │ a 1 1 │ b 2 ┃
┃ │ │ b 2 2 │ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
https://gto76.github.io/python-cheatsheet/ 55/60
7/10/2021 Comprehensive Python Cheatsheet
Encode, Decode:
<DF> = pd.read_json/html('<str/path/url>')
<DF> = pd.read_csv/pickle/excel('<path/url>')
<DF> = pd.read_clipboard()
<dict> = <DF>.to_dict(['d/l/s/sp/r/i'])
<str> = <DF>.to_json/html/csv/markdown/latex([<path>])
<DF>.to_pickle/excel(<path>)
<DF>.to_sql('<table_name>', <connection>)
GroupBy
Object that groups together rows of a dataframe based on the value of the passed column.
>>> df.groupby('z').get_group(3)
x y
a 1 2
>>> df.groupby('z').get_group(6)
x y
b 4 5
c 7 8
>>> gb = df.groupby('z')
x y z
3: a 1 2 3
6: b 4 5 6
c 7 8 6
┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
┠─────────────┼─────────────┼─────────────┼─────────────┼───────────────┨
┃ gb.agg(…) │ x y │ x y │ x y │ x ┃
┃ │ z │ a 1 1 │ rank rank │ a 1 ┃
┃ │ 3 1 2 │ b 1 1 │ a 1 1 │ b 1 ┃
┃ │ 6 11 13 │ c 2 2 │ b 1 1 │ c 2 ┃
┃ │ │ │ c 2 2 │ ┃
┠─────────────┼─────────────┼─────────────┼─────────────┼───────────────┨
┃ gb.trans(…) │ x y │ x y │ │ ┃
┃ │ a 1 2 │ a 1 1 │ │ ┃
┃ │ b 11 13 │ b 1 1 │ │ ┃
┃ │ c 11 13 │ c 1 1 │ │ ┃
┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
https://gto76.github.io/python-cheatsheet/ 56/60
7/10/2021 Comprehensive Python Cheatsheet
Rolling
# Plotly
Continent
South America
North America
600
Total Deaths per Million
Europe
Asia
Africa
400 Oceania
200
Apr 2020 May 2020 Jun 2020 Jul 2020 Aug 2020 Sep 2020 Oct 2020 Nov 2020
Date
covid = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv',
continents = pd.read_csv('https://datahub.io/JohnSnowLabs/country-and-continent-codes-' + \
'list/r/country-and-continent-codes-list-csv.csv',
usecols=['Three_Letter_Country_Code', 'Continent_Name'])
df = df.groupby(['Continent_Name', 'date']).sum().reset_index()
https://gto76.github.io/python-cheatsheet/ 57/60
7/10/2021 Comprehensive Python Cheatsheet
Confirmed covid cases, Dow Jones, gold, and Bitcoin price:
200
60M Total Cases
Bitcoin
50M Gold
150 Dow Jones
40M
Total Cases
%
30M 100
20M
50
10M
0 0
Mar 2020 Apr 2020 May 2020 Jun 2020 Jul 2020 Aug 2020 Sep 2020 Oct 2020 Nov 2020
import pandas as pd
import plotly.graph_objects as go
def main():
display_data(wrangle_data(*scrape_data()))
def scrape_data():
def scrape_covid():
url = 'https://covid.ourworldindata.org/data/owid-covid-data.csv'
def scrape_yahoo(slug):
url = f'https://query1.finance.yahoo.com/v7/finance/download/{slug}' + \
'?period1=1579651200&period2=1608850800&interval=1d&events=history'
return df.set_index('Date').Close
df = df.sort_index().interpolate()
df = df.loc['2020-02-23':'2020-11-25']
def display_data(df):
figure = go.Figure()
figure.add_trace(trace)
figure.update_layout(
legend=dict(x=1.1)
).show()
if __name__ == '__main__':
main()
https://gto76.github.io/python-cheatsheet/ 58/60
7/10/2021 Comprehensive Python Cheatsheet
# PySimpleGUI
import PySimpleGUI as sg
# Appendix
Cython
import <cython_script>
<cython_script>.main()
Definitions:
All 'cdef' definitions are optional, but they contribute to the speed-up.
Script needs to be saved with a 'pyx' extension.
self.<attr_name> = <arg_name>
PyInstaller
$ pyinstaller script.py --add-data '<path>:.' # Adds file to the root of the executable.
https://gto76.github.io/python-cheatsheet/ 59/60
7/10/2021 Comprehensive Python Cheatsheet
#!/usr/bin/env python3
# Usage: .py
def main():
pass
###
## UTIL
def read_file(filename):
return file.readlines()
if __name__ == '__main__':
main()
# Index
Only available in the PDF.
Ctrl+F / ⌘F is usually sufficient.
Searching '#<title>' will limit the search to the titles.
https://gto76.github.io/python-cheatsheet/ 60/60