Assigning to count inside the function makes Python treat it as a local variable for the whole function, so reading it before assignment fails.
Say it like this in the interview
“UnboundLocalError. Because of the assignment, count is local in increment. I’d use global count (rarely a good idea), pass and return the value, or use a class or closure with nonlocal.”
a = 256; b = 256
print(a is b)
x = int('1000'); y = int('1000')
print(x is y)
In simple words
CPython reuses the same objects for small integers (-5 to 256), so is happens to be true for them but not for bigger numbers. It’s an implementation detail; never use is for numbers.
Say it like this in the interview
“Typically True then False, because small integers are cached. This shows why is must only be used for identity checks like None.”
tuple(1, 2): ordered, unchangeable. Can be a dict key.
set{1, 2}: no duplicates, fast “is it in here?”.
dict{'a': 1}: key → value lookup.
Say it like this in the interview
“Lists are mutable sequences; tuples are immutable and hashable, so they work as dict keys; sets give O(1) membership and deduplication; dicts map keys to values with O(1) average lookup and keep insertion order.”
== asks “do these look the same?” (equal values). is asks “are these literally the same object?” Use is only for None, True, False.
Say it like this in the interview
“== compares values via __eq__; is compares identity. I use is None for None checks, and == for everything else. Small integer and string caching can make is look like it works by accident.”
A comprehension is a one-line loop that builds a list or dict. Using round brackets makes a generator, which produces values one at a time instead of building the whole list.
squares = [n * n for n in range(1, 11) if n % 2 == 0] # [4, 16, 36, 64, 100]
lengths = {w: len(w) for w in ['api', 'python', 'db']} # {'api': 3, 'python': 6, 'db': 2}
total = sum(n * n for n in range(1_000_000)) # generator: no big list in memory
Say it like this in the interview
“List and dict comprehensions for building collections, and generator expressions when I only iterate once, to save memory.”
d['key'] crashes with KeyError if missing; .get returns None or a default; defaultdict creates a default value automatically when a key is missing.
Say it like this in the interview
“Brackets raise KeyError, get returns a default, setdefault inserts and returns, and defaultdict(list) auto-creates values, great for grouping. Counter for counting.”
Use sorted with a key function that returns a tuple. Negate numbers to reverse just one of them.
Say it like this in the interview
“sorted(people, key=lambda p: (-p['age'], p['name'])). Python’s sort is stable, so multi-pass sorting also works. sorted returns a new list; .sort() sorts in place.”
A decorator is gift wrapping for functions: it takes a function and returns a new function that does something before and after the original. @timed is shorthand for build_report = timed(build_report).
“A decorator is a higher-order function returning a wrapper. *args, **kwargs forward any arguments; functools.wraps keeps the original name and docstring. Django’s @login_required and FastAPI routes are decorators.”
*args collects extra positional arguments into a tuple; **kwargs collects extra named arguments into a dict. They let a function accept a flexible number of inputs.
Say it like this in the interview
“*args gathers positional arguments into a tuple and **kwargs keyword arguments into a dict. They’re also used to unpack when calling, fn(*items, **options), and in decorators to forward arguments.”
A function with yield that produces values one at a time and pauses in between, instead of building the whole list in memory.
Say it like this in the interview
“Generators produce items lazily, keeping memory constant, which is ideal for large files, streams, or infinite sequences. They can be chained into pipelines, and generator expressions use round brackets.”
In standard CPython, only one thread runs Python code at a time (the Global Interpreter Lock). So threads help when waiting (network, disk), but not for heavy calculation. For calculation, use multiple processes.
Say it like this in the interview
“The GIL lets only one thread execute Python bytecode at a time. Threads suit I/O-bound work; multiprocessing or process pools suit CPU-bound work; asyncio handles many concurrent I/O operations in one thread with cooperative scheduling, used by FastAPI. Python 3.13+ offers an experimental free-threaded build without the GIL.”
One thread switches between many tasks whenever one is waiting (for the network or a database). If any task does slow blocking work without await, everyone waits.
Say it like this in the interview
“An event loop runs coroutines cooperatively; await yields control during I/O. asyncio.gather runs tasks concurrently. Calling blocking code like time.sleep, requests or heavy CPU work inside a coroutine blocks the loop; I use async libraries like httpx and asyncpg, or asyncio.to_thread for blocking calls.”
Each project gets its own private box of packages, so project A’s Django 4 doesn’t clash with project B’s Django 5.
Say it like this in the interview
“A virtual environment isolates dependencies per project. I create one with python -m venv .venv or use uv or Poetry, and pin versions in a lock file so every machine installs exactly the same packages.”
Same N+1 problem as everywhere: one query for the list, then one per row for related data.
Say it like this in the interview
“Use select_related for foreign keys (SQL join) and prefetch_related for many-to-many or reverse relations, only()/values() to fetch fewer columns, add database indexes, and paginate. I find the issue with Django Debug Toolbar or by logging queries.”
Model = data, View = Python function handling the request, Template = HTML. A URL is matched to a view, the view uses models and renders a template.
Say it like this in the interview
“Request goes through middleware, the URL resolver finds the view, the view uses the ORM and forms, renders a template or returns JSON via DRF, and the response passes back through middleware. Django provides the admin, auth, migrations and ORM out of the box.”
Signals let code react automatically when something happens (a model was saved). Convenient, but logic becomes hidden and hard to follow.
Say it like this in the interview
“post_save, pre_delete and friends decouple side effects. Downsides: hidden control flow, they don’t fire on bulk operations like update() or bulk_create, and they run inside the request. I prefer explicit service functions and use signals sparingly.”
They convert model objects into JSON for the API and validate incoming JSON before saving, like forms for APIs.
Say it like this in the interview
“Serializers convert between model instances and JSON and validate input. ModelSerializer generates fields from models; viewsets and routers generate CRUD endpoints; permissions and throttling classes control access.”
FastAPI is a modern Python API framework: you describe the input with Python types, and it validates requests, converts types and generates API docs automatically.
Say it like this in the interview
“FastAPI uses type hints and Pydantic models for request validation and serialisation, generates OpenAPI docs automatically, and supports async. Dependency injection with Depends handles things like database sessions and auth. Django is better when I need the admin, ORM and batteries-included features.”
The with block guarantees setup and cleanup: open and close a file, acquire and release a lock, even if an error happens in the middle.
from contextlib import contextmanager
import time
@contextmanager
def timer(label):
start = time.perf_counter()
try:
yield
finally:
print(f"{label}: {time.perf_counter() - start:.3f}s")
with timer('report'):
build_report()
Say it like this in the interview
“Context managers implement __enter__ and __exit__, or I write one with @contextmanager and try/finally. They guarantee cleanup for files, connections, locks and transactions.”
Catch only the specific errors you can handle, keep the try block small, and never silently swallow errors.
Say it like this in the interview
“Catch specific exceptions, use else for code that runs only if no exception, finally for cleanup, raise ... from err to keep the cause, and custom exception classes for domain errors. Never a bare except: that hides bugs and even catches KeyboardInterrupt.”
No. Python ignores them at runtime. They help editors, tools like mypy, and readers catch mistakes, and frameworks like FastAPI and Pydantic use them for validation.
Say it like this in the interview
“Type hints aren’t enforced by the interpreter; static checkers like mypy or pyright use them, and libraries like Pydantic and FastAPI read them at runtime to validate data. I use them on public functions and run a type checker in CI.”
Special methods with double underscores that let your objects work with built-in syntax: printing, comparing, adding, len(), in, iteration.
Say it like this in the interview
“__init__, __repr__ and __str__, __eq__ and __hash__, __len__, __iter__, __getitem__, __add__, __enter__/__exit__, __call__. Implementing them makes custom classes behave like built-ins. @dataclass generates several automatically.”
It writes the boring class code for you: constructor, readable printing, and equality comparison, from just the field list.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Order:
id: int
items: list[str] = field(default_factory=list)
total: float = 0.0
Say it like this in the interview
“It generates __init__, __repr__ and __eq__ from type-annotated fields, with options like frozen=True for immutability and slots=True for memory. Pydantic models add validation for external data.”
“Stream with csv.reader over the open file line by line, or pandas with chunksize, or Polars’ lazy scanning; aggregate incrementally and write results as I go. For heavy analytics, DuckDB can query the CSV directly without loading it.”