Python for back ends: language, Django and FastAPI – Server Side interview prep

261 interview-style multiple-choice questions on Python for back ends: language, Django and FastAPI, organized by topic: concepts, scenarios, code to read and tradeoffs, each with a short explanation. Learn the 213 key terms with the flashcards first, then test yourself.

Take the practice test · Flashcards · All study tools

What it covers

  1. 10.1 Language core and syntax
  2. 10.2 Built-in data structures and the standard library
  3. 10.3 Functions, closures, decorators and generators
  4. 10.4 Classes, dataclasses and the data model
  5. 10.5 Typing, packaging and tooling
  6. 10.6 Runtime, memory and concurrency
  7. 10.7 Testing and debugging
  8. 10.8 Django
  9. 10.9 FastAPI, Flask and web services

Key terms

10.1 Language core and syntax

Mutable default argument
A default value created once and shared between calls
Decorator
Function that wraps another function
Context manager
Object managing setup and teardown with `with`
Generator
Function that yields values lazily
Truthiness
Empty and zero are falsy
Chained comparison
1 < x < 10
Floor division
// rounds toward minus infinity
math.isclose
Tolerant float comparison
Arbitrary-precision int
No overflow
f-string =
Prints name and value
Walrus operator
Assignment expression
match statement
Structural pattern matching
for-else
Runs when no break
try-else
Runs when no exception
Extended unpacking
first, *rest
removesuffix
Removes an exact suffix
raise from
Explicit exception cause
ExceptionGroup
Multiple exceptions at once
__all__
Names exported by import *
Circular import
Modules importing each other

10.2 Built-in data structures and the standard library

Set
Unordered collection with fast membership tests
Counter
Dict subclass for counting items
dataclass
Decorator that generates boilerplate for data classes
Type hint
Annotation describing expected types
dict.get
Lookup with default
setdefault
Insert if missing, return value
Dict merge operator
Merges two dicts into a new one
zip strict
Raise on unequal lengths
itertools.chain
Concatenate iterables lazily
itertools.groupby
Groups consecutive keys
islice
Slice any iterator
itertools.product
Cartesian product
any / all
Short-circuit tests
namedtuple
Tuple with named fields
ChainMap
Layered dict lookups
pathlib
Object-oriented paths
zoneinfo
IANA time zones
Naive datetime
No timezone attached
bytearray
Mutable bytes
subprocess.run
Run a command safely
logging.getLogger
Per-module logger
Raw string
Backslashes kept
tomllib
Read-only TOML parser
secrets
Secure random tokens

10.3 Functions, closures, decorators and generators

LEGB
Local, Enclosing, Global, Built-in
UnboundLocalError
Local read before assignment
nonlocal
Rebind enclosing variable
Late binding closure
Captures variable, not value
Keyword-only parameter
After bare *
Positional-only parameter
Before /
functools.wraps
Preserve wrapped metadata
Decorator factory
Returns a decorator
Decorator stacking
Nearest applies first
Generator expression
Lazy comprehension
yield from
Delegate to sub-generator
generator.send
Push value into generator
contextmanager
Generator-based context manager
contextlib.suppress
Ignore one exception type
ExitStack
Dynamic context managers
functools.reduce
Fold to one value
No tail-call optimization
Deep recursion overflows
attrgetter
Attribute key function

10.4 Classes, dataclasses and the data model

__str__ vs __repr__
User display vs developer form
__hash__ and __eq__
Equal objects need equal hashes
Frozen dataclass
Immutable, hashable fields
default_factory
Fresh mutable default per instance
__slots__
Fixed attributes, no __dict__
__post_init__
Validation after generated init
dataclasses.replace
Copy with changes
total_ordering
Fills in comparison methods
cached_property
Computed once per instance
Alternative constructor
classmethod returning cls(...)
__contains__
Controls in operator
__exit__
Context manager teardown
NotImplemented
Lets the other operand try
__new__
Creates the instance
Descriptor
__get__ / __set__ on a class
Metaclass
Class of a class
__init_subclass__
Hook on subclass creation
StrEnum
String-valued enum
Class attribute
Shared by all instances
__del__
Finalizer with no timing guarantee

10.5 Typing, packaging and tooling

