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
- 10.1 Language core and syntax
- 10.2 Built-in data structures and the standard library
- 10.3 Functions, closures, decorators and generators
- 10.4 Classes, dataclasses and the data model
- 10.5 Typing, packaging and tooling
- 10.6 Runtime, memory and concurrency
- 10.7 Testing and debugging
- 10.8 Django
- 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
What does this print? ```python def add(item, items=[]): items.append(item) return items add(1) print(add(2)) ```
- `[2]`
- `[1, 2]`
- A `TypeError`
- `[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.
What does `collections.Counter("banana").most_common(1)` return?
- `{'a': 3}`
- `[('a', 3)]`
- `[('b', 1)]`
- `3`
Answer: B. `[('a', 3)]` Counter counts hashable items.
What is a decorator in Python?
- A special comment that documents what a function does
- A function that wraps another, applied with `@name`
- A type hint that describes a function's return value
- 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.
What does `@dataclass` generate for a class?
- A database table, with a column for each annotated field
- A REST endpoint that exposes instances of the class
- Only a JSON schema describing the class's fields
- `__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.
Why use type hints like `def total(prices: list[float]) -> float:`?
- Python raises a `TypeError` at runtime when the types don't match
- They make CPython run the code faster by compiling it to C
- They've been mandatory on all functions since Python 3.10
- 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.
What is the GIL in CPython?
- A lock letting only one thread run bytecode at a time, limiting CPU threading
- A security feature that blocks Python code from accessing the network
- The package manager CPython uses to install third-party libraries
- 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.
Why can pytest tests use a plain `assert total == 42` instead of special assertion methods?
- pytest replaces Python's `assert` with a function that never fails
- Plain asserts only work in pytest when running in debug mode
- pytest converts each assert into a `unittest` method at import time
- 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.
What is Django's architectural pattern often called?
- MVVM (Model–View–ViewModel)
- Flux, with one-way data flow
- Hexagonal (ports and adapters)
- MTV (Model–Template–View)
Answer: D. MTV (Model–Template–View) Django views play the controller role; templates render HTML.
What does FastAPI use type hints and Pydantic models for?
- Compiling the Python code to C so the API runs faster
- Rendering server-side HTML templates for each page
- Generating and applying database schema migrations
- 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.
What is the difference between `is` and `==` in Python?
- `is` checks for the same object; `==` checks equal values
- `is` only works on numbers; `==` works on any type
- They're interchangeable and always give the same result
- `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`.
More Server Side
- HTTP fundamentals
- REST API design
- GraphQL
- gRPC & real-time APIs
- OAuth 2.0, OIDC & JWT
- Sessions, cookies & web app security
- C# & .NET
- Java & Spring Boot
- Node.js & Express
- Go (Golang)
- Concurrency & multithreading
- OOP & SOLID
- Design patterns
- Dependency injection
- Logging & observability
- Data structures
- Algorithms & Big-O
- Linux & shell scripting