Questions 81–100 of 100 · 0 of 20 on this page marked learned
81.python-0081Easyfresher
Why does calling s.strip() leave s unchanged? Predict the output of this string-cleaning code.
String methods never change the original string; they return a new one. Calling s.upper() or s.replace() without assigning the result has no effect on s. Building a string by repeated += creates new strings each time, so join is preferred in loops.
Full answer
python
s = " Hello World "
s.strip()
s.upper()
print(repr(s))
t = s.strip().replace("World", "Python").upper()
print(repr(t), repr(s))
try:
t[0] = "J"
except TypeError as e:
print("TypeError:", e)
parts = ["a", "b", "c"]
print("-".join(parts), "J" + t[1:])
Output:
text
' Hello World '
'HELLO PYTHON' ' Hello World '
TypeError: 'str' object does not support item assignment
a-b-c JELLO PYTHON
The first two method calls compute new strings and throw them away, so s still has its spaces and original case. Chaining methods and assigning the result to t gives the cleaned value while s remains unchanged. Item assignment on a string raises a TypeError because strings cannot be modified in place; slicing and concatenation build a new string instead. join combines many parts in one step.
python
s = " Hello World "
s.strip()
s.upper()
print(repr(s))
t = s.strip().replace("World", "Python").upper()
print(repr(t), repr(s))
try:
t[0] = "J"
except TypeError as e:
print("TypeError:", e)
parts = ["a", "b", "c"]
print("-".join(parts), "J" + t[1:])
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
String methods return new strings
Assign the result to keep it
Item assignment raises TypeError
Chain methods for cleanup
join for combining many parts
Common mistakes
Calling s.strip() and expecting s to change
Concatenating in a loop with +=
Follow-ups
Why are strings immutable?
How does io.StringIO help when building text?
Tips
Point out the discarded results
82.python-0082Easyfresher
Why does this loop that removes items from a list while iterating skip elements, and how is it fixed?
Removing an item shifts the following items left, while the loop's internal index still moves forward, so the item after each removed one is skipped. Build a new list with a comprehension, iterate over a copy, or loop backwards by index.
Full answer
python
nums = [2, 4, 5, 6, 8]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print("buggy:", nums)
nums = [2, 4, 5, 6, 8]
print("fixed:", [n for n in nums if n % 2 != 0])
nums = [2, 4, 5, 6, 8]
for n in nums[:]:
if n % 2 == 0:
nums.remove(n)
print("copy:", nums)
Output:
text
buggy: [4, 5, 8]
fixed: [5]
copy: [5]
In the buggy loop, removing 2 moves 4 into position 0 while the loop moves on to position 1, which now holds 5, so 4 is never checked; the same happens with 6 and 8. The result still contains 4 and 8. The comprehension builds a new list and is the clearest fix; iterating over nums[:] also works because the copy does not change. Modifying a dict or set while iterating over it raises a RuntimeError instead of silently skipping.
python
nums = [2, 4, 5, 6, 8]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print("buggy:", nums)
nums = [2, 4, 5, 6, 8]
print("fixed:", [n for n in nums if n % 2 != 0])
nums = [2, 4, 5, 6, 8]
for n in nums[:]:
if n % 2 == 0:
nums.remove(n)
print("copy:", nums)
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Removal shifts later elements
The loop index still advances
Comprehensions build a new list safely
Iterate over a copy if mutating in place
Dicts and sets raise RuntimeError
Common mistakes
Mutating a list during iteration
Assuming the bug only affects consecutive matches
Follow-ups
How would you remove items in place efficiently?
What error does a dict give when changed during iteration?
Tips
Trace the indexes
83.python-0083Mediummid
Use pathlib to find the largest files under a directory and report their sizes.
pathlib.Path offers object-oriented paths: / joins parts, rglob walks recursively, stat() gives size, and suffix and stem split names. Combine rglob with is_file and heapq.nlargest to get the top files without sorting everything. Paths work across operating systems.
Full answer
python
import heapq, tempfile
from pathlib import Path
root = Path(tempfile.mkdtemp())
(root / "logs").mkdir()
(root / "logs" / "app.log").write_text("x" * 5000)
(root / "logs" / "old.log").write_text("x" * 12000)
(root / "data.csv").write_text("id,name 1,Asha")
(root / "notes.txt").write_text("x" * 800)
files = (p for p in root.rglob("*") if p.is_file())
top = heapq.nlargest(2, files, key=lambda p: p.stat().st_size)
for p in top:
print(p.relative_to(root).as_posix(), p.stat().st_size, p.suffix)
print(sorted(p.name for p in root.glob("*.csv")), (root / "logs").is_dir())
rglob('*') yields every path below the root, and the generator filters out directories. heapq.nlargest keeps only the top two while scanning, which matters for trees with millions of files. relative_to and as_posix produce readable, platform-neutral output. glob without the r searches one level. For huge trees, os.scandir is faster because it reuses directory entry information, but pathlib is clearer for most scripts.
python
import heapq, tempfile
from pathlib import Path
root = Path(tempfile.mkdtemp())
(root / "logs").mkdir()
(root / "logs" / "app.log").write_text("x" * 5000)
(root / "logs" / "old.log").write_text("x" * 12000)
(root / "data.csv").write_text("id,name 1,Asha")
(root / "notes.txt").write_text("x" * 800)
files = (p for p in root.rglob("*") if p.is_file())
top = heapq.nlargest(2, files, key=lambda p: p.stat().st_size)
for p in top:
print(p.relative_to(root).as_posix(), p.stat().st_size, p.suffix)
print(sorted(p.name for p in root.glob("*.csv")), (root / "logs").is_dir())
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Path objects join with /
rglob walks recursively
stat().st_size gives sizes
heapq.nlargest avoids a full sort
os.scandir for very large trees
Common mistakes
Building paths with string concatenation
Sorting every file to find the top few
Follow-ups
How would you skip hidden directories?
How would you handle permission errors during the walk?
Tips
Use nlargest
84.python-0084Mediummid
Validate and parse JSON input into typed objects, reporting all errors at once.
Parse with json.loads, then validate fields explicitly: required keys, types and ranges, collecting messages in a list instead of stopping at the first problem. Return a dataclass on success or raise a single error listing every issue. Libraries such as pydantic do this declaratively in real projects.
Full answer
python
import json
from dataclasses import dataclass
@dataclass(frozen=True)
class Signup:
email: str
age: int
plan: str
class ValidationError(Exception):
pass
def parse_signup(text):
try:
data = json.loads(text)
except json.JSONDecodeError as e:
raise ValidationError([f"invalid JSON at line {e.lineno} column {e.colno}"]) from None
errors = []
email = data.get("email")
if not isinstance(email, str) or "@" not in email:
errors.append("email must contain @")
age = data.get("age")
if not isinstance(age, int) or isinstance(age, bool) or not 13 <= age <= 120:
errors.append("age must be an integer from 13 to 120")
if data.get("plan") not in {"free", "pro"}:
errors.append("plan must be free or pro")
if errors:
raise ValidationError(errors)
return Signup(email, age, data["plan"])
print(parse_signup('{"email": "a@x.in", "age": 21, "plan": "pro"}'))
for bad in ['{"email": "ax.in", "age": true, "plan": "gold"}', '{"email": ']:
try:
parse_signup(bad)
except ValidationError as e:
print(e.args[0])
Output:
text
Signup(email='a@x.in', age=21, plan='pro')
['email must contain @', 'age must be an integer from 13 to 120', 'plan must be free or pro']
['invalid JSON at line 1 column 11']
The valid input becomes a frozen dataclass. The second input has three problems, all reported together, which is friendlier for form users than fixing them one at a time. true is rejected as an age because bool is a subclass of int in Python, a subtle case worth checking. Malformed JSON produces a position-specific message, and from None hides the internal traceback chain.
python
import json
from dataclasses import dataclass
@dataclass(frozen=True)
class Signup:
email: str
age: int
plan: str
class ValidationError(Exception):
pass
def parse_signup(text):
try:
data = json.loads(text)
except json.JSONDecodeError as e:
raise ValidationError([f"invalid JSON at line {e.lineno} column {e.colno}"]) from None
errors = []
email = data.get("email")
if not isinstance(email, str) or "@" not in email:
errors.append("email must contain @")
age = data.get("age")
if not isinstance(age, int) or isinstance(age, bool) or not 13 <= age <= 120:
errors.append("age must be an integer from 13 to 120")
if data.get("plan") not in {"free", "pro"}:
errors.append("plan must be free or pro")
if errors:
raise ValidationError(errors)
return Signup(email, age, data["plan"])
print(parse_signup('{"email": "a@x.in", "age": 21, "plan": "pro"}'))
for bad in ['{"email": "ax.in", "age": true, "plan": "gold"}', '{"email": ']:
try:
parse_signup(bad)
except ValidationError as e:
print(e.args[0])
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Parse, then validate explicitly
Collect all errors
bool is a subclass of int
Return typed objects
pydantic automates this
Common mistakes
Stopping at the first error
Accepting True as an integer
Follow-ups
How would pydantic express this model?
How should validation errors map to HTTP responses?
Tips
Catch the bool case
85.python-0085Mediummid
Make custom objects sortable and comparable with total_ordering and sort keys.
Define __eq__ and __lt__, then functools.total_ordering fills in <=, > and >=. Often a sort key is simpler: sorted(items, key=attrgetter('a', 'b')) needs no methods at all. Return NotImplemented for unsupported types so Python can try the other operand.
Full answer
python
from functools import total_ordering
from operator import attrgetter
@total_ordering
class Version:
def __init__(self, text):
self.parts = tuple(int(p) for p in text.split("."))
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.parts == other.parts
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.parts < other.parts
def __hash__(self):
return hash(self.parts)
def __repr__(self):
return ".".join(map(str, self.parts))
vs = [Version(v) for v in ["1.10.0", "1.2.3", "1.9", "2.0"]]
print(sorted(vs), max(vs), Version("1.9") >= Version("1.10.0"))
print(sorted(["1.10.0", "1.2.3", "1.9"]))
try:
Version("1.0") < "1.0"
except TypeError as e:
print("TypeError:", e)
Output:
text
[1.2.3, 1.9, 1.10.0, 2.0] 2.0 False
['1.10.0', '1.2.3', '1.9']
TypeError: '<' not supported between instances of 'Version' and 'str'
Comparing tuples of integers sorts versions numerically, so 1.10.0 comes after 1.9, while plain string sorting puts '1.10.0' first. total_ordering derives >= from __lt__ and __eq__. Returning NotImplemented for a string makes Python raise a clear TypeError instead of silently returning False. Defining __eq__ removes the default hash, so __hash__ is restored from the same tuple to keep versions usable in sets.
python
from functools import total_ordering
from operator import attrgetter
@total_ordering
class Version:
def __init__(self, text):
self.parts = tuple(int(p) for p in text.split("."))
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.parts == other.parts
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.parts < other.parts
def __hash__(self):
return hash(self.parts)
def __repr__(self):
return ".".join(map(str, self.parts))
vs = [Version(v) for v in ["1.10.0", "1.2.3", "1.9", "2.0"]]
print(sorted(vs), max(vs), Version("1.9") >= Version("1.10.0"))
print(sorted(["1.10.0", "1.2.3", "1.9"]))
try:
Version("1.0") < "1.0"
except TypeError as e:
print("TypeError:", e)
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Define __eq__ and __lt__
total_ordering fills in the rest
Return NotImplemented for other types
Tuples compare element by element
Sort keys avoid methods altogether
Common mistakes
Sorting version strings lexically
Forgetting __hash__ after defining __eq__
Follow-ups
How would dataclass(order=True) do this?
How do you sort descending by one key and ascending by another?
Tips
Compare with string sorting
86.python-0086Mediummid
Implement binary search by hand and with the bisect module.
Binary search halves the search range each step, finding a value in a sorted list in O(log n). The hand-written version must handle the boundaries carefully. bisect.bisect_left gives the insertion point, which also answers 'how many items are smaller' and supports keeping a list sorted with insort.
Full answer
python
import bisect
def binary_search(items, target):
lo, hi = 0, len(items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if items[mid] == target:
return mid
if items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
prices = [99, 149, 199, 249, 499, 999]
print(binary_search(prices, 249), binary_search(prices, 300))
i = bisect.bisect_left(prices, 300)
print(i, prices[i], i < len(prices) and prices[i] == 300)
grades = [(60, "D"), (70, "C"), (80, "B"), (90, "A")]
cut = [g[0] for g in grades]
print([("F" if (j := bisect.bisect_right(cut, s)) == 0 else grades[j - 1][1]) for s in [55, 70, 89, 95]])
bisect.insort(prices, 300)
print(prices)
249 is found at index 3, and 300 is absent, so the hand-written search returns -1. bisect_left reports that 300 would go at index 4, before 499, which is a membership test when combined with a comparison. The grade lookup uses bisect_right on the cut-offs, so 70 counts as a C and anything below 60 is an F. insort inserts while keeping the list sorted, though each insert is O(n) because elements shift. Python 3.10 added a key parameter to bisect functions.
python
import bisect
def binary_search(items, target):
lo, hi = 0, len(items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if items[mid] == target:
return mid
if items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
prices = [99, 149, 199, 249, 499, 999]
print(binary_search(prices, 249), binary_search(prices, 300))
i = bisect.bisect_left(prices, 300)
print(i, prices[i], i < len(prices) and prices[i] == 300)
grades = [(60, "D"), (70, "C"), (80, "B"), (90, "A")]
cut = [g[0] for g in grades]
print([("F" if (j := bisect.bisect_right(cut, s)) == 0 else grades[j - 1][1]) for s in [55, 70, 89, 95]])
bisect.insort(prices, 300)
print(prices)
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Binary search is O(log n) on sorted data
Careful lo/hi boundaries
bisect_left gives insertion points
bisect_right for range lookups
insort keeps lists sorted
Common mistakes
Using binary search on unsorted data
Off-by-one errors in the loop condition
Follow-ups
How would you find the first index where a condition becomes true?
Why is insort O(n)?
Tips
Show a lookup table
87.python-0087Mediummid
How do you use subprocess safely to run an external command and capture its output?
Use subprocess.run with a list of arguments, capture_output=True, text=True, a timeout and check=True. Passing a list avoids the shell, so arguments containing spaces or characters such as ; are not interpreted. Avoid shell=True with any user input, and handle CalledProcessError and TimeoutExpired.
The argument report; rm -rf / reaches the child as one harmless string because no shell parses it; with shell=True and string formatting, the shell would treat ; as a command separator. check=True turns a non-zero exit into CalledProcessError, and timeout kills a hung child and raises TimeoutExpired. text=True decodes output as text. Using sys.executable keeps the example portable.
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Pass arguments as a list
Avoid shell=True with input
check=True raises on failure
Always set a timeout
capture_output with text=True
Common mistakes
Formatting user input into shell strings
No timeout on external commands
Follow-ups
How do you stream output from a long-running process?
When is shell=True acceptable?
Tips
Show the injection attempt
88.python-0088Mediummid
Write a generator pipeline that processes a large log file lazily.
Chain generator functions or expressions, each consuming the previous one: read lines, parse them, filter, then aggregate. Only one line is in memory at a time, so the pipeline handles files larger than RAM, and each stage stays small and testable.
Full answer
python
from collections import Counter
LOG = [
"2026-12-01 10:00:01 INFO /home 200 12",
"2026-12-01 10:00:02 ERROR /pay 500 340",
"bad line",
"2026-12-01 10:00:03 INFO /pay 200 95",
"2026-12-01 10:00:04 WARN /home 404 8",
]
def parse(lines):
for line in lines:
parts = line.split()
if len(parts) != 6:
continue
date, time_, level, path, status, ms = parts
yield {"level": level, "path": path, "status": int(status), "ms": int(ms)}
def slow(records, threshold):
return (r for r in records if r["ms"] >= threshold)
records = parse(iter(LOG))
print(Counter(r["status"] for r in records))
print([r["path"] for r in slow(parse(LOG), 90)])
parse skips malformed lines and yields dictionaries one at a time, and slow filters lazily. With a real file, parse(open(path, encoding='utf-8')) would stream lines from disk the same way. A generator can be consumed only once, which is why the second query creates a fresh parse(LOG) pipeline. The status counter shows two 200s, one 500 and one 404; the slow requests are /pay at 340 ms and /pay at 95 ms.
python
from collections import Counter
LOG = [
"2026-12-01 10:00:01 INFO /home 200 12",
"2026-12-01 10:00:02 ERROR /pay 500 340",
"bad line",
"2026-12-01 10:00:03 INFO /pay 200 95",
"2026-12-01 10:00:04 WARN /home 404 8",
]
def parse(lines):
for line in lines:
parts = line.split()
if len(parts) != 6:
continue
date, time_, level, path, status, ms = parts
yield {"level": level, "path": path, "status": int(status), "ms": int(ms)}
def slow(records, threshold):
return (r for r in records if r["ms"] >= threshold)
records = parse(iter(LOG))
print(Counter(r["status"] for r in records))
print([r["path"] for r in slow(parse(LOG), 90)])
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Generators process one item at a time
Stages compose like Unix pipes
Skip bad lines rather than crash
Generators are single-use
Works on files larger than memory
Common mistakes
Reading the whole file with readlines()
Reusing an exhausted generator
Follow-ups
How would you count malformed lines?
How would you parallelise this pipeline?
Tips
Mention single use
89.python-0089Mediummid
Use heapq to get the top k items and to merge already-sorted streams.
heapq implements a min-heap on a plain list: heappush and heappop are O(log n). nlargest and nsmallest return top k items in O(n log k), better than sorting when k is small. heapq.merge lazily merges sorted inputs, and a heap of (priority, counter, item) tuples gives a stable priority queue.
nlargest returns the three highest scores without sorting all five. heapq.merge consumes the inputs lazily, so it can merge sorted files that do not fit in memory. In the priority queue, the counter breaks ties: 'email' and 'report' share priority 2 and come out in insertion order, and the task strings are never compared. heapq is a min-heap; for a max-heap, push negated priorities.
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
heapq is a min-heap on a list
push and pop are O(log n)
nlargest for top k
merge for sorted streams
Counter tie-breaker for stable priorities
Common mistakes
Sorting everything to take the top 3
Heap entries that compare unorderable items on ties
Follow-ups
How would you find the median of a stream?
When would you use queue.PriorityQueue instead?
Tips
Mention the tie-breaker
90.python-0090Hardsenior
Write a generic, type-safe repository class with TypeVar, Generic and Protocol, and explain what the type checker gains.
A TypeVar bound to a Protocol lets one class work with any entity type that has the required attributes, while the type checker tracks the concrete type through get and add. Python 3.12 syntax writes this as class Repo[T: HasId]. Annotations are not enforced at runtime, so a checker such as mypy or pyright provides the benefit.
Full answer
python
from dataclasses import dataclass
from typing import Generic, Protocol, TypeVar, get_type_hints
class HasId(Protocol):
id: int
T = TypeVar("T", bound=HasId)
class Repo(Generic[T]):
def __init__(self) -> None:
self._items: dict[int, T] = {}
def add(self, item: T) -> T:
self._items[item.id] = item
return item
def get(self, id: int) -> T | None:
return self._items.get(id)
@dataclass
class User:
id: int
email: str
class Repo312[E: HasId]:
def first(self, items: list[E]) -> E:
return items[0]
users: Repo[User] = Repo()
users.add(User(1, "a@x.in"))
print(users.get(1), users.get(2))
print(get_type_hints(Repo.get))
print(Repo312.__type_params__)
try:
users.add("not a user")
except AttributeError as e:
print("AttributeError:", e)
Output:
text
User(id=1, email='a@x.in') None
{'id': <class 'int'>, 'return': typing.Optional[~T]}
(E,)
AttributeError: 'str' object has no attribute 'id'
The repository stores and returns User objects, and a type checker infers that users.get(1) is User | None, so attribute typos on the result are caught before running. User satisfies HasId structurally, without inheriting from it. get_type_hints shows the annotations are available for introspection, and the 3.12 syntax stores its parameters in __type_params__. The last call passes a string, which a checker rejects at analysis time; at runtime nothing checks the annotation, and the call fails only when add reaches item.id, raising AttributeError. In larger code the bad value might travel far before failing, which is the main argument for running a checker in CI.
python
from dataclasses import dataclass
from typing import Generic, Protocol, TypeVar, get_type_hints
class HasId(Protocol):
id: int
T = TypeVar("T", bound=HasId)
class Repo(Generic[T]):
def __init__(self) -> None:
self._items: dict[int, T] = {}
def add(self, item: T) -> T:
self._items[item.id] = item
return item
def get(self, id: int) -> T | None:
return self._items.get(id)
@dataclass
class User:
id: int
email: str
class Repo312[E: HasId]:
def first(self, items: list[E]) -> E:
return items[0]
users: Repo[User] = Repo()
users.add(User(1, "a@x.in"))
print(users.get(1), users.get(2))
print(get_type_hints(Repo.get))
print(Repo312.__type_params__)
try:
users.add("not a user")
except AttributeError as e:
print("AttributeError:", e)
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
TypeVar with a bound restricts generic types
Protocols are structural interfaces
3.12 adds class C[T] syntax
Checkers enforce, the runtime does not
Generics carry concrete types through APIs
Common mistakes
Expecting annotations to validate at runtime
Using Any where a TypeVar fits
Follow-ups
When would you use ParamSpec?
How do you add type checking to CI gradually?
Tips
Separate checker from runtime
91.python-0091Hardsenior
Use weak references to build a cache that does not keep objects alive.
A weak reference points to an object without increasing its reference count, so the object can be freed when nothing else uses it. weakref.WeakValueDictionary removes entries automatically when values die, which suits caches of large objects owned elsewhere. Not every type supports weak references; int, str and tuple do not.
Full answer
python
import gc, weakref
class Image:
def __init__(self, name): self.name = name
def __repr__(self): return f"Image({self.name})"
cache = weakref.WeakValueDictionary()
logo = Image("logo")
banner = Image("banner")
cache["logo"], cache["banner"] = logo, banner
print(sorted(cache.keys()))
del banner
gc.collect()
print(sorted(cache.keys()), cache.get("banner"))
r = weakref.ref(logo, lambda ref: print("logo finalised"))
print(r() is logo)
del logo
gc.collect()
print(r())
try:
weakref.ref(42)
except TypeError as e:
print("TypeError:", e)
Output:
text
['banner', 'logo']
['logo'] None
True
logo finalised
None
TypeError: cannot create weak reference to 'int' object
Deleting the last strong reference to the banner frees it, and its cache entry disappears without any cleanup code. The weakref.ref callback runs when the logo is freed, and calling the dead reference returns None. CPython frees objects as soon as their reference count drops to zero; gc.collect() is called only to make the example reliable if a cycle were involved. Weak references are also used for observer lists, so listeners do not keep subscribers alive, and weakref.finalize is the preferred cleanup hook.
python
import gc, weakref
class Image:
def __init__(self, name): self.name = name
def __repr__(self): return f"Image({self.name})"
cache = weakref.WeakValueDictionary()
logo = Image("logo")
banner = Image("banner")
cache["logo"], cache["banner"] = logo, banner
print(sorted(cache.keys()))
del banner
gc.collect()
print(sorted(cache.keys()), cache.get("banner"))
r = weakref.ref(logo, lambda ref: print("logo finalised"))
print(r() is logo)
del logo
gc.collect()
print(r())
try:
weakref.ref(42)
except TypeError as e:
print("TypeError:", e)
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Weak references do not keep objects alive
WeakValueDictionary drops dead values
Callbacks run on finalisation
Built-in immutables do not support weakrefs
Useful for caches and observers
Common mistakes
Caches with strong references that leak memory
Relying on __del__ for cleanup
Follow-ups
How does weakref.finalize differ from __del__?
Why can't ints be weakly referenced?
Tips
Show automatic removal
92.python-0092Hardsenior
An asyncio service stalls under load because a handler calls a blocking function. Detect it and fix it.
A blocking call such as time.sleep, requests.get or a heavy computation inside a coroutine stops the whole event loop, so every other request waits. Detect it with asyncio debug mode, which logs callbacks slower than slow_callback_duration, or with latency spikes across unrelated endpoints. Fix it by using an async library, or by moving the call off the loop with asyncio.to_thread or a process pool.
Full answer
python
import asyncio, time
async def heartbeat(ticks):
for _ in range(5):
ticks.append(time.perf_counter())
await asyncio.sleep(0.02)
async def blocking_handler():
time.sleep(0.1)
async def fixed_handler():
await asyncio.to_thread(time.sleep, 0.1)
async def measure(handler):
ticks = []
await asyncio.gather(heartbeat(ticks), handler())
gaps = [b - a for a, b in zip(ticks, ticks[1:])]
return max(gaps)
async def main():
print("blocking: heartbeat gap over 0.08s:", await measure(blocking_handler) > 0.08)
print("to_thread: heartbeat gap under 0.06s:", await measure(fixed_handler) < 0.06)
asyncio.run(main())
Output:
text
blocking: heartbeat gap over 0.08s: True
to_thread: heartbeat gap under 0.06s: True
The heartbeat task should tick every 20 ms. With the blocking handler, time.sleep(0.1) freezes the loop and the heartbeat misses its slots, producing a long gap. With asyncio.to_thread, the sleep runs in a worker thread and the heartbeat continues on time. The checks use wide margins, so the output is stable across runs. In production, asyncio.run(main(), debug=True) or PYTHONASYNCIODEBUG=1 logs any step slower than 100 ms by default, naming the slow coroutine. CPU-heavy work should go to a ProcessPoolExecutor via loop.run_in_executor, because threads do not help pure-Python CPU work.
python
import asyncio, time
async def heartbeat(ticks):
for _ in range(5):
ticks.append(time.perf_counter())
await asyncio.sleep(0.02)
async def blocking_handler():
time.sleep(0.1)
async def fixed_handler():
await asyncio.to_thread(time.sleep, 0.1)
async def measure(handler):
ticks = []
await asyncio.gather(heartbeat(ticks), handler())
gaps = [b - a for a, b in zip(ticks, ticks[1:])]
return max(gaps)
async def main():
print("blocking: heartbeat gap over 0.08s:", await measure(blocking_handler) > 0.08)
print("to_thread: heartbeat gap under 0.06s:", await measure(fixed_handler) < 0.06)
asyncio.run(main())
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Blocking calls freeze the event loop
Debug mode logs slow callbacks
to_thread for blocking I/O
Process pools for CPU work
Prefer native async libraries
Common mistakes
Calling requests or time.sleep inside async def
Running CPU work in threads expecting speed-ups
Follow-ups
How would you find which library call blocks?
What does the default executor size depend on?
Tips
Show the heartbeat gap
93.python-0093Hardsenior
Build a thread-safe producer and consumer pipeline with queue.Queue and clean shutdown.
queue.Queue is thread-safe and handles locking internally: producers put items, consumers get them, and task_done with join tracks completion. A bounded queue applies back-pressure so producers cannot outrun consumers. Shut down by sending one sentinel per consumer, or with Queue.shutdown in Python 3.13.
Full answer
python
import queue, threading
def producer(q, n):
for i in range(n):
q.put(i)
def consumer(q, results, lock):
while True:
try:
item = q.get()
except queue.ShutDown:
return
with lock:
results.append(item * item)
q.task_done()
q = queue.Queue(maxsize=5)
results, lock = [], threading.Lock()
workers = [threading.Thread(target=consumer, args=(q, results, lock)) for _ in range(3)]
for w in workers: w.start()
producer(q, 20)
q.join()
q.shutdown()
for w in workers: w.join()
print(len(results), sum(results), sorted(results)[:5])
print(all(not w.is_alive() for w in workers))
Output:
text
20 2470 [0, 1, 4, 9, 16]
True
Three consumers process twenty items; maxsize=5 blocks the producer whenever the queue is full. q.join() waits until every item has been marked done, then q.shutdown() (new in 3.13) makes blocked get calls raise queue.ShutDown, so the consumers exit and the threads can be joined. On older versions, put one sentinel such as None per consumer. The results list is sorted before printing because consumers finish in an unpredictable order; the sum, 2470, is deterministic. The lock around append is technically unnecessary for a single list append in CPython, but it makes the intent explicit and stays correct with free-threaded builds.
python
import queue, threading
def producer(q, n):
for i in range(n):
q.put(i)
def consumer(q, results, lock):
while True:
try:
item = q.get()
except queue.ShutDown:
return
with lock:
results.append(item * item)
q.task_done()
q = queue.Queue(maxsize=5)
results, lock = [], threading.Lock()
workers = [threading.Thread(target=consumer, args=(q, results, lock)) for _ in range(3)]
for w in workers: w.start()
producer(q, 20)
q.join()
q.shutdown()
for w in workers: w.join()
print(len(results), sum(results), sorted(results)[:5])
print(all(not w.is_alive() for w in workers))
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
queue.Queue handles locking
Bounded queues give back-pressure
task_done and join track completion
Queue.shutdown in 3.13, sentinels before
Results arrive in nondeterministic order
Common mistakes
Unbounded queues that grow without limit
Consumers that never exit, so join hangs
Follow-ups
How would you propagate an exception from a consumer?
When would multiprocessing.Queue be needed?
Tips
Explain shutdown
94.python-0094Hardsenior
Implement a lazy-loading proxy with __getattr__, and explain how it differs from __getattribute__.
__getattr__ is called only when normal lookup fails, which makes it safe for proxies and fallbacks. __getattribute__ intercepts every attribute access, including internal ones, so overriding it risks infinite recursion unless it calls object.__getattribute__. A lazy proxy creates the expensive object on first use and forwards attributes to it.
Full answer
python
class LazyClient:
def __init__(self, factory):
self._factory = factory
self._target = None
def __getattr__(self, name):
if self._target is None:
print("connecting...")
self._target = self._factory()
return getattr(self._target, name)
class DbClient:
def query(self, sql):
return f"rows for {sql!r}"
timeout = 30
client = LazyClient(DbClient)
print("created proxy")
print(client.query("SELECT 1"))
print(client.timeout, client._target is not None)
try:
client.missing
except AttributeError as e:
print("AttributeError:", e)
def __getattr__(name):
if name == "LEGACY":
return "deprecated value"
raise AttributeError(name)
print(__getattr__("LEGACY"))
Output:
text
created proxy
connecting...
rows for 'SELECT 1'
30 True
AttributeError: 'DbClient' object has no attribute 'missing'
deprecated value
Creating the proxy does no work; the first attribute that is not found on the proxy itself triggers the connection, and later accesses reuse the target. _factory and _target are found by normal lookup, so they never reach __getattr__, which is what prevents recursion. Missing attributes on the target raise AttributeError naming the target class. Modules can define a module-level __getattr__ (PEP 562) for lazy imports or deprecation warnings; the last lines show the function directly. A proxy does not forward special methods such as __len__, because Python looks those up on the type.
python
class LazyClient:
def __init__(self, factory):
self._factory = factory
self._target = None
def __getattr__(self, name):
if self._target is None:
print("connecting...")
self._target = self._factory()
return getattr(self._target, name)
class DbClient:
def query(self, sql):
return f"rows for {sql!r}"
timeout = 30
client = LazyClient(DbClient)
print("created proxy")
print(client.query("SELECT 1"))
print(client.timeout, client._target is not None)
try:
client.missing
except AttributeError as e:
print("AttributeError:", e)
def __getattr__(name):
if name == "LEGACY":
return "deprecated value"
raise AttributeError(name)
print(__getattr__("LEGACY"))
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
__getattr__ runs only on failed lookups
__getattribute__ runs on every access
Lazy proxies defer expensive setup
Special methods bypass __getattr__
Modules support __getattr__
Common mistakes
Overriding __getattribute__ and recursing
Expecting len() to work through a simple proxy
Follow-ups
How would you forward special methods?
How does PEP 562 help with lazy imports?
Tips
Explain recursion safety
95.python-0095Hardsenior
Design a token-bucket rate limiter for an API, in process first and then shared across servers.
A token bucket holds up to capacity tokens and refills at a fixed rate; each request takes a token or is rejected with HTTP 429 and a Retry-After header. It allows short bursts while enforcing an average rate. With several servers, keep the bucket state in a shared store such as Redis and update it atomically with a Lua script.
Full answer
python
class TokenBucket:
def __init__(self, rate, capacity, clock):
self.rate, self.capacity, self.clock = rate, capacity, clock
self.tokens, self.updated = capacity, clock()
def allow(self):
now = self.clock()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
def retry_after(self):
return max(0.0, (1 - self.tokens) / self.rate)
t = [0.0]
bucket = TokenBucket(rate=2, capacity=3, clock=lambda: t[0])
print([bucket.allow() for _ in range(4)], bucket.retry_after())
t[0] = 1.0
print([bucket.allow() for _ in range(3)])
Output:
text
[True, True, True, False] 0.5
[True, True, False]
With a capacity of 3, the first three requests at time 0 pass as a burst and the fourth is rejected; the limiter reports that one token arrives in 0.5 seconds at 2 tokens per second. After one second, two tokens have been added, so two more requests pass and the third fails. The injected clock makes the behaviour testable.
Across servers, design points are: key buckets per user or API key; store tokens and timestamp in Redis and update them in one atomic Lua script to avoid races; set expiry on idle keys; return 429 with Retry-After and rate-limit headers; decide whether to fail open or closed if Redis is down; and consider a sliding-window counter when exact per-minute limits matter more than burst handling.
python
class TokenBucket:
def __init__(self, rate, capacity, clock):
self.rate, self.capacity, self.clock = rate, capacity, clock
self.tokens, self.updated = capacity, clock()
def allow(self):
now = self.clock()
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= 1:
self.tokens -= 1
return True
return False
def retry_after(self):
return max(0.0, (1 - self.tokens) / self.rate)
t = [0.0]
bucket = TokenBucket(rate=2, capacity=3, clock=lambda: t[0])
print([bucket.allow() for _ in range(4)], bucket.retry_after())
t[0] = 1.0
print([bucket.allow() for _ in range(3)])
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Token buckets allow bursts within an average rate
Refill lazily from elapsed time
Return 429 with Retry-After
Atomic updates in a shared store across servers
Decide fail-open versus fail-closed
Common mistakes
Per-process limits behind a load balancer
Read-modify-write races in Redis
Follow-ups
How does a sliding-window log differ?
How would you rate limit per tenant and globally?
Tips
Use an injected clock
96.python-0096Hardsenior
Raise and handle multiple errors with ExceptionGroup, add_note and exception chaining.
raise NewError(...) from err records the original cause, so tracebacks show both. add_note (Python 3.11+) attaches context such as which record failed. ExceptionGroup bundles several independent failures, for example from validating many rows or from concurrent tasks, and except* handles each type separately.
Full answer
python
class ImportFailed(Exception):
pass
def parse_row(i, row):
try:
return int(row["qty"])
except (KeyError, ValueError) as e:
e.add_note(f"row {i}: {row}")
raise
def import_rows(rows):
errors, good = [], []
for i, row in enumerate(rows):
try:
good.append(parse_row(i, row))
except (KeyError, ValueError) as e:
errors.append(e)
if errors:
raise ExceptionGroup("import failed", errors)
return good
rows = [{"qty": "3"}, {"qty": "x"}, {}, {"qty": "5"}]
try:
import_rows(rows)
except* ValueError as eg:
print("value errors:", [n for e in eg.exceptions for n in e.__notes__])
except* KeyError as eg:
print("missing keys:", [n for e in eg.exceptions for n in e.__notes__])
try:
try:
{}["config"]
except KeyError as e:
raise ImportFailed("config missing") from e
except ImportFailed as e:
print(type(e.__cause__).__name__, e.__cause__, e.__suppress_context__)
Each failing row gets a note naming the row, and the importer collects all failures instead of stopping at the first. The two except* clauses each receive a sub-group of the matching type, so both run. raise ... from e sets __cause__ and marks the implicit context as suppressed, and a traceback would print 'The above exception was the direct cause of the following exception'. raise ... from None hides the cause when it is noise for the caller.
python
class ImportFailed(Exception):
pass
def parse_row(i, row):
try:
return int(row["qty"])
except (KeyError, ValueError) as e:
e.add_note(f"row {i}: {row}")
raise
def import_rows(rows):
errors, good = [], []
for i, row in enumerate(rows):
try:
good.append(parse_row(i, row))
except (KeyError, ValueError) as e:
errors.append(e)
if errors:
raise ExceptionGroup("import failed", errors)
return good
rows = [{"qty": "3"}, {"qty": "x"}, {}, {"qty": "5"}]
try:
import_rows(rows)
except* ValueError as eg:
print("value errors:", [n for e in eg.exceptions for n in e.__notes__])
except* KeyError as eg:
print("missing keys:", [n for e in eg.exceptions for n in e.__notes__])
try:
try:
{}["config"]
except KeyError as e:
raise ImportFailed("config missing") from e
except ImportFailed as e:
print(type(e.__cause__).__name__, e.__cause__, e.__suppress_context__)
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
from err records the cause
add_note attaches context
ExceptionGroup bundles failures
except* handles each type
from None hides irrelevant causes
Common mistakes
Losing the original exception when re-raising
Stopping a batch import at the first bad row
Follow-ups
How do ExceptionGroups interact with TaskGroup?
When should a library wrap exceptions?
Tips
Show both except* branches
97.python-0097Hardsenior
What does this class-body code print, and why can a comprehension in a class body not see class variables?
A class body is a scope, but functions and most comprehensions defined inside it do not see its names, because class scope is not an enclosing scope for nested functions. The outermost iterable of a comprehension is evaluated in the class body, while the rest runs in the comprehension's own scope, so names used in conditions or expressions raise NameError.
Full answer
python
class Config:
base = 10
names = ["a", "b"]
copied = [n.upper() for n in names]
try:
scaled = [x * base for x in range(3)]
except NameError as e:
error = str(e)
def method(self):
try:
return base
except NameError:
return Config.base
print(Config.copied)
print(Config.error)
print(Config().method())
Output:
text
['A', 'B']
name 'base' is not defined
10
copied works because names, the outermost iterable, is evaluated in the class body. scaled fails because base is used inside the comprehension's own scope, which skips the class scope and finds no global named base. The method has the same limitation, so methods use self.base or Config.base. PEP 709 inlined comprehensions in Python 3.12 for speed but kept this scoping rule in class bodies. The usual fix is to compute such values after the class or in a classmethod.
python
class Config:
base = 10
names = ["a", "b"]
copied = [n.upper() for n in names]
try:
scaled = [x * base for x in range(3)]
except NameError as e:
error = str(e)
def method(self):
try:
return base
except NameError:
return Config.base
print(Config.copied)
print(Config.error)
print(Config().method())
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Class scope is not visible to nested functions
Comprehension outermost iterable is evaluated outside
Other comprehension parts run in their own scope
Methods use self or the class name
PEP 709 kept the rule
Common mistakes
Using class variables directly inside comprehensions in the class body
Referring to class attributes in methods without self
Follow-ups
Why was class scope designed this way?
How do dataclass field defaults avoid this?
Tips
Separate the outermost iterable
98.python-0098Hardsenior
A team must upgrade a large service from Python 3.8 to 3.13. Plan the migration.
Upgrade in steps: get the test suite green with warnings enabled on the current version, upgrade dependencies to releases that support 3.13, then run CI on both versions until the new one is clean. Removed modules (the 'dead batteries' such as cgi, imghdr and telnetlib went in 3.13) and deprecations such as datetime.utcnow need code changes. Roll out gradually with monitoring.
Full answer
python
import warnings, datetime, sys, importlib.util
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
datetime.datetime.utcnow()
print(sys.version_info[:2], [w.category.__name__ for w in caught])
print(caught[0].message.args[0].split(".")[0])
print({m: importlib.util.find_spec(m) is not None for m in ["cgi", "imghdr", "telnetlib", "tomllib"]})
print(datetime.datetime.now(datetime.UTC).tzinfo)
On 3.13, datetime.utcnow() emits a DeprecationWarning because it returns a naive datetime; the replacement is datetime.now(datetime.UTC), which is timezone-aware. The module check shows that cgi, imghdr and telnetlib no longer exist, while tomllib (added in 3.11) does. A migration plan built on this:
Run tests on 3.8 with -W error::DeprecationWarning to surface problems early.
Inventory dependencies; upgrade or replace those without 3.13 wheels.
Add 3.13 to the CI matrix; fix removed modules, changed defaults and C-extension builds.
Use pyupgrade or ruff --target-version py313 to modernise syntax mechanically.
Deploy to a canary, compare error rates and latency, then roll out and drop the old version from CI.
python
import warnings, datetime, sys, importlib.util
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
datetime.datetime.utcnow()
print(sys.version_info[:2], [w.category.__name__ for w in caught])
print(caught[0].message.args[0].split(".")[0])
print({m: importlib.util.find_spec(m) is not None for m in ["cgi", "imghdr", "telnetlib", "tomllib"]})
print(datetime.datetime.now(datetime.UTC).tzinfo)
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
Enable warnings before upgrading
Upgrade dependencies first
Run CI on both versions
Handle removed modules and deprecations
Canary rollout with monitoring
Common mistakes
Jumping versions without running tests with warnings on
Upgrading Python before checking dependency support
Follow-ups
How would you handle a dependency that is abandoned?
What changed in asyncio between 3.8 and 3.13?
Tips
Name concrete removals
99.python-0099Hardsenior
What is the free-threaded build of Python 3.13, and how should a senior engineer evaluate it?
Python 3.13 ships an optional experimental build (python3.13t) with the GIL disabled, so threads can run Python code on several cores at once. The standard build still has the GIL. Evaluate it by checking that C extensions support it, measuring real workloads (single-threaded code runs slower in 3.13t), and auditing code that relied on the GIL for implicit thread safety.
(3, 13)
GIL enabled: True
free-threaded build: False
The box runs the standard 3.13 build, so the GIL is enabled and the build was not compiled for free threading; the free-threaded behaviour itself was not run here. sys._is_gil_enabled() is new in 3.13 and is the runtime check, since even a free-threaded build re-enables the GIL if an incompatible extension module is imported. Evaluation points: CPU-bound thread pools may scale with cores; libraries must publish free-threaded wheels; operations that happened to be atomic under the GIL, such as some read-modify-write patterns, need explicit locks; and single-thread performance is lower in 3.13t. Processes and asyncio remain the safe defaults for most services today.
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
3.13t is optional and experimental
Standard builds keep the GIL
Extensions must support it
Measure single and multi-threaded performance
Audit implicit GIL assumptions
Common mistakes
Assuming 3.13 removed the GIL everywhere
Switching builds without checking extension support
Follow-ups
Which workloads benefit most?
How do free-threaded wheels differ?
Tips
Mention the runtime check
100.python-0100Hardsenior
Design the package layout and public API for an internal Python library shared by several teams.
Use a src layout with pyproject.toml, a small public API re-exported from the package's __init__ with __all__, and internal modules prefixed with an underscore. Version with semantic versioning, deprecate with warnings for at least one minor release before removal, ship type hints with py.typed, and publish to an internal index from CI.
Full answer
python
import sys, tempfile, textwrap, warnings
from pathlib import Path
root = Path(tempfile.mkdtemp()) / "src" / "payments"
root.mkdir(parents=True)
(root / "_core.py").write_text(textwrap.dedent('''
def charge(amount_paise: int) -> str:
return f"charged {amount_paise}"
def _retry(): pass
'''))
(root / "__init__.py").write_text(textwrap.dedent('''
import warnings
from ._core import charge
__all__ = ["charge"]
__version__ = "2.3.0"
def old_charge(amount):
warnings.warn("old_charge is deprecated; use charge", DeprecationWarning, stacklevel=2)
return charge(amount)
'''))
(root / "py.typed").write_text("")
sys.path.insert(0, str(root.parent))
import payments
ns = {}
exec("from payments import *", ns)
print(payments.__version__, sorted(k for k in ns if not k.startswith("__")))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
print(payments.old_charge(500), w[0].category.__name__)
print(sorted(p.name for p in root.iterdir() if not p.name.startswith("__pycache")))
The run builds a minimal library in a temporary src layout. from payments import * exposes only charge, as declared in __all__, while _core and _retry stay internal by convention. The deprecated function still works but emits a DeprecationWarning pointing at the caller, thanks to stacklevel=2. The empty py.typed file tells type checkers to use the inline hints.
Further design points: keep the public surface small, because everything exported becomes a promise; document a support policy for Python versions; add a changelog; run tests against the oldest and newest supported versions; and give consuming teams a migration note for every major release.
python
import sys, tempfile, textwrap, warnings
from pathlib import Path
root = Path(tempfile.mkdtemp()) / "src" / "payments"
root.mkdir(parents=True)
(root / "_core.py").write_text(textwrap.dedent('''
def charge(amount_paise: int) -> str:
return f"charged {amount_paise}"
def _retry(): pass
'''))
(root / "__init__.py").write_text(textwrap.dedent('''
import warnings
from ._core import charge
__all__ = ["charge"]
__version__ = "2.3.0"
def old_charge(amount):
warnings.warn("old_charge is deprecated; use charge", DeprecationWarning, stacklevel=2)
return charge(amount)
'''))
(root / "py.typed").write_text("")
sys.path.insert(0, str(root.parent))
import payments
ns = {}
exec("from payments import *", ns)
print(payments.__version__, sorted(k for k in ns if not k.startswith("__")))
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
print(payments.old_charge(500), w[0].category.__name__)
print(sorted(p.name for p in root.iterdir() if not p.name.startswith("__pycache")))
Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
src layout with pyproject.toml
Explicit public API with __all__
Underscore-prefixed internals
Semantic versioning with deprecation periods
Ship py.typed for type hints
Common mistakes
Exposing every module as public API
Removing functions without a deprecation period
Follow-ups
How would you handle a breaking change used by ten teams?