由 neevop 十二月 9, 2022
Arguments
Inside Function Call
func(<positional_args>) # func(0, 0)
func(<keyword_args>) # func(x=0, y=0)
func(<positional_args>, <keyword_args>) # func(0, y=0)
Inside Function Definition
def func(<nondefault_args>): ... # def func(x, y): ...
def func(<default_args>): ... # def func(x=0, y=0): ...
def func(<nondefault_args>, <default_args>): ... # def func(x, y=0): ...
- Default values are evaluated when function is first encountered in the scope.
- Any mutation of a mutable default value will persist between invocations.
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 = {'x': 3, 'y': 4, 'z': 5}
func(*args, **kwargs)
Is the same as:
func(1, 2, x=3, y=4, z=5)
Inside Function Definition
Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.
def add(*a):
return sum(a)
>>> add(1, 2, 3)
6
Legal argument combinations:
def f(*args): ... # f(1, 2, 3)
def f(x, *args): ... # f(1, 2, 3)
def f(*args, z): ... # f(1, 2, z=3)
def f(**kwargs): ... # f(x=1, y=2, z=3)
def f(x, **kwargs): ... # f(x=1, y=2, z=3) | f(1, y=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(*args, y, **kwargs): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3)
def f(*, x, y, z): ... # f(x=1, y=2, z=3)
def f(x, *, y, z): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3)
def f(x, y, *, z): ... # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
Other Uses
<list> = [*<coll.> [, ...]] # Or: list(<collection>) [+ ...]
<tuple> = (*<coll.>, [...]) # Or: tuple(<collection>) [+ ...]
<set> = {*<coll.> [, ...]} # Or: set(<collection>) [| ...]
<dict> = {**<dict> [, ...]} # Or: dict(**<dict> [, ...])
head, *body, tail = <coll.> # Head or tail can be omitted.
Inline
Lambda
<func> = lambda: <return_value> # A single statement function.
<func> = lambda <arg_1>, <arg_2>: <return_value> # Also accepts default arguments.
Comprehensions
<list> = [i+1 for i in range(10)] # Or: [1, 2, ..., 10]
<iter> = (i for i in range(10) if i > 5) # Or: iter([6, 7, 8, 9])
<set> = {i+5 for i in range(10)} # Or: {5, 6, ..., 14}
<dict> = {i: i*2 for i in range(10)} # Or: {0: 0, 1: 2, ..., 9: 18}
>>> [l+r for l in 'abc' for r in 'abc']
['aa', 'ab', 'ac', ..., 'cc']
Map, Filter, Reduce
<iter> = map(lambda x: x + 1, range(10)) # Or: iter([1, 2, ..., 10])
<iter> = filter(lambda x: x > 5, range(10)) # Or: iter([6, 7, 8, 9])
<obj> = reduce(lambda out, x: out + x, range(10)) # Or: 45
- Reduce must be imported from the functools module.
Any, All
<bool> = any(<collection>) # Is `bool(el)` True for any element.
<bool> = all(<collection>) # Is True for all elements or empty.
Conditional Expression
<obj> = <exp> if <condition> else <exp> # Only one expression gets evaluated.
>>> [a if a else 'zero' for a in (0, 1, 2, 3)]
['zero', 1, 2, 3]
Named Tuple, Enum, Dataclass
from collections import namedtuple
Point = namedtuple('Point', 'x y') # Creates a tuple's subclass.
point = Point(0, 0) # Returns its instance.
from enum import Enum
Direction = Enum('Direction', 'n e s w') # Creates an enum.
direction = Direction.n # Returns its member.
from dataclasses import make_dataclass
Player = make_dataclass('Player', ['loc', 'dir']) # Creates a class.
player = Player(point, direction) # Returns its instance.
Imports
import <module> # Imports a built-in or '<module>.py'.
import <package> # Imports a built-in or '<package>/__init__.py'.
import <package>.<module> # Imports a built-in or '<package>/<module>.py'.
- Package is a collection of modules, but it can also define its own objects.
- On a filesystem this corresponds to a directory of Python files with an optional init script.
- Running
'import <package>'
does not automatically provide access to the package’s modules unless they are explicitly imported in its init script.
Closure
We have/get a closure in Python when:
- A nested function references a value of its enclosing function and then
- the enclosing function returns the nested function.
def get_multiplier(a):
def out(b):
return a * b
return out
>>> 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
from functools import partial
<function> = partial(<function> [, <arg_1>, <arg_2>, ...])
>>> import operator as op
>>> multiply_by_3 = partial(op.mul, 3)
>>> 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
>>> counter = get_counter()
>>> counter(), counter(), counter()
(1, 2, 3)
Decorator
- A decorator takes a function, adds some functionality and returns it.
- It can be any callable, but is usually implemented as a function that returns a closure.
@decorator_name
def function_that_gets_passed_to_decorator():
...
Debugger Example
Decorator that prints function’s name every time the function is called.
from functools import wraps
def debug(func):
@wraps(func)
def out(*args, **kwargs):
print(func.__name__)
return func(*args, **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'
.
LRU Cache
Decorator that caches function’s return values. All function’s arguments must be hashable.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n-2) + fib(n-1)
- Default size of the cache is 128 values. Passing
'maxsize=None'
makes it unbounded. - CPython interpreter limits recursion depth to 1000 by default. To increase it use
'sys.setrecursionlimit(<depth>)'
.
Parametrized Decorator
A decorator that accepts arguments and returns a normal decorator that accepts a function.
from functools import wraps
def debug(print_result=False):
def decorator(func):
@wraps(func)
def out(*args, **kwargs):
result = func(*args, **kwargs)
print(func.__name__, result if print_result else '')
return result
return out
return decorator
@debug(print_result=True)
def add(x, y):
return x + y
- Using only
'@debug'
to decorate the add() function would not work here, because debug would then receive the add() function as a ‘print_result’ argument. Decorators can however manually check if the argument they received is a function and act accordingly.
Class
class <name>:
def __init__(self, a):
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__
- Return value of repr() should be unambiguous and of str() readable.
- If only repr() is defined, it will also be used for str().
- Methods decorated with
'@staticmethod'
do not receive ‘self’ nor ‘cls’ as their first arg.
Str() use cases:
print(<el>)
f'{<el>}'
logging.warning(<el>)
csv.writer(<file>).writerow([<el>])
raise Exception(<el>)
Repr() use cases:
print/str/repr([<el>])
f'{<el>!r}'
Z = dataclasses.make_dataclass('Z', ['a']); print/str/repr(Z(<el>))
>>> <el>
Constructor Overloading
class <name>:
def __init__(self, a=None):
self.a = a
Inheritance
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Employee(Person):
def __init__(self, name, age, staff_num):
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 or an attribute:
>>> C.mro()
[<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
Property
Pythonic way of implementing getters and setters.
class Person:
@property
def name(self):
return ' '.join(self._name)
@name.setter
def name(self, value):
self._name = value.split()
>>> person = Person()
>>> person.name = '\t Guido van Rossum \n'
>>> person.name
'Guido van Rossum'
Dataclass
Decorator that automatically generates init(), repr() and eq() special methods.
from dataclasses import dataclass, field
@dataclass(order=False, frozen=False)
class <class_name>:
<attr_name_1>: <type>
<attr_name_2>: <type> = <default_value>
<attr_name_3>: list/dict/set = field(default_factory=list/dict/set)
- 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. Its ‘default_factory’ argument can be any callable. - For attributes of arbitrary type use
'typing.Any'
.
Inline:
from dataclasses import make_dataclass
<class> = make_dataclass('<class_name>', <coll_of_attribute_names>)
<class> = make_dataclass('<class_name>', <coll_of_tuples>)
<tuple> = ('<attr_name>', <type> [, <default_value>])
Rest of type annotations (CPython interpreter ignores them all):
def func(<arg_name>: <type> [= <obj>]) -> <type>: ...
<var_name>: typing.List/Set/Iterable/Sequence/Optional[<type>]
<var_name>: typing.Dict/Tuple/Union[<type>, ...]
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
Copy
from copy import copy, deepcopy
<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
- If eq() method is not overridden, it returns
'id(self) == id(other)'
, which is the same as'self is other'
. - That means all objects compare not equal by default.
- Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. False is returned if both return NotImplemented.
- Ne() automatically works on any object that has eq() defined.
class MyComparable:
def __init__(self, a):
self.a = a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
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:
def __init__(self, a):
self._a = a
@property
def a(self):
return self._a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
def __hash__(self):
return hash(self.a)
Sortable
- With ’total_ordering’ decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods and the rest will be automatically generated.
- Functions sorted() and min() only require lt() method, while max() only requires gt(). However, it is best to define them all so that confusion doesn’t arise in other contexts.
- When two lists, strings or dataclasses are compared, their values get compared in order until a pair of unequal values is found. The comparison of this two values is then returned. The shorter sequence is considered smaller in case of all values being equal.
from functools import total_ordering
@total_ordering
class MySortable:
def __init__(self, a):
self.a = a
def __eq__(self, other):
if isinstance(other, type(self)):
return self.a == other.a
return NotImplemented
def __lt__(self, other):
if isinstance(other, type(self)):
return self.a < other.a
return NotImplemented
Iterator
- Any object that has methods next() and iter() is an iterator.
- Next() should return next item or raise StopIteration.
- Iter() should return ‘self’.
class Counter:
def __init__(self):
self.i = 0
def __next__(self):
self.i += 1
return self.i
def __iter__(self):
return self
>>> counter = Counter()
>>> next(counter), next(counter), next(counter)
(1, 2, 3)
Python has many different iterator objects:
- 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
>>> counter = Counter()
>>> counter(), counter(), counter()
(1, 2, 3)
Context Manager
- Enter() should lock the resources and optionally return an object.
- Exit() should release the resources.
- Any exception that happens inside the with block is passed to the exit() method.
- If it wishes to suppress the exception it must return a true value.
class MyOpen:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename)
return self.file
def __exit__(self, exc_type, exception, traceback):
self.file.close()
>>> with open('test.txt', 'w') as file:
... file.write('Hello World!')
>>> with MyOpen('test.txt') as file:
... print(file.read())
Hello World!
Iterable Duck Types
Iterable
- Only required method is iter(). It should return an iterator of object’s items.
- Contains() automatically works on any object that has iter() defined.
class MyIterable:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
>>> obj = MyIterable([1, 2, 3])
>>> [el for el in obj]
[1, 2, 3]
>>> 1 in obj
True
Collection
- Only required methods are iter() and len(). Len() should return the number of items.
- This cheatsheet actually means
'<iterable>'
when it uses'<collection>'
. - I chose not to use the name ‘iterable’ because it sounds scarier and more vague than ‘collection’. The only drawback of this decision is that a reader could think a certain function doesn’t accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections.
class MyCollection:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
def __len__(self):
return len(self.a)
Sequence
- Only required methods are len() and getitem().
- Getitem() should return an item at the passed index or raise IndexError.
- Iter() and contains() automatically work on any object that has getitem() defined.
- Reversed() automatically works on any object that has len() and getitem() defined.
class MySequence:
def __init__(self, a):
self.a = a
def __iter__(self):
return iter(self.a)
def __contains__(self, el):
return el in self.a
def __len__(self):
return len(self.a)
def __getitem__(self, i):
return self.a[i]
def __reversed__(self):
return reversed(self.a)
Discrepancies between glossary definitions and abstract base classes:
- Glossary defines iterable as any object with iter() or getitem() and sequence as any object with getitem() and len(). It does not define collection.
- Passing ABC Iterable to isinstance() or issubclass() checks whether object/class has method iter(), while ABC Collection checks for iter(), contains() and len().
ABC Sequence
- It’s a richer interface than the basic sequence.
- Extending it generates iter(), contains(), reversed(), index() and count().
- Unlike
'abc.Iterable'
and'abc.Collection'
, it is not a duck type. That is why'issubclass(MySequence, abc.Sequence)'
would return False even if MySequence had all the methods defined. It however recognizes list, tuple, range, str, bytes, bytearray, memoryview and deque, because they are registered as Sequence’s virtual subclasses.
from collections import abc
class MyAbcSequence(abc.Sequence):
def __init__(self, a):
self.a = a
def __len__(self):
return len(self.a)
def __getitem__(self, i):
return self.a[i]
Table of required and automatically available special methods:
+------------+------------+------------+------------+--------------+
| | Iterable | Collection | Sequence | abc.Sequence |
+------------+------------+------------+------------+--------------+
| iter() | REQ | REQ | Yes | Yes |
| contains() | Yes | Yes | Yes | Yes |
| len() | | REQ | REQ | REQ |
| getitem() | | | REQ | REQ |
| reversed() | | | Yes | Yes |
| index() | | | | Yes |
| count() | | | | Yes |
+------------+------------+------------+------------+--------------+
- Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.
- Names of their required methods are stored in
'<abc>.__abstractmethods__'
.
Enum
from enum import Enum, auto
class <enum_name>(Enum):
<member_name_1> = <value_1>
<member_name_2> = <value_2_a>, <value_2_b>
<member_name_3> = auto()
- If there are no numeric values before auto(), it returns 1.
- Otherwise it returns an increment of the last numeric value.
<member> = <enum>.<member_name> # Returns a member.
<member> = <enum>['<member_name>'] # Returns a member or raises KeyError.
<member> = <enum>(<value>) # Returns a member or raises ValueError.
<str> = <member>.name # Returns member's name.
<obj> = <member>.value # Returns member's value.
list_of_members = list(<enum>)
member_names = [a.name for a in <enum>]
member_values = [a.value for a in <enum>]
random_member = random.choice(list(<enum>))
def get_next_member(member):
members = list(member.__class__)
index = (members.index(member) + 1) % len(members)
return members[index]
Inline
Cutlery = Enum('Cutlery', 'fork knife spoon')
Cutlery = Enum('Cutlery', ['fork', 'knife', 'spoon'])
Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3})
User-defined functions cannot be values, so they must be wrapped:
from functools import partial
LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
'OR': partial(lambda l, r: l or r)})
- Member names are in all caps because trying to access a member that is named after a reserved keyword raises SyntaxError.
Exceptions
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 (unless a signal is received).
Catching Exceptions
except <exception>: ...
except <exception> as <name>: ...
except (<exception>, [...]): ...
except (<exception>, [...]) as <name>: ...
- Also catches subclasses of the exception.
- Use
'traceback.print_exc()'
to print the error message to stderr. - Use
'print(<name>)'
to print just the cause of the exception (its arguments). - Use
'logging.exception(<message>)'
to log the exception.
Raising Exceptions
raise <exception>
raise <exception>()
raise <exception>(<el> [, ...])
Re-raising caught exception:
except <exception> as <name>:
...
raise
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
line = linecache.getline(filename, <name>.__traceback__.tb_lineno)
traceback = ''.join(traceback.format_tb(<name>.__traceback__))
error_msg = ''.join(traceback.format_exception(exc_type, <name>, <name>.__traceback__))
Built-in Exceptions
BaseException
+-- SystemExit # Raised by the sys.exit() function.
+-- KeyboardInterrupt # Raised when the user hits the interrupt key (ctrl-c).
+-- Exception # User-defined exceptions should be derived from this class.
+-- ArithmeticError # Base class for arithmetic errors.
| +-- ZeroDivisionError # Raised when dividing by zero.
+-- AssertionError # Raised by `assert <exp>` if expression returns false value.
+-- AttributeError # Raised when an attribute is missing.
+-- EOFError # Raised by input() when it hits end-of-file condition.
+-- LookupError # Raised when a look-up on a collection fails.
| +-- IndexError # Raised when a sequence index is out of range.
| +-- KeyError # Raised when a dictionary key or set element is missing.
+-- MemoryError # Out of memory. Could be too late to start deleting vars.
+-- NameError # Raised when an object is missing.
+-- OSError # Errors such as “file not found” or “disk full” (see Open).
| +-- FileNotFoundError # When a file or directory is requested but doesn't exist.
+-- RuntimeError # Raised by errors that don't fall into other categories.
| +-- RecursionError # Raised when the maximum recursion depth is exceeded.
+-- StopIteration # Raised by next() when run on an empty iterator.
+-- TypeError # Raised when an argument is of wrong type.
+-- ValueError # When an argument is of right type but inappropriate value.
+-- UnicodeError # Raised when encoding/decoding strings to/from bytes fails.
Collections and their exceptions:
+-----------+------------+------------+------------+
| | List | Set | Dict |
+-----------+------------+------------+------------+
| getitem() | IndexError | | KeyError |
| pop() | IndexError | KeyError | KeyError |
| remove() | ValueError | KeyError | |
| index() | ValueError | | |
+-----------+------------+------------+------------+
Useful built-in exceptions:
raise TypeError('Argument is of wrong type!')
raise ValueError('Argument is of right type but inappropriate value!')
raise RuntimeError('None of above!')
User-defined Exceptions
class MyError(Exception): pass
class MyInputError(MyError): pass