You are on page 1of 59
7ero20 Comprehensive Python Cheatsheet sure Sor Comprehensive Python Cheatsheet Download text il, Buy PDF, Fork me on Git or Check out FAQ. HhSeSeehes # Contents ToC = { "1. Collections': (List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator], Types": [Type, String, Regular_€xp, Format, Nunbers, Combinatorics, Datetime], syntax [Args, Inline, Closure, Decorator, ‘Class, Duck_Type, Enum, Exception], System’: [Exit, Print, Input, Command_Line’Arguments, Open, Patn, 0S_Commands], Data’ [ISON, Pickle, CSV, SQLite, Bytes, Struct, Array, Menory_View, Deque], Advanced’: [Threading Operator, Introspection, Metaprograming, Eval, Coroutine], Libraries': [Progress_8ar, Plot, Table, Curses, Logging, Scraping, Web, Profile, NumPy, Tage, Audio, Games, Data, Cython} # Main if _name_ Fain() main # Runs main() if file wasn't imported. # List = [frominclusive : to_exclusive : #step_size] 1 1 . append() . extend() {] . sort() Treverse() ist» = sorted() = reversed() hitpsigto76.gthubiopython-cheatsheet! 1159 7rero20 Comprehensive Python Cheatsheet sun_of_elements elementwise_sun sorted_by_second sum() [sum(pair) for pair in zip(list_a, list_b)] sorted(, key=lambde et: el(1]) sorted_by both = sorted(, key=lambde el: (el[1], el{0])) flatter_list List (itertools. chain. from_iterable()} product_ot_elens = functools.reduce(Lambda out, el: out * el, ) list_of_chars = list() ‘+ Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above. = ,count(sinsert(inder, sels) # Inserts item at index and moves the rest to the right. Sele = -pop({index}) Removes and returns item at index or from the end. renovelcel>) # Removes first occurrence of iten or raises Valuet*ror. Slistesclear() # Renoves all items, Also works on dictionary and set. # Dictionary eview = .keys() CouL, of keys that reflects changes. ,values() eview> = ,items() Coll. of values that reflects changes. Coll. of key-value tuples that reflects chs. eae value = .get (key, defaut=None) # Returns default if key is missing. value = .setdefault(key, default-None) # Returns and writes default if key is missing. = collections .defaultdict () # Creates a dict with default value of type. = collections ,defaultdict(Lambda: 1) # Creates a dict with default value 1, = dict() # Creates a dict from coll. of key-value pairs. = dict(zip(keys, values)) # Creates a dict from two collections. = dict. fromkeys(keys [, value]) 4# Creates a dict from collection of keys. .update() * h matching keys. value = .pop(key) # Removes item or raises Keyérror. {k for k, v in .items() if v == value) # Returns set of keys that point to the value. {k: v for k, v in ,items() if k in keys} # Returns a dictionary, filtered by keys. Adds itens. Replaces ones wit Counter >>> from collections import Counter pe> colors = ['biue', 'blue', 'blue', ‘red’, ‘red'] >>> counter = Counter(colors) >>> counter[*yeltow"] += 1 Counter({"blue': 3, *red': 2, ‘yellow’: 1}) bee counter.most_common() [0] (‘blue', 3) # Set = set() . add () . update () 1: |= { |= we hitpsigto76.gthubiopython-cheatsheet! 2189 7rero20 Comprehensive Python Cheatsheet = .union() # Or: | eset> = , intersection() # Or: & = , difference() # Or: ~ synmetric_difference() # Or: * . issubset() # Or: <= = . issuperset () # Or: >= = .pop() # Raises Keyrror if eupty. . remove() # Raises KeyError if missing. , discard() # Doesn't raise an error. Frozen Set ‘+ Isimmutable and hashable. ‘+ That means it can be used as a key in a dictionary or as an element in a set. = frozenset() # Tuple ‘Tuple is an immutable and hashable list. tuples = () = (, ) stuple> = (cells, [, Named Tuple ‘Tuple's subclass with named elements. oe» from collections import namedtupte pep Point = namedtuple('Point', "x y") >>> p = Point(1, y=2) Point(x=1, y=2) >>> p[0] 1 S5> px 1 pep getattr(p, 2 ee vy) fields # Or: Point, fields y) # Range range> = range(to_exclusive) = range(from_inclusive, to_exclusive) = range(from_inclusive, to_exclusive, +step_size) fron_inclusive to_exclusive .start = .stop hitpsigto76.gthubiopython-cheatsheet! 189 7ero20 Comprehensive Python Cheatsheet # Enumerate for i, el in enunerate( [, istart]): # Iterator = iter() = iter( = next( [, default]) = List() Itertoots fron itertools import count, repeat, cycle, = count(start=0, step=1) = repeat( [, tines]) = cycle( = chain( [, -++1) = chain, from_iterable() # “iter()* returns unnodified iterator. # A sequence of return values until 'to_exclusive'. # Raises StopIteration or returns ‘default! on end. # Returns a list of iterator’s remaining clenents. chain, islice Returns updated value endlessly. Accepts floats. Returns element endlessly or ‘times’ times. Repeats the sequence endlessly. # Empties collections in order. # Empties collections inside a collection in order. = islice(, to_exclusive) = islice(, from_inclusive, to_exclusive [, #step_size]) # Generator ‘+ Any function that contains a yield statement returns a generator, ‘+ Generators and iterators are interchangeable. def count(start, step): while True: yield start start += step pee counter = count(10, 2) >>> next(counter), next(counter), next(counter) (10, 12, 14) # Type + Everything is an object. + Every object has a type. + ‘Type and class are synonymous. = type() = isinstance(, ) pep type('a!), 'a'._class_, str # Or: ._class_ # Or: issubclass(type(), ) (, ) hitpsigto76.gthubiopython-cheatsheet! 4189 7ero20 Comprehensive Python Cheatsheet ‘Some types do not have built-in names, so they must be imported: fron types import FunctionType, MethodType, LanbdaType, GeneratorType Abstract Base Classes 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. >e> from collections.abe import Sequence, Collection, Iterable >e> isinstance((1, 2, 3], Tterable! ) True Sequence | Collection | Iterable list, range, str ’ ’ : dict, set ’ ’ iter | ’ >>> isinstance(123, Number) >e> from numbers import Integral, Rational, Real, Complex, Number True Integrat | Rationat | Reat | Complex ] Nunber int ’ ’ ’ 2 : fractions. Fraction ’ ’ ’ ’ float ’ 2 Y complex . ’ decimal, Decimal ’ # String = .strip() estr> = ") = .split() = .split(sep-None, maxsplit = , split Lines (keepends=False) = ,join() = in = .startswith() .endswith () . find() , index() = -replace(old, new [, = ,translate() chr() ord() hitpsigto76.gthubiopython-cheatsheet! count} ) SeHee sene ne ee Strips all whitespace characters fron both ends. Strips all passed characters from both ends. Splits on one or more whitespace characters. Splits on ‘sep’ str at most ‘maxsplit’ times. Splits on \n,\r,\r\ns Keeps them if *keepends', Joins elements using string as separator. Checks if string contains a substring. Pass tuple of strings for multiple options. Pass tuple of strings for multiple options. Returns start index of first match or ~1. Same but raises ValueError if missing. Replaces ‘old' with ‘new’ at most ‘count’ times. Use “stremaketrans()” to generate table, Converts int to Unicode chars Converts Unicode char to ints e150 7ero20 Comprehensive Python Cheatsheet * Also: 'lstrip()', 'rstrip()' + Also: "Lower() capitalize()' and 'title()'. Property Methods [C981 | te2a-z) |G ey) (0-9) isprintable() ’ ’ ’ ’ 2 isatnum() ’ : 2 isnumeric() ’ ’ ’ isdigit() ’ ’ isdecimal() 2 + Also: 'isspace()' checks for '[ \t\n\r\f\val # Regex import re = re.sub(, new, text, count=0) # Substitutes all occurrences with 'new'. = re:findall(cregex>, text) # Returns all occurrences as strings. = re-split(, text, maxsplit=0) # Use brackets in regex to include the matches. latch» = ressearch( = resmatch(, ‘text) # Searches only at the beginning of the text. = re:finditer(, text) # Returns all occurrences as match objects. arch( and matcho 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 the "\n'. + Use r'\1' or '\1' for backreference. + Add '?! after an operator to make it non-greedy. Match Object = datch>.group() # Returns the whole match. Also group(0)- sstr> = Match>.group(1) # Returns part in the first bracket. Stupte> = atch>.groups() # Returns all bracketed parts. = atch>.start() # Returns start index of the match. = Match>-end() # Returns exclusive end index of the maten. Special Sequences + By default digits, alphanumerics and whitespaces from all alphabets are matched, unless “Flags=re.ASCIT' argument is used. + Use a capital letter for negation. ‘Nd! == t10-9]' # Matches any digit. ‘Nw! = *[ar2A-20-9.)' # Matches any alphanumeric. Ns) == "1 \t\n\e fv)! # Natches any whitespace, # Format = f'{)! = "{}, J" format (Zel_i>, ) ps9to78 github iclpytnon-cheatshet! oso 7ero20 Comprehensive Python Cheatsheet Attributes >>> from collections import namedtuple >>> Person = nanedtuple("Person*, 'nane height") 35> person = Person(‘Jean-Lue', 187) 55> #{person. height)" “187° 25> “{psheight}' «format (p=person) 7 "18 General Options {:<10} # cele {eel>:*10} #o eels * {:>10} a cel" {:.<10} eee! {eel>:<0} # eels! Strings ‘tr* calls object's repr() method, instead of strQ, to get a string. (‘abede! 17:10) # "abcde" (abcde: # ‘abe . (abede' # tabe! Numbers { 123456:10,} #* 123,456" #* 123/456" #473456" #123456" #123456" # 173456" Floats 210.3} #423 10:31) #1335" 10.3¢) 4 * 1,235ev00" 10:38} #* 123.4568" ‘Comparison of presentation types: | (efloat>y {floats} {Float>se} {floats} 0.000056769 | _'5.6789e-05" 9.000057" | '5.6789006-05' *0.005679%" 800056789 *0.00056789° so.e00568' | *5.6789006-04° 0.056788" 0.0056789 *9.0056789" 9.005679" | '5.6789000-03' 9.567898" 0.056769, *9.056789" ‘0.056789! | '5.6789006-02' 1516789008" 0.56789 *0.56789" +0.567890° | '5.678900e-01' | "56. 7890008" 5.6789 °5,6789° '5,678900' | '5,678900e+00" | 5678900008" 56.789 56.789" +56,7a9000' | '5.678900e-01' | ‘5678. 9000008" 367.89 +567.89" +567,890000' | ‘5.678900e+02' | ‘5679.000000%" hitpsigto76.gthubiopython-cheatsheet! 189 7rero20 Comprehensive Python Cheatsheet | ( int () # Or: math. floor() float () # Or: eteint> = complex(real=0, imag-0) —# Or: + j = fractions.Fraction(@, 1) # Or: Fraction(nunerator=@, denominato: = decimal.Decimal() # Or: Decimal((sign, digits, exponent)) + Sint()' and 'float() ' raise ValueError on malformed strings. ‘+ Decimal numbers can be represented exactly, unlike floats where '1.1 + 2.2 != 3.3" ‘+ Precision of decimal operations is set with: ‘decimal. getcontext().prec = ' Basic Functions = pow(, ) # Or: er = abs() # = abs() ‘num> = round( [, sndigits]) # “round(126, -1) == 130° Math fron math import e, pi, inf, nan, isinf, isnan fron math import cos, acos,’sin, asin, tan, atan, degrees, radians fron math import log, log10, 1092 Statistics fron statistics import mean, median, variance, stdev, pvariance, pstdev Random fron random import random, randint, choice, shuffle = random() = randint(from_inclusive, to_inclusive) choice() shuffle() hitpsigto76.gthubiopython-cheatsheet! aise 7ero20 Bin, Hex Ab = int(*z nt(*sebebin>", 0) *[-l@bebin>' = bin() Bitwise Operators int> & | int> * int> = << n_bits - # Combinatorics ‘+ Every funetion returns an iterator. eae ween Comprehensive Python Cheatsheet Or: #0xchex> or: int(*schex>', 16) Or: int(*#0xchex>", 0) Or: hex() And or Xor (@ if both bits equal) Shift left (>> for right) Not (also: - - 1) ‘+ Ifyou want to print the iterator, you need to pass it to the list( function first! fron itertools import product, combinations, combinations_with_replacenent, permutations >>> product({®, 1], repeat=3) (0, @, 0) pee product(‘ab', '12') (at, 11), Cat, 12"), (bt, 24), (bY 1297 >>> combinations(‘abc', 2) (Cat, tb), (at, tc), (bt, te!) (, @,'1), (8, 1, ®), (@, 1, 2), +O), (1, @ 1), (1, 1, 0), (2, 2, 2)) >e> combinations with_replacement(‘abc', 2) (at, ta), (lat, tT), (fat, tc), (ibe, bt), (bY, te"), (et) te) >>> permutations(‘abc', 2) (Cat, tb), Cat, tet), (bt, tat), (tbe) tet), (et, tat), (ety tb] # Datetime ‘+ Module ‘datetime’ provides ‘date’ , time’ , ‘datetime’
and ‘timedelta’
classes. All are immutable and hashable. ‘+ Time and datetime objects can be ‘aware’ , meaning they have defined timezone, or ‘naive' , meaning they don't. ‘+ Ifobject is naive, itis presumed to be in the system's timezone. fron datetime import date, time, datetime, timedelta fron dateutil.tz import UTC, tztocal, gettz, resolve_imaginary hitpsigto76.gthubiopython-cheatsheet! ise 7ero20 Comprehensive Python Cheatsheet Constructors = date(year, month, day) = time(hour“0, minute=®, second=, microsecond=0, tzinfo-None, fold=0)
= datetime(year, month, day, hour=, minute=@, second=@, ...)
= timedelta(days=0, seconds=0, microseconds=0, millisecond: minutes=8, hours=0, weeks=0) + Use '<0/DT>.weekday() ' to get the day of the week (Mon == 0). + 'fold=1' means the second pass in case of time jumping back for one hour. + ‘ = resolve_imaginary()' fixes DTs that fall into the missing hour. Now = D/DT. today() # Current local date or naive datetine. DT.utcnow() # Naive datetine from current UTC tine. = DT-now() # Aware datetime from current tz time. ‘+ To extract time use '.time()', '. time()' or '.timetz()' Timezone stzinfo> = UTC # UTC timezone. London without DST. = tztocal() # Local timezone. Also gettz(). = gettz('/") # ‘Continent/City Name! timezone or None.
.astimezone() # Datetine, converted to passed timezone. = . replace(tzinfo=) # Unconverted object with new timezone. Encode = D/T/DT. fromisoformat(*') # Object from IS0 string. Raises ValueError.
DI.strptime(, '') # Datetime from str, according to format. = D/DT. fromordinal() #D/DTn from days since Christ, at midnight. DT. fromtimestamp() # Local time DTn from seconds Since Epoch. DT. fromtimestamp(, ) # Aware datetime from seconds since Epoch. + 180 strings come in following forms: 'YYYY-HM-DD', 'HH:MM:SS. fff fff [+] ', or both separated by an arbitrary character. Offset is formatted as: 'HH:MM ‘+ Epoch on Unix systems is: '1970-@1-01 00:00 UTC’, ‘1970-01-01 @1:00 CET", Decode estr> = . isofornat (sep='T*) # Also timespec="auto/hours/minutes/seconds'. .strftime('') _ # Custom string representation. . toordinal() # Days since Christ, ignoring time and tz. = .timestanp() # Seconds since Epoch, from DTn in local tz. = .timestamp() # Seconds since Epoch, from DTa. Format >>> from datetime import datetime bo> dt = datetime, strptime('2015~05-14 23:39:00,00 +0200", 'AY-An-Rd SH:AM:4S.8f 42") o> dt.strftime("&A, dth of BB ‘ay, %I:%8K%p 42") “Thursday, 14th of May '15, 11:39PM’ UTC+02:00" ‘+ When parsing, '%2" also accepts '#HH:NM' ‘+ For abbreviated weekday and month use "a" and "sb hitpsigto76.gthubiopython-cheatsheet! 10159 7ero20 Comprehensive Python Cheatsheet Arithmetics = +
# Returned datetine can fall into missing hour. = ~ # Returns the difference, ignoring time junps. <10> - # Ignores tine junps if they share tzinfo object. = ~ # Convert DTs to UTC to get the actual delta. # Arguments Inside Function Call () # £(0, 0) () # F020, x0) (, ) # f(0, y=0) Inside Function Definition def f(): # def T(x, y) def f() # def f( def f(, ): # def f(x, # Splat Operator Inside Function Call Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments. args = (1, 2) kwargs = (1x4 3, ‘y's 4, ‘24: 5} funclxargs, sekwargs) Is the same as: func(1, 2, 1 y=4y 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. def add(a): return sum(a) bem add(1, 2, 3) 6 Legal argument combinations: def f(x, y, 2): def f(x, x, y, 2) def f(x, *, y, 2) def f(x, y, *, 2) ) | FL, 2, 253) | FL, 2, 3) saan | f(, 2, 2=3) hitpsigto76.gthubiopython-cheatsheet! 189 7rero20 def def def def f(4args): f(x, xargs (args, 2): f(x, xargs, 2): saae def def def F(4erkwargs) : (x, erkwargs): f(r) x, etkwargs) wae def def def def f(4args, ++kwargs): f(x, sargs, e*kwargs) frargs, y, ekwargs) f(x, args, 2, #kwargs): Other Uses = [# [, = {# [, etuple> = (#ecollection>, [+ = {weedict> [, .1.]) head, +body, tail = Comprehensive Python Cheatsheet (1, ye2, 253) f(1, y=2, 23) | £1, 2, 263) | £1, 2, 3) fa, 14) 2) 3) | 4) 2, 3) ra, f(1, ye2, 253) | £1, 2, 253) # Inline Lambda = lambda: = lambda , : Comprehensions = [141 for i in range(10)) = {i for i in range(18) if i > 5} = (145 for i in range(10)) = {i: #2 for 1 in range(10)) out = [isj for i in range(1@) for j in range(10)] Is the same as: out = for i in range(10): for j in range(10): out append(i-j) fron functools import reduce = map(lambda x: x + 1, range(10)) = filter(Lambde x: x > 5, range(10)) = reduce(Lambda out, x: out + x, range(10)) hitpsigto76.gthubiopython-cheatsheet! #1, 2, very 10] #{6, 7, 8 9} # (5, 6, ws.) 14) #0! 0, 12, .. 18) # (1, 2, se, 18) # (6, 7, 8 9) #45, 12189 7ero20 Comprehensive Python Cheatsheet Any, All = any() # False if enpty. = all(et(1] for el in ) # True if enpty. If Else = if else boo [a if a else ‘zero for a in (0, 1, 2, 3)] ('zero", 1, 2, 3] Namedtuple, Enum, Dataclass fron collections import nanedtuple Point nanedtupte( "Point", "x y*) point Point(®, 0) from enun import Enum Direction = Enum('Direction', 'n es w') direction = Direction.n fron dataclasses import make_dataclass Creature = make_dataclass( ‘Creature’, [‘location', ‘direction’ ]) creature = Creature(Point(®, 0), Directionsn) # Closure ‘We have a closure in Python when: ‘+ Anested function references a value ofits enclosing function and then ‘+ the enclosing function returns the nested function. def get_multiplier(a) def out(b): return a + b return out pep 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 ‘.__closure__[0].cell_contents’. Partial from functools import partial = partial( [, , , «+.1) hitpsgt078 thu iopython-ce tsheot! 12159 7rero20 Comprehensive Python Cheatsheet >>> import operator as op >>> multiply by 3 = partial(op.mul, 3) >e> multiply_by_3(10) 30 ‘+ Partial is also useful in cases when function needs to be passed as an argument, because enables us to set its arguments beforehand, ‘+ A few examples being: ‘defaultdict()', ‘iter(, ‘to_exclusive) ' and dataclass's ' field (default_factory=) '. Non-Local If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless itis declared as a ‘global’ or a ‘nonlocal’ def get_counter() i=e def out() nonlocal 4 ied return i return out >>> counter = get_counter() >>> counter(), counter(), counter() (1, 2, 3) # Decorator ‘A decorator takes a function, adds some functionality and returns it. @decorator_name def function_that_gets_passed_to_decorator(): Debugger Example Decorator that prints function’s name every time it gets called. from functools import wraps def debug( func): @uraps( func) def out(*args, ++kwargs): print (func. _nane_) return func(wargs, *#kwargs) return out @debug def add(x, y) 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. hitpsigto76.gthubiopython-cheatsheet! aise 7ero20 Comprehensive Python Cheatsheet LRU Cache Decorator that caches function's return values. All function's arguments must be hashable. fron functools import Lru_cache @lru_cache(maxsize-None) def Fib(n return n if n <2 else fib(n-2) + fib(n=1) ‘+ CPython interpreter limits recursion depth 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. fron functools import wraps def debug(print_resutt= def decorator( func): @wraps( func) def out(xargs, xskwargs): result = func(xargs, #kwargs) print (func. _nane_, result if print_result else * return resutt return out return decorator tse) @debug(print_result=True) def add(x, y) returr x + y # Class class : def _init_(setf, a): Selfia=a def _repr_(self): Tlass_fame = self._class_._name_ return f*{class_nane}({self.alr})" def _str_(self) Feturn str(self.a) @classmethod def get_class_name(cls): return cls.__name_ ‘= Return value of repr() should be unambiguous and of str( readable. + Ionly repr() is defined, it will also be used for str, Str() use cases: print () print (f* (}") raise Exception() Loguru. Logger. debug () csv.writer() .writerow( (]) hitpsgt078 thu iopython-ce tsheot! 16159 7ero20 Comprehensive Python Cheatsheet Repr() use cases: print ([]) print (f* (!r}*) bo> Loguru. logger. exception() Z = dataclasses.nake_dataclass(*Z', ['a"]); print(Z(: def _init_(setf, a-None): Self.asa Inheritance class Person: def _init_(self, nane, age) Self name = none self.age = age class Employee(Person): def _init_(self, name, age, staff_oum): Super()._init_ (name, age) self-staff_num = staff_num Multiple Inheritance class A: pass class B: pass class C(A, B): pass ‘MRO determines the order in which parent classes are traversed when searching for a method: >>> C.mro() [, , , ] Property Pythonic way of implementing getters and setters. class MyClass ‘@property def a(setf): return self._a @a,setter def a(self, value): self._a = value bee el = MyClass() pop el.a = 123 >>> eli 123 hitpsigto76.gthubiopython-cheatsheet! 16159 7ero20 Comprehensive Python Cheatsheet Dataclass Decorator that automatically generates init(, repr and eqQ special methods. fron dataclasses import dataclass, field Ise, frozen=False) @dataclass (orde class : : : = : list/dict/set = field(default_factory=List/dict/set) ‘+ Objects can be made sortable with ‘order=True' and/or immutable and hashable with “frozen=True'. ‘+ Function field( is needed because ' = make_dataclass('', ) = make_dataclass('", ) = (‘', [, ]) Slots ‘Mechanism that restricts objects to attributes listed in ‘slots’ and significantly reduces their ‘memory footprint, class MyClassWithSlots: —slot: [lat] def _init_(sett): Selfia ed Copy fron copy import copy, deepcopy = copy() = deepcopy() hitpsigto76.gthubiopython-cheatsheet! ‘ise 292020 Comprenensve Python Cheatsheet # 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'eq0 method is not overridden, it returns *id(self) == id(other) ', which is the sameas ‘self is other'. + That means all objects compare not equal by default. ‘+ Only the left side object has eq0 method called, unless it returns Notimplemented, in ‘which case the right object is consulted. class MyComparable: def _init_(setf, a): Self.a=a def _eq_(self, other): TF isinstance(other, type(setf)): return self.a = other.a return NotImplenented Hashable ‘+ Hashable object needs both hash() and eqQ methods and its hash value should never change. ‘+ Hashable objects that compare equal must have the same hash value, meaning default hash0 that returns 'id(seUf) ' will not do. ‘+ That is why Python automatically makes classes unhashable if you only implement eq0. class MyHashable: def __init_(self, a) self. a @property’ def a(setf): return self._a def eq_(self, other): TF isinstance(other, return self.a = return NotInplenented def _hash_(setf): Teturn hash(self.a) type(setf)): other.a Sortable ‘+ With total_ordering decorator, you only need to provide eq() and one of ItQ, gt0, le0 or ‘ge special methods. fron functools import total_ordering @total_ordering class MySortable: def _init_(self, a) Felf.a=a def _eq_(self, other): TF isinstance(other, type(self)}: return self.a = other.a return NotImplenented def _lt_(self, other): Tf iSinstance(other, type(setf)): return self.a >> counter = Counter() me> next(counter), next(counter), next (counter) (a, 2, 3) 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. + File objects returned by the open() function, etc. Callable ‘+ All functions and classes have a call method, hence are callable ‘© When this cheatsheet uses '' as an argument, it actually means ‘'. class Counter: def _init_(setf): self.i def _call_(sett): Belfer 1 return self.i >>> counter = Counter() >>> counter(), counter(), counter() (1, 2,3) Context Manager ‘= Enter() should lock the resources and optionally return an object. ‘+ Exit0 should release the resources. ‘+ Any exception that happens inside the with block is passed to the exit() method, ‘+ Ifit wishes to suppress the exception it must return a true value. class MyOpen: def _init_(sett, filename): Self, filenane’= filename det _enter_(selt) Self. file = open(self. filename) return self. file def _exit_(selt, exc_type, exception, traceback): Belt. file.close() hitpsigto76.gthubiopython-cheatsheet! 7rero20 Comprehensive Python Cheatsheet pee with open('test.txt!, 'w') as file: ses file.write(*Hello World! *) 55> with MyOpen( ‘test, txt') as file: ves print (file. read(}) Hello world! # Iterable Duck Types lterable ‘+ Only required method is iter(. It should return an iterator of object's items. * Contains automatically works on any object that has iter defined. class MyIterable: def _init_(setf, a) Self.a def _iter_(self): Teturr iter(self.a) def _contains_(seif, et): Teturr et in setfia >>> obj = MyIterable( (1, 2, 3]) bee [el for el in obj] 1, 2, 31 p> 1 in obj True Collection + Only required methods are iter() and lend. ‘+ This cheatsheet actually means '' when it uses '". ‘+ Tchose not to use the name ‘iterable' because it sounds scarier and more vague than ‘collection’. class MyCoLlection: def _init_(self, a) Selfea =a def _iter_(setf): Teturr iter(self.a) def _contains_(seif, et): Teturr et in setfia def _len_(self) Teturr len(self-a) hitpsigto76.gthubiopython-cheatsheet! 20159 292020 Comprenensive Python Cheatsneet Sequence + Only required methods are len() and getitem@. ‘+ Getitem@ should return an item at index or raise IndexError. ‘+ Tter( and contains() automatically work on any object that has getitem( defined. + Reversed automatically works on any object that has getitem( and len( defined. class MySequence: def _init_(self, a) Selfea =a def _iter_(self): Teturr iter(self.a) def _contains_(seif, et): Teturr et in setfia def _len_(setf) Teturr_len(self.a) def _getitem_(self, i): Teturr selt.ali) def _reversed_(setf): Feturr reversed(setf.a) ‘ABC Sequence ‘+ Isa richer interface than the basic sequence. ‘= Extending it generates iter(, contains(, reversed(, index() and count. + Unlike ‘abc. Iterable' and ‘abc. Collection, itis not a duck type. That is why ‘issubclass(MySequence, abc.Sequence) ' would return False even if MySequence hhad all the methods defined. fron collections import abc class MyAbcSequence (abc. Sequence) def _init_(self, a) Selfa =a det _len_(setf) Tetur len(self.a) def _getitem_(self, i): Teturr setf.ali) ‘Table of required and automatically avalable special methods: Tterable | Collection | Sequence | abc.Sequence iter() ! ’ contains() : ’ : Ten() ! t 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 ",_abstractmethods_'. hitpsigto76.gthubiopython-cheatsheet! 2159 7ero20 Comprehensive Python Cheatsheet # Enum fron enun import Enum, auto class (Enun): ‘enenber_name_1> = member nane_2> = , = auto() «+ Ifthere are no numeric values before auto() it returns 1. + Otherwise it returns an increment of the last numeric value. = . # Returns a member. ‘menber> = {'"] # Returns a member or raises KeyErrors ‘emember> = () # Returns a member or raises ValueError. smenber>.name # Returns member's name. = .value # Returns member's value. List_of_members = List() menber_hanes [asname for a in ] menber_values = [2.value for a in ] randon_menber = random.choice( List()) def get_next_nenber(menber) : members = list(menber.class_) index = (members. index(member) + 1) % ten(menbers) return members [index] Inline Cutlery = Enum('Cutlery', 'fork knife spoon') Cutlery = Enum( ‘Cutlery’, [*fork", ‘knife’, ‘spoon']) Cutlery = Enum( ‘Cutlery’, {*fork": 1, "knifet: 2, ‘spoon': 3}) User-defined functions cannot be values, so they must be wrapped: from functools import partial LogicOp = Enum('Logicop', {*AND* “OR” partial(lambda t, rz Land r), : partial(lambda t, r: tor r)}) + Another solution in this particular case is to use built-in functions and_Q and or_( from the module operator. # Exceptions Basic Example try: except hitpsigto76.gthubiopython-cheatsheet! 22169 7292020 Comprenensive Python Cheatsneet ‘Complex Example try: except : ‘ except : else: ‘ finally: ‘+ Code inside the 'e1se" block will only be executed if 't ry" block had no exception. + Code inside the 'finally' block will always be executed. Catching Exceptions except as : except (, ..+) except (, ...) as : ‘+ Also catches subclasses of the exception. ‘= Use ‘traceback. print_exc() to print the error message to stderr. Raising Exceptions raise raise () raise ( [, ..+]) Re-raising caught exception: except as : raise Exception Object arguments = .args exc_type = , class filename = . traceback_.tb_frane. f_code.co_filenane func_name = .—traceback_.tb_frame. f_code.co_name Line Linecache, getLine( filename, , _traceback__.tb_Lineno) error_msg = traceback. format_exception(exc_type, , . _traceback_) hitpsigto76.gthubiopython-cheatsheet! 289 7ero20 Built-in Exceptions Comprehensive Python Cheatsheet BaseException [— systemexit # Raised by the sys.exit() function. {— keyboardInterrupt # Raised when the user hits the interrupt key (ctrl-c). LC exception # User-defined exceptions should be derived from this class. |— Arithneticérror # Base class for arithmetic errors. ZerobivisionError # Raised when dividing by zero. | attributetrror # Raised when an attribute is missing. | eorerror # Raised by input() when it hits end-of-file condition. | LookupError # Raised wnen a look-up on a collection fails. |— Indexérror # Raised when a sequence index is out of range. keyError # Raised wnen a dictionary key or set element is not found. |_ naneerror # Raised when a variable name is not found. | oserror # Failures such as “file not found” or “disk full". \— FileNotFounderror # When a file or directory is requested but doesn't exist. |_ runtineerror # Raised by errors that don't fall in other categories. \ Recursion€rror # Raised when the maximum recursion depth is exceeded, |— Stoprterat ion # Raised by next() when run on an empty iterator. |— Typeérror # Raised when an argunent is of wrong type. LC Vatuetrror # When an argunent is of right type but inappropriate value. LUnicodeError # Raised when encoding/decoding strings to/from bytes fails. Collections and their exceptions: List dict set getitem() | IndexError | KeyError pop) IndexError | KeyError | KeyError remove() | VatueError KeyError index() | ValueError raise TypeError( ‘Argument is of wrong type!") raise ValueError('Argument is of right type but inappropriate value!") raise Runtimefrror(*None of above!') User-defined Exceptions class MyError(Except ion) : pass class MyInputError(tyError) : pass # Exit Exits the interpreter by raising SystemExit exception. import sys sys.exit() sys-exit() sys-exit() hitpsigto76.gthubiopython-cheatsheet! # Exits with exit code @ (success). # Prints to stderr and exits with 1. # Exits with passed exit code. 2459 7ero20 Comprehensive Python Cheatsheet # Print print(, ..., sep! ', end="\n", filessys.stdout, flush=False) + Use 'filessys. stderr’ for messages about errors. ‘= Use ‘flush=True' to forcibly flush the stream. Pretty Print fron pprint import pprint pprint(, width=80, depth-None, compact=False, sort_dicts=True) ‘+ Levels deeper than ‘depth’ get replaced by ‘. # Input Reads a line from user input or pipe if present. = input (prompt-None) ‘+ Trailing newline gets stripped. ‘+ Prompt string is printed to the standard output before reading input. ‘+ Raises EOFError when user hits EOF (ctrl-d/2) or input stream gets exhausted. # Command Line Arguments import sys script_name = sys.argv[0] arguments = sys-argv(1:] ‘Argument Parser fron argparse import ArgumentParser, FileType p = ArgumentParser (descr iption=) p.add_argument('—', '--cname>', action="store_true') # Flag p.add_argument(‘—eshort_name>', *--cname>', type=) # Option p.add_argument(‘', type=, nargs=1) # First argument p.add_argument(‘', type=, nargs: # Renaining argunents p.add_argument(‘", type=ctype>, nargs: # Optional arguments args = p.parse_args() # Exits on error. value = args. + 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. = open('", modi » encoding-None, newline-None) hitpsigto76.gthubiopython-cheatsheet! 2559 7ero20 Comprehensive Python Cheatsheet ‘= ‘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 \¥' or \r\n' Modes «= 'r' Read (default, + 'w! - Write (truncate), ‘x! + Write of fail ifthe file already exists. ‘a - Append. ‘we! ~ Read and write (truncate). ‘74! - Read and write from the start. ‘az! - Read and write from the end. ‘tt -Text mode (default), + 'b' - Binary mode. Exceptions ‘= 'FileNotFoundError' can be raised when reading with 'r' or ‘r+. + 'FileExistsError’ can be raised when writing with 'x'. + 'IsADirectoryError' and 'PermissionError' can be raised by any. ‘= ‘OSError’ is the parent class of all listed exceptions. File Object .seek(@) # Moves to the start of the file. , seek (offset) # Moves ‘offset’ chars/bytes from the start. : seek(®, 2) # Moves to the end of the file. .seek(#offset, ) # Anchor: 0 start, 1 current position, 2 end. estr/bytes> = . read(size estr/pytes> = readline() ,readLines() estr/bytes> = next() 1) # Reads "size! chars/bytes or until EOF. Returns a Line or empty string/bytes on EOF. Returns a list of remaining lines. Returns a Line using buffer. Do not mix. .write() # Writes a string or bytes object. .writelines(. flush() # Flushes write buffer. ‘+ Methods do not add or strip trailing newlines, even writelines(. Read Text from File def read_file( filename with open(fitename, encoding='utf-8") as file return fite.readlines() Write Text to File def write_to_file(fitename, text): with open( filename, 'w', encoding="utf-8") as file: file.write(text) hitpsigto76.gthubiopython-cheatsheet! 26159 7ero20 # Path Comprehensive Python Cheatsheet fron os import getewd, path, Listdir fron glob import glob = getewd() = path. join(, ...) = path. abspath() = path. basename() = path. dirname() = path. splitext() = Lstdir(pat = glob( '") = path. exists () = path. isfile() = path. isdir() Direntry Returns the current working directory. Joins two or more pathnane components Returns absolute path. eae # Returns final component of the path. # Returns path without the final component. 4# Splits on last period of the final component. # Returns filenanes located at path. # Returns paths matching the wildcard pattern. sexists() . is_file() . is-dir() Using scandir) instead of listdir() can significantly increase the performance of code that also needs file type information. fron os import scandir = scandir(path='.") estr> = .path estr> = .name = open() Path Object from pathlib import Path Path( [ «++1) / [7 = Path() = Path. cwd() = .resolve() = . parent estr> = /name .stem = . suffix = _parts = , iterdir() = .glob('") str() open() hitpsigto76.gthubiopython-cheatsheet! Returns Direntry objects located at path. Returns path as a string. Returns final component as a string. Opens the file and returns file object. eae # Accepts strings, Paths and DirEntry objects. # One of the paths must be a Path object. Returns relative cwd, Also Path('."). Returns absolute cwd. Also Path().resolve(). Returns absolute Path without symlinks. wae Returns Path without final component. Returns final component as a string. Returns final component without extension. Returns final component's extension. Returns all components as strings. sake Returns dir contents as Path objects, Returns Paths matching the wildcard pattern. we # Returns path as @ string. # Opens the file and returns file object. 259 7129/2020 ‘Comprehensive Python Cheatsheet # 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. import 0s, shutit os.chdir() # Changes the current working directory. os.mkdir(, mode=00777) # Creates a directory. Mode is in octal. shutit.copy(from, to) 4 Copies the file. ‘to’ can exist or be a dir. shutil.copytree( from, to) # Copies the directory. ‘to’ must not exist. os.renane(from, to) # Renames/moves the file or directory. os.replace(from, to) 4# Sane, but overwrites ‘to’ if it exists. os, remove() # Deletes the file. os. rmdir () # Deletes the empty directory. shut il. rmtree() # Deletes the directory. ‘Shell Commands import os = 05-popen('' ) .read() Sends 1 + 1° tothe basic calculator and captures its output: be> from subprocess import run >>> run(*be", input="1 + 1\n", capture_output=True, encodin ConpletedProcess(args='bc', returncode=@, stdout: itf-8") \n', stderr=" ‘Sends test.n to the basic calculator running n standard mode and saves its output to test.out: >>> from shlex import split be> 0S.popen('echo 1+ 1 > test.in') >>> run(split( ‘bc ~s'), stdin=open('test.in'), stdoutzopen( ‘test.out!, ConpietedProcess(args={'bc', '=5*], returncode=0) >>> open('test.out").read() "2\n" # ISON ‘Text file format for storing collections of strings and numbers. import json estr> json.dumps(, ensure_asci: = json. toads() rue, indent=None) Read Object from JSON File def read_json_file(fitenane) : with open(fitename, encoding='utf-8") as file return json. load( file) hitpssigto76.gthubiopython-cheatshect! wy) 2059 7ero20 Comprehensive Python Cheatsheet Write Object to JSON File def write_to_json_file(filename, an_object) with open(fitename, ‘w', encoding='utf-8") as file: json.dump(an_object, file, ensure ascii=False, indent=2) # Pickle Binary file format for storing objects. import pickle = pickle. dumps() = pickle. loads () Read Object from Fite def read_pickle_file(filenane): with open(fitename, ‘rb') as file: return pickle. load( file) Write Object to File def write_to_pickle_file(filename, an_object): with open( filename, 'wb') as file: pickle. dump(an_object, file) # CSV ‘Text file format for storing spreadsheets. import csv Read = csv.reader() # Also: “dialect='excel', delimiters", "*. = next() # Returns next row as a List of strings. = list() # Returns List of remaining rows. ‘+ File must be opened with ‘newLine=""" argument, or newlines embedded inside quoted fields will not be interpreted correctly! Write ewriter> = csv.writer() # Also: “dialect='excel', delimiter=",'*. .writerow() # Encodes objects using ‘str()". ewriter>.writerows() # Appends multiple rows. + File must be opened with ‘newLine=""" argument, or \¥' will be added in front of every ‘\n' on platforms that use ‘\\n' line endings! hitpsigto76.gthubiopython-cheatsheet! 20159 7ero20 Comprehensive Python Cheatsheet Parameters ‘dialect! - Master parameter that sets the default values. ‘delimiter’ - A one-character string used to separate fields. 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' - specifies how writer terminates rows. + ‘quoting’ - Controls the amount of quoting: 0 - as necessary, 1 - all. = ‘escapechar’ - Character for escaping ‘quotechar’ if ‘doublequote' is False. + ‘quotechar* Dialects T excet excel-tab unix. T delimiter | ot quotechar doublequote True skipinitialspace False Lineterminator "\r\n" quoting ° escapechar None Read Rows from CSV File def read_csv_file(filenane) : with open( filename, encoding="utf-8", newLin return list(csv.reader(fite}) Write Rows to CSV File def write_to_csv_file(filename, rows) with open(fitename, 'w', encoding="utf-8', newLine=| writer = csv.writer(file) writer.writerows( rows) # SQLite *) as file: ") as file: 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 = sqlite3.connect(‘") .close() Read Returned values can be of type str, int, float, bytes or None. = .execute( ‘") = , fetchone() = .fetchall() hitpsigto76.gthubiopython-cheatsheet! # Also ":menory:". # Can raise a subclass of sqlite3.Error. # Returns next row, Also next(). # Returns remaining rows. Also list(). 20159 7ero20 Comprehensive Python Cheatsheet Write . execute ‘") con>. commit () or: with . execute '") 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. . execute( '", ) # Replaces '?'s in query with values. ,execute( ‘', ) _# Replaces ':'s with values. executemany('', ) # Runs execute() many tines. Example In this example values are not actually saved because ‘con, conmit()' is omitted! ppp con = sqlite}. connect(‘test.db') >>> con-execute(*create table person (person_id integer primary key, name, height)') be> conexecute("insert into person values (null, ?, ?)*, (‘Jean-Luc', 187)).lastrowid 1 >>> consexecute( "select * from person’), fetchall() (2, 'Jean-Luc', 187) MySQL Has a very similar interface, with differences listed below. 4 § pip3 install mysql-connector fron mysql import connector = connector. connect (host=, ~) # Suser=, password=, database=. = .cursor() # only cursor has execute method. .execute('') # Can raise a subclass of connector.Error. -execute(‘', ) # Replaces ‘%s's in query with values. sexecute('', ) # Replaces 'S()s's with values. # Bytes Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray. = b'' # Only accepts ASCIT characters and \x0d = \xff. = [] # Returns int in range from @ to 255. ebytes> = [eslice>] # Returns bytes even if it has only one element. = . join() # Joins elements using bytes object as separator. hitpsigto76.gthubiopython-cheatsheet! 1159 7ero20 Comprehensive Python Cheatsheet Encode = bytes() # Ints must be in range from @ to 255. = bytes(, ‘Utf-8") # Or: -encode(*utf-8") = .to_bytes(n_bytes, .) # “byteorder='big/little', signed-False*. = bytes. fromhex( "') # Hex numbers can be separated by spaces. Decode = List() # Returns ints in range from 0 to 255. estr> = str(, ‘utf-8") # Or: . decode( ‘utf-8") = int, from_bytes(, .) _# “byteorder='big/little', signed-False’. ‘chexe! = .hex() # Returns a string of hexadecimal numbers. Read Bytes from File def read_bytes( filename) with open(fitename, ‘rb') as file: return file.read() Write Bytes to File def write _bytes(filenane, bytes_obj with open(fitenane, ‘wb') as file file.write(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, fron struct import pack, unpack, iter_unpack sbytes> = pack(*', [, , = unpack('', ) = iter_unpack( '", ) » Example >>> pack('hhl', 1, 2, 3) b!\x00\x01\x00\x02\x00\x00\x00\x03' be> unpack(">hhl", b'\x@0\x01\x00\x02\x00\x00\x20\x03' ) (1, 2,3) Format For standard type sizes start format string with: + =! native byte order + '! big-endian (also '!") hitpsigto76.gthubiopython-cheatsheet! 22159 7ero20 Comprehensive Python Cheatsheet Integer types. Use a capital letter for unsigned type. Standard sizes are in brackets: + Ix! -pad byte + tb! chara) + tht -short @ + fit int (a) #1 tong @ + 'q" - long long (8) Floating point types: «Ft 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. fron array import array = array(*', ) — # Array from collection of numbers, = array('', ) # Array from bytes object. = array(*', ) # Treats array as a sequence of numbers. = bytes() # Or: ,tobytes() # 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. enview> memoryview() [] enview> = [] = . cast( '') .release() Decode .write() = bytes() = , join() = array(‘'; ) = Lst() estr> = str(, ‘utf-8") = int. from_bytes(' = ,hex() # Deque # # # # # aes saa Innutable if bytes, else mutable. Returns an int or 2 float. Mview with rearranged elenents. Casts menoryview to the new format. Releases the object's memory buffer. Writes mview to the binary file. Creates a new bytes abject. Joins mviews using bytes object as sep. Treats mview as a sequence of numbers. Returns lst of ints or floats. Treats mview as a bytes object. “byteorder="big/little', signe: Treats mview as a bytes object. A thread-safe list with efficient appends and pops from either side. Pronounced “deck. fron collections import deque = deque(, maxten=None) hitpsiigto76.gthubiepython-cheatshect! 23159 7rero20 Comprehensive Python Cheatsheet .appendleft() # Opposite element is dropped if full. .extendleft () # Collection gets reversed. = .popleft() # Raises IndexError if empty. .rotatel # Rotates elenents to the right. # Threading + Python interpreter can only run a single thread at a time. «That is why using multiple threads won't result in a faster execution, unless atleast one of the threads contains an /0 operation. fron threading import Thread, RLock, Semaphore, Event, Barrier Thread = Thread(target=) # Use “args=* to set arguments. .start() # Starts the thread. = , is_alive() # Checks if thread has finished executing, . join() # Waits for thread to finish. + 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 = RLock() .acquire() # Waits for lock to be available. release() # Makes the lock available again. or: lock = RLock() with Lock ‘Semaphore, Event, Barrier = Senaphore(valu # Lock that can be acquired ‘value" tines. = Event() # Method wait() blocks until set() is called. = Barrier(n_tines) # Method wait() blocks until it's called 'n_times* ‘Thread Pool Executor from concurrent.futures import ThreadPoolexecutor with ThreadPoolExecutor(max_workers=None) as executor: # Does not exit until done. = executor.map{ lambda x: x + 1, range(3)) # (1, 2, 3) = executorsmap(Lambda x, y: x + y, ‘abc", 1123") # ('a1', "b2", 'c3") = executor. submit( [, ,'...]) # Also visible outside block. Future: = .done() # Checks if thread has finished executing. = .result() # Waits for thread to finish and returns result. hitpsigto76.gthubiopython-cheatsheet! aise 292020 Comprenensive Python Cheatsneet ‘Queue A thread-safe FIFO queue. For LIFO queue use LifoQueue. fron queue import Queue = Queue(maxsiz .put() # Blocks until queue stops being full. =put_nowait () # Raises queve.Full exception if full. xel> = get() # Blocks until queue stops being empty. Zel> = -get_nowait() # Raises queve.Enpty exception if enpty. # Operator ‘Module of functions that provide the functionality of operators. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs fron operator import eq, 'ne, tt, le, ot, ge fron operator import and_, or_, not. fron operator import itengetter, attrgetter, methodcalter import operator as op elenentwise_sun = map(op.add, List_a, list_b) sorted_by_second = sorted(, key=op.itengetter(1)) sorted_by_both = sorted(, key=op,itengetter(1, @)) product_of_elems = functools.reduce(op.mul, ) Logicop fenun.Enum('LogicOp', {‘AND': op.and_, ‘OR* : op-or_}) last_el opsmethodcatter( ‘pop") () # Introspection Inspecting code at runtime. Variables = dirt) # Names of local variables (incl. functions). edict> = vars() # Dict of local variables. Also locals(). = globals() # Dict of global variables. Attributes = dir() # Names of object's attributes (incl. methods). = vars() # Dict of object's fields. Also ._dict_. = hasattr(, ‘") # Checks if getattr() raises an error. value = getattr(, ‘') # Raises AttributeErrar if attribute is missing. setattr(, ‘', value) # Only works on objects with _dict__ attribute. delattr(, ''} # Equivalent to “del .’. Parameters from inspect import signature ) no_of_params = len(.parameters) paran_names = list(.paraneters .keys()) paran_kinds = [a.kind for a in .parameters.values()] hitpsigto76.gthubiopython-cheatsheet! 26159 7292020 Comprehensive Pytnon Cheatsheet # 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. = type('*, , ) poz ype('Z', (), {'a': tabede', () 12345)) Meta Class Acclass that ereates classes. def my_meta_class(name, parents, attrs): attrs(‘a"] = ‘abcde’ return type(name, parents, attrs) oF: class MyMetaClass(type): def _new_(cls, name, parents, attrs): aEtrsTa"] = ‘abcde’ return type._new_(cls, name, parents, attrs) ‘+ New()is a class method that gets called before initQ, If it returns an instance of its class, then that instance gets passed to init as a ‘self’ argument, ‘+ Itreceives the same arguments as init0, 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 ifit has the ‘metaclass’ attribute defined. If not, recursively checks if any of his parents has it defined and eventually comes to type(. class MyClass(metaclass-MyMetaClass) : b = 12345 >>> MyClass.a, MyClass.b (abede", 12345) ‘Type Diagram type(MyClass) = NyMetaClass —# MyClass is an instance of MyMetaClass. ‘type(MyetaClass) == type # MyMetaClass is an instance of type. hitpsigto76.gthubiopython-cheatsheet! 26159 7rero20 Classes | Metaclasses MyClass — MyMetaClass object + type pooped ste ——_J) ni Inheritance Diagram WyClass.__base_ hyMetactass. base abject type Classes | Metaclasses MyClass | MyMetaClass object —— type str # Eval pe> from ast import Literal_eval po> Uiteraleval('l + 2") de> Literal_eval('[1, 2, 3]") (1, 2, 3] soi Uteral_eval(‘abs(1)") ValueError: malformed node or string hitpsigto76.gthubiopython-cheatsheet! Comprehensive Python Cheatsheet # MyClass is a subclass of object. # MyMetaClass is a subclass of type. arise 7ero20 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() ' 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: import asyncio, collections, curses, enun, random P = collections.namedtupte('P', 'x y") # Position D = enum,Enum('D', ‘ne sw") # Direction def main(screen): curses. curs_set(@) # Makes cursor invisible. screen. nodetay (True) # Makes getch() non-blocking. asyncio. run(main_coroutine(screen)) # Starts running asyncio code. async def main_coroutine(screen) : state = {'¥': P(, 0), **{id_: P(30, 10) for id_ in range(10)}} moves = asyncio.Queue() coros = (*(random_controtter(id_, moves) for id_ in range(10)), hunan_controtler(screen, moves), model(noves, state, *screen.getmaxyx()), view(state, screen) ) await asyncio.wait(Coros, return_when=asyncio, FIRST_COMPLETED) async def random_controUler(id_, moves): while True: moves. put_nowait((id_, random. chosce(List(D)))) await asyncio. sleep(random.random() / 2) async def human_controUler(screen, moves) while True: ch = screen.getch() key_mappings = {259: D.n, 261: D.e, 258: D.s, 260: D.w} if th in key_mappings moves. put_nowait((‘x*, key_mappings(ch])) await asyncio.sleep(0.01) async def model(noves, state, height, width): while state(‘*'] not in {p for id_, p in state.items() if id_ heh: id_, d= await moves.get() > tate id_] dettas = {Dens P(B, 1), Deez P(1, 0), Desi P(B, 1), Daw: P(-1, 0)} new = P(4[sum(a) for’a in zip(p, deltas[d])]} if 0 <= new p.x [, label=]) pyplot.plot(, ) pyplot. Legend() # Adds a legend. pyplot. saver ig( ‘") # Saves the figure, pyplot. show() # Displays the figure. pyplot.clf() # Clears the figure. # Table Prints a CSV fle as an ASCII table: # $ pip3 install tabulate import csv, tabulate with open(‘test.csv', encoding="utf-8", newLin rows = csv.reader(file) header = [a.title() for a in next(rows)] table = tabulate. tabulate(rows, header) print (table) ") as file: hitpsigto76.gthubiopython-cheatsheet! 29159 7ero20 Comprehensive Python Cheatsheet # Curses ‘Clears the terminal, prints a message and waits for the ESC key press: from curses import wrapper, curs_set, ascii fron curses import KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_LEFT def main(): wrapper (draw) def draw(screen): curs_set(0) # Makes cursor invisible. screen. nodelay (True) # Makes getch() non-blocking. screen. clear() screenvaddstr(0, 0, "Press ESC to quit. while Screen.getch() != ascii.esc pass # Coordinates are y, x. def get_border(screen): from collections import namedtuple P = namedtupte("P', "x y") height, width = screen. getmaxyx() returr’ P(width-1, height-1) if name == '_main_! main() # Logging # § pip3 install Loguru from loguru import logger logger.add( ‘debug _{time}.log', colorize-True) # Connects a log file. logger-addi 'error_{time}. log", level="ERROR") # Another file for errors or nigher. Logger.('A logging message. ") info’, 'success', ‘warning’, ‘error’, ‘critical’. Exceptions Exception description, stack trace and values of variables are appended automatically. tr except ||| + ‘! - Max file size in bytes. + ‘' - Max age ofa file. = '