Appearance
Errors, Modules and Packaging
43. How do try, except, else and finally work?
The short answer
try runs the risky code. An except SomeError block runs only if that error, or a subclass, is raised. else runs only if no exception happened, which keeps the "success" code out of the try so you do not accidentally catch its errors. finally runs always, error or not, even after return, so it is for cleanup. Catch specific exceptions; a bare except: or except Exception: that silently passes hides real bugs. Python's style is "easier to ask forgiveness than permission": try the operation and handle failure, instead of checking every condition first.
python
def parse_qty(raw: str) -> int | None:
try:
qty = int(raw) # (1)
except ValueError:
print("except") # (2)
return None
else:
print("else") # (3)
return qty
finally:
print("finally") # (4)
parse_qty("3") # else, finally, returns 3
parse_qty("x") # except, finally, returns None- Only the line that can fail is inside
try. - Runs only on
ValueError. - Runs only on success.
- Runs in both cases, even though both branches
return.
44. How do you create custom exceptions, and what does raise … from do?
The short answer
Subclass Exception, usually from your own base class, such as PaymentError, so callers can catch your whole family of errors at once, and add useful attributes like the order ID. When you catch a low-level error and raise a higher-level one, use raise NewError(...) from err: it records the original as __cause__, and the traceback shows both, "The above exception was the direct cause of…". Without from, Python still records it as __context__, "During handling… another exception occurred", which reads like a bug in the handler. Use from None to hide the original deliberately.
python
class PaymentError(Exception):
def __init__(self, order_id: str, reason: str):
super().__init__(f"payment failed for {order_id}: {reason}")
self.order_id = order_id
class CardDeclined(PaymentError): ...
def charge(order_id: str, wallet: dict):
try:
card = wallet["card"]
except KeyError as err:
raise CardDeclined(order_id, "no card on file") from err # (1)
try:
charge("ord_7", {})
except PaymentError as e: # (2)
print(type(e).__name__, e, "| cause:", repr(e.__cause__))
# CardDeclined payment failed for ord_7: no card on file | cause: KeyError('card')- Translate the error into one that means something to the caller, keeping the original for debugging.
- Catch the family by its base class.
Adding context without a new type: since 3.11, err.add_note("row 17 of orders.csv") attaches extra lines shown in the traceback.
45. What are exception groups and except*?
The short answer
An ExceptionGroup, added in Python 3.11, carries several exceptions at once, which happens naturally when many tasks run concurrently, such as in an asyncio.TaskGroup where three of ten requests fail. except* ValueError handles only the ValueErrors inside the group, and other kinds continue to the next except* clause or propagate. Several except* clauses can each run for the same group. You mainly meet these with asyncio.TaskGroup and libraries that run work in parallel.
python
try:
raise ExceptionGroup("batch failed", [ValueError("bad qty"), KeyError("sku"), ValueError("bad price")])
except* ValueError as eg:
print([str(e) for e in eg.exceptions]) # ['bad qty', 'bad price']
except* KeyError as eg:
print(eg.exceptions) # (KeyError('sku'),)Reading it: both clauses run, each receiving a smaller group with only its matching exceptions. A plain except ValueError would not match, because the raised object is an ExceptionGroup, not a ValueError. Concurrency with task groups is in asyncio task groups.
46. What are modules and packages, and what does if __name__ == "__main__": do?
The short answer
A module is a .py file; a package is a directory of modules, usually with an __init__.py, imported with dotted names like shop.orders.service. Each module runs once, on first import, and is cached in sys.modules; later imports reuse it. Every module has __name__: the module's dotted name when imported, or "__main__" when run directly with python file.py. So code under if __name__ == "__main__": runs only when the file is executed as a script, not when it is imported, which keeps importing side-effect free.
text
shop/
__init__.py
orders/
__init__.py
service.py
repository.py
cli.pypython
# shop/cli.py
from shop.orders.service import place_order # absolute import, preferred
def main() -> None:
place_order(customer_id=42, items=["A1"])
if __name__ == "__main__": # (1)
main()python -m shop.clirunsmain().import shop.clifrom elsewhere does not.
Run modules with -m. python -m shop.cli runs it as part of the package, so absolute imports work. python shop/cli.py puts the shop/ folder itself on the path and often breaks imports.
47. How does importing work, how do you fix circular imports, and what are lazy imports?
The short answer
import x finds the module on sys.path, executes it top to bottom once, caches it in sys.modules, and binds the name. A circular import happens when a imports b while b, during its own execution, imports a, which is only half-initialised, so a name it needs does not exist yet. Fix it by moving shared code into a third module, importing inside the function that needs it, or importing the module rather than names from it. Lazy imports, explicit since Python 3.15 with lazy import name, delay loading a module until it is first used, which speeds up startup for programs with many imports.
A circular import, and the fix:
python
# orders.py
from customers import Customer # (1)
class Order: ...
# customers.py
from orders import Order # (2) orders is half-loaded: ImportError
class Customer: ...ordersstarts loading and immediately importscustomers.customersasksordersforOrder, which has not been defined yet, becauseordersstopped at line 1.
| Fix | When |
|---|---|
Move shared types into a third module, such as models.py | The usual, cleanest fix |
| Import inside the function that needs it | A one-off dependency |
import orders and use orders.Order later | Only attribute access at call time |
if TYPE_CHECKING: imports for type hints only | The cycle exists only because of annotations |
Lazy imports in 3.15:
python
lazy import pandas as pd # nothing loaded yet
def export_report(rows):
return pd.DataFrame(rows) # pandas is imported here, on first useA command-line tool that imports pandas, boto3 and others at the top pays that cost even for --help. Lazy imports make startup cost depend on what is actually used.
48. What are virtual environments, and why use them?
The short answer
A virtual environment is a folder containing its own Python interpreter link and its own site-packages, so each project has its own versions of its dependencies, isolated from other projects and from the system Python. Without one, installing requests 2.x for one project can break another that needs an older version. Create one with python -m venv .venv and activate it, or let uv or Poetry create and manage it for you. Never commit the environment folder; commit the dependency list and lock file instead.
bash
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install fastapi
# or with uv, which creates and uses .venv automatically
uv init shop-api
uv add fastapi "uvicorn[standard]"
uv run uvicorn app.main:app --reload49. How do you package a Python project, and how do pip, uv and Poetry differ?
The short answer
A modern project describes itself in pyproject.toml: name, version, Python version, dependencies, optional groups and the build backend. Dependencies are pinned for reproducible installs in a lock file, such as uv.lock or poetry.lock. pip installs packages and is always available, but does not manage projects or lock files on its own. uv, from Astral and written in Rust, is a very fast all-in-one tool that manages Python versions, virtual environments, dependencies, lock files and running tools; it has become the common choice for new projects. Poetry is an older project manager with similar goals.
toml
[project]
name = "shop-api"
version = "1.4.0"
requires-python = ">=3.13"
dependencies = [
"fastapi>=0.115",
"sqlalchemy>=2.0",
"pydantic-settings>=2.4",
]
[dependency-groups]
dev = ["ruff", "mypy"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"| Tool | Does | Lock file | Notes |
|---|---|---|---|
| pip | Install packages | No, use pip-tools or constraints | Built in |
| uv | Python versions, venvs, deps, lock, run, build | uv.lock | Very fast; a drop-in uv pip too |
| Poetry | Venvs, deps, lock, build, publish | poetry.lock | Mature, slower |
pipx or uv tool | Install command-line tools in isolation | For tools like ruff |
In Docker: copy pyproject.toml and the lock file first, install from the lock, then copy the source, so the dependency layer is cached. With uv: uv sync --frozen --no-dev.
50. How do you read and write files safely, and what changed about encodings?
The short answer
Use with open(...) so the file always closes, pass encoding="utf-8" explicitly, read large files line by line or in chunks rather than all at once, and use pathlib.Path for paths. Write important files atomically: write to a temporary file in the same folder, then os.replace it over the target, so a crash never leaves a half-written file. Since Python 3.15, UTF-8 is the default text encoding everywhere, ending a long-standing problem where Windows used a legacy code page and the same code read files differently on different machines.
python
from pathlib import Path
import json, os, tempfile
orders_dir = Path("data") / "orders"
for path in orders_dir.glob("*.jsonl"):
with path.open(encoding="utf-8") as f:
for line in f: # (1)
process(json.loads(line))
def write_atomic(path: Path, text: str) -> None:
fd, tmp = tempfile.mkstemp(dir=path.parent) # (2)
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(text)
f.flush(); os.fsync(f.fileno())
os.replace(tmp, path) # (3)- One line at a time, so a 5 GB file uses little memory.
- The temporary file is in the same folder, so the final move is on the same disk.
os.replaceis atomic: readers see the old file or the new one, never half of one.