Union with None
Modern Optional syntax
PEP 695 generics
def f[T](x: T)
type statement
Lazy type alias
Literal
Exact allowed values
TypedDict
Typed dict shape
overload
Signature variants for checkers
Self
Returns own class type
Final
No reassignment
Any vs object
Unchecked vs safest top type
cast
Checker-only type assertion
TYPE_CHECKING
Annotation-only imports
Deferred annotations
Lazy by default
Gradual typing
Unannotated code skipped
pyproject.toml
Standard project config
Wheel
Prebuilt package archive
uv
Rust-based package manager
uvx
Run a tool in a temp env
Ruff
Rust linter and formatter
Hash-checking mode
--require-hashes
Editable install
pip install -e .
PEP 668
Externally managed environment
src layout
Package under src/
Compatible release
~= specifier
Type stubs
.pyi hints for untyped libraries
py.typed
Package ships types

10.6 Runtime, memory and concurrency

GIL
Global Interpreter Lock in CPython
asyncio
Library for single-threaded concurrent I/O
multiprocessing
Parallelism with separate processes
Virtual environment
Isolated per-project Python packages
Free-threaded CPython
No-GIL build
GIL and I/O
Released while waiting
ThreadPoolExecutor
Thread pool for blocking calls
asyncio.to_thread
Run blocking call off the loop
TaskGroup
Structured concurrency
asyncio.timeout
Async deadline
asyncio.Semaphore
Limit concurrent tasks
Unawaited coroutine
Never runs
create_task reference
Keep it or lose it
asyncio.run
Async entry point
async with
Async context manager
Pickling
How work reaches processes
Spawn start method
Child re-imports main
forkserver
Linux default since 3.14
concurrent.interpreters
Per-interpreter GIL
CPython JIT
Experimental, off by default
WeakValueDictionary
Self-cleaning cache
tracemalloc
Allocation tracing
py-spy
Sampling profiler
PyPy
JIT Python implementation
Vectorization
Whole-array C loops
uvloop
Fast asyncio loop
as_completed
Futures in finish order

10.7 Testing and debugging

Assertion rewriting
Detailed assert failures
Fixture
Injected test dependency
Fixture scope
function, module, session
Yield fixture
Setup and teardown
conftest.py
Shared fixtures per directory
parametrize
One test, many cases
pytest.raises
Expect an exception
tmp_path
Per-test temp directory
ini_options
pytest config in pyproject
capsys
Capture printed output
pytest.approx
Float tolerance
Markers
Tag and select tests
xfail
Expected failure
autouse
Fixture applied implicitly
Autospec
Mock matching the real API
MagicMock
Mock with magic methods
AsyncMock
Awaitable mock
pytest-asyncio
Async test support
pytest-xdist
Parallel test runs
freezegun
Frozen clock in tests
breakpoint()
Enter the debugger
pdb
Python debugger
add_note
Extra context on exceptions
filterwarnings
Warnings as errors
doctest
Examples in docstrings
caplog
Capture log records

10.8 Django

Django ORM
Django's object-relational mapper
select_related
Django JOIN-based eager loading for foreign keys
Pydantic
Data validation library using type hints
ASGI
Asynchronous Server Gateway Interface
Django project vs app
Site vs feature package
makemigrations / migrate
Write vs apply migrations
F expression
Column value in SQL
Q object
Composable query condition
transaction.atomic
Database transaction block
annotate
Per-row computed values
only / defer
Partial column loading
bulk_create
Batched inserts
get_or_create race
Needs unique constraint
exists()
Cheap any-rows check
on_delete
FK delete behavior
Custom QuerySet
Named chainable filters
Django middleware order
Down for requests, up for responses
csrf_token
Hidden anti-forgery field
Auto-escaping
Escapes template variables
ModelForm
Form built from a model
Generic views
ListView, DetailView
DRF serializer
Model to JSON and back
Async ORM
aget, acount
DEBUG
Must be False in production
ALLOWED_HOSTS
Valid host names
Django Tasks
Built-in background tasks
Data migration
RunPython changes data
AUTH_USER_MODEL
Custom user model
Django TestCase
Rollback per test

10.9 FastAPI, Flask and web services

