Backend Live Coding

Backend Live Coding

Explore backend live coding code snippets and tutorials

Backend Live Coding

Writing a timing context manager in Python

Write a context manager that measures execution time.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# ======================================================================
# Q: Write a context manager that measures execution time.
# ======================================================================

from contextlib import contextmanager

@contextmanager
def timer(label):
    start = time.perf_counter()
    try:
        yield
    finally:                          # runs even if an exception occurs
        logger.info('%s took %.1f ms', label, (time.perf_counter() - start) * 1000)

with timer('erp sync'):
    sync_stock()
Backend Live Coding

Writing a retry decorator with exponential backoff in Python

What the interviewer looks for: functools.wraps, retrying only on specific exceptions (not all of them), re-raising on the last attempt, and jitter so that not all clients hit at the …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# ======================================================================
# Q: Write a decorator that retries with exponential backoff.
#
# What the interviewer looks for: functools.wraps, retrying only on specific
# exceptions (not all of them), re-raising on the last attempt, and jitter so
# that not all clients hit at the same time.
# ======================================================================

import functools, random, time

def retry(exceptions, tries=3, base_delay=0.5):
    def decorator(func):
        @functools.wraps(func)            # keeps __name__, __doc__
        def wrapper(*args, **kwargs):
            for attempt in range(1, tries + 1):
                try:
                    return func(*args, **kwargs)
                except exceptions:
                    if attempt == tries:
                        raise
                    time.sleep(base_delay * 2 ** (attempt - 1) + random.uniform(0, 0.1))
        return wrapper
    return decorator

@retry((ConnectionError, TimeoutError), tries=5)
def fetch_erp_prices(): ...
Backend Live Coding

Python closures and late binding in lambdas

The lambdas close over the variable i, not its value at the time of creation (late binding).

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# ======================================================================
# Q: What is a closure? What does the following code print?
#
# The lambdas close over the variable i, not its value at the time of creation
# (late binding). When they are called, i is 2. Fix: lambda i=i: i, which binds
# the value as a default argument, or functools.partial.
# ======================================================================

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])   # [2, 2, 2]
Backend Live Coding

Python shallow copy vs deep copy

A shallow copy (list(x), x.copy(), copy.copy) creates a new outer object but shares the inner ones.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# ======================================================================
# Q: What is the difference between a shallow copy and a deep copy?
#
# A shallow copy (list(x), x.copy(), copy.copy) creates a new outer object but
# shares the inner ones. A deep copy (copy.deepcopy) recursively copies
# everything.
# ======================================================================

a = [[1, 2], [3]]
b = a.copy()          # shallow
b[0].append(99)
print(a)              # [[1, 2, 99], [3]]  <- a changed too
c = copy.deepcopy(a)  # independent copy