WSGI vs ASGI
Sync interface vs async interface
Uvicorn workers
Multiple processes
def vs async def endpoint
Thread pool vs event loop
response_model
Output filtering and validation
Query parameter
Non-path simple parameter
Annotated + Query
Parameter constraints
pydantic-core
Rust validation core
model_validate / model_dump
Pydantic v2 API
field_validator
Custom field check
BaseSettings
Typed env config
HTTPException
Error response
BackgroundTasks
Work after the response
lifespan
Startup and shutdown
APIRouter
Grouped endpoints
TestClient
In-process requests
CORSMiddleware
Cross-origin access
fastapi dev
Dev server with reload
Flask g
Per-request storage
Application factory
create_app()
Blueprint
Flask component
Starlette
ASGI toolkit under FastAPI
StreamingResponse
Chunked response body
httpx
Sync and async HTTP client
OAuth2PasswordBearer
Bearer token dependency

Sample practice questions

  1. What does this print? ```python def add(item, items=[]): items.append(item) return items add(1) print(add(2)) ```

    1. `[2]`
    2. `[1, 2]`
    3. A `TypeError`
    4. `[1]`

    Answer: B. `[1, 2]` The default list is created once, when the function is defined, and shared between calls, so the second call appends to the same list. Use `None` as the default and create the list inside.

  2. What does `collections.Counter("banana").most_common(1)` return?

    1. `{'a': 3}`
    2. `[('a', 3)]`
    3. `[('b', 1)]`
    4. `3`

    Answer: B. `[('a', 3)]` Counter counts hashable items.

  3. What is a decorator in Python?

    1. A special comment that documents what a function does
    2. A function that wraps another, applied with `@name`
    3. A type hint that describes a function's return value
    4. A class that styles and formats printed output

    Answer: B. A function that wraps another, applied with `@name` Use `functools.wraps` to keep the wrapped function's name and docstring.

  4. What does `@dataclass` generate for a class?

    1. A database table, with a column for each annotated field
    2. A REST endpoint that exposes instances of the class
    3. Only a JSON schema describing the class's fields
    4. `__init__`, `__repr__` and `__eq__` from the annotated fields

    Answer: D. `__init__`, `__repr__` and `__eq__` from the annotated fields Pydantic models add runtime validation on top of similar syntax.

  5. Why use type hints like `def total(prices: list[float]) -> float:`?

    1. Python raises a `TypeError` at runtime when the types don't match
    2. They make CPython run the code faster by compiling it to C
    3. They've been mandatory on all functions since Python 3.10
    4. They document intent for tools like mypy; Python doesn't enforce them

    Answer: D. They document intent for tools like mypy; Python doesn't enforce them Frameworks like FastAPI read hints to validate and document requests.

  6. What is the GIL in CPython?

    1. A lock letting only one thread run bytecode at a time, limiting CPU threading
    2. A security feature that blocks Python code from accessing the network
    3. The package manager CPython uses to install third-party libraries
    4. A built-in tool for profiling how much memory each object uses

    Answer: A. A lock letting only one thread run bytecode at a time, limiting CPU threading Python 3.13 added an experimental free-threaded build without the GIL.

  7. Why can pytest tests use a plain `assert total == 42` instead of special assertion methods?

    1. pytest replaces Python's `assert` with a function that never fails
    2. Plain asserts only work in pytest when running in debug mode
    3. pytest converts each assert into a `unittest` method at import time
    4. pytest rewrites assert statements to show the compared values when they fail

    Answer: D. pytest rewrites assert statements to show the compared values when they fail Failure output shows both sides of the comparison.

  8. What is Django's architectural pattern often called?

    1. MVVM (Model–View–ViewModel)
    2. Flux, with one-way data flow
    3. Hexagonal (ports and adapters)
    4. MTV (Model–Template–View)

    Answer: D. MTV (Model–Template–View) Django views play the controller role; templates render HTML.

  9. What does FastAPI use type hints and Pydantic models for?

    1. Compiling the Python code to C so the API runs faster
    2. Rendering server-side HTML templates for each page
    3. Generating and applying database schema migrations
    4. Validating requests, serializing responses and generating OpenAPI

    Answer: D. Validating requests, serializing responses and generating OpenAPI Invalid input gets an automatic `422` response with details.

  10. What is the difference between `is` and `==` in Python?

    1. `is` checks for the same object; `==` checks equal values
    2. `is` only works on numbers; `==` works on any type
    3. They're interchangeable and always give the same result
    4. `is` checks equal values; `==` checks for the same object

    Answer: A. `is` checks for the same object; `==` checks equal values Use `is` for `None` checks: `if x is None`.

Practice all 261 questions

More Server Side