Library
Secure coding in Python
Most vulnerabilities are not exotic. They hide in code that is hard to read: a function nobody fully understands, an error that passes silently, a message that tells an attacker more than it tells the user. So the first security tool you own is the one this course has been sharpening all along — clear, small, boring Python. This guide turns that idea into concrete habits: how to set up a safe environment, how to fail well, and all fifteen secure-coding practices — from the Zen of Python, line-of-sight code, type annotations, docstrings, and exception discipline through imports, dependencies, SQL, and a hardened HTTP client.
All code below runs unmodified on Python 3.14, and every output shown is the real output of a run.
Start with a safe environment
Before the first line of code, three habits remove a whole class of problems:
- Use a currently supported Python 3. Old minor versions stop receiving security fixes. The course installs 3.13 or newer in Part 1; stay current the same way on real projects.
- Isolate every project.
python -m venv .venvpluspipis the standard, built-in way — one project's packages (and one project's compromised package) cannot leak into another. uv is a popular faster drop-in if your team prefers it. - Type package names carefully. Attackers publish packages whose names are one typo away from famous ones (
requets,numpyy) — this is called typosquatting. Copy names from the project's own docs, pin them inrequirements.txt, and read the name once more before you press Enter onpip install.
Does a clean environment make the application secure? No — it is the entry ticket, not the match. The rest of this guide is about the code itself.
Defensive programming and secure coding
These are two related ideas, and you need both of them:
| Idea | The question it asks | Example |
|---|---|---|
| Defensive programming | "What could go wrong at runtime, and how does my code stay standing when it does?" | Validate inputs, handle the ValueError, close the file even on a crash |
| Secure coding | "How do I use the language so an attacker gets nothing to work with?" | Don't leak internals in error messages, don't build nested code nobody can review |
Defensive programming is anticipation: you assume bad input, missing files, and flaky networks, and write code that behaves predictably anyway. Secure coding is using Python's own constructs — exceptions, context managers, logging levels — so the finished program gives attackers the smallest possible surface. A program that is merely defensive can still leak secrets in a stack trace; a program that is merely "secure" can still fall over on the first malformed request. Write both.
Five ways to fail well
Things will go wrong. Defensive programming is mostly about choosing how your program fails. Five disciplines cover it.
1. Fail fast
Check the cheap things before you start the expensive things. If a request is going to be rejected, reject it before it touches the database, the disk, or the network — otherwise an attacker can destabilize your service just by sending many doomed-but-expensive requests.
def export_report(rows, fmt):
if fmt not in {"csv", "json"}: # cheap check first
raise ValueError(f"unsupported format: {fmt!r}")
return f"exported {len(rows)} rows as {fmt}" # the expensive part
print(export_report([1, 2, 3], "csv"))
try:
export_report([1, 2, 3], "pdf")
except ValueError as error:
print("rejected:", error)
exported 3 rows as csv
rejected: unsupported format: 'pdf'
The bad format never reaches the "expensive" line. One if at the top is the whole defense.
2. Fail safe
Whatever you open, close — even when the code between open and close blows up. Files left open, locks left held, and half-written temp files are all gifts to an attacker (and to future you). Python's with statement (Part 8) exists exactly for this:
from tempfile import NamedTemporaryFile
f = NamedTemporaryFile("w")
try:
with f:
f.write("order 1\n")
raise RuntimeError("disk full halfway")
except RuntimeError as error:
print("handled:", error)
print("file closed anyway?", f.closed)
handled: disk full halfway
file closed anyway? True
The error fired halfway through, and the file still got closed, because with runs the cleanup no matter how the block exits.
3. Fail conspicuously
Log failures loudly for yourself, quietly for the user. A cluster of logged failures is often the first sign of an attack in progress — but the message you show the user must not disclose paths, table names, library versions, or which half of "username and password" was wrong.
import logging, sys
logging.basicConfig(stream=sys.stdout, format="%(levelname)s %(message)s")
def careful_login_error(user_id):
logging.warning("login failed for user id %s (users.db lookup)", user_id)
return "Login failed. Check your username and password."
print(careful_login_error(42))
WARNING login failed for user id 42 (users.db lookup)
Login failed. Check your username and password.
The first line goes to your logs with every detail you need; the second is all the user (or attacker) ever sees. Compare the message you should never return: "no row in users.db at /srv/app/users.db for id 42" — that one sentence leaks a file path, the storage technology, and a valid user id.
4. Fail appropriately
Not every failure deserves the same alarm. Layer severities with the logging module (Part 7 covers modules) and keep CRITICAL rare — critical messages are the ones that should page a human, and if everything pages, nothing does.
import logging, sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG,
format="%(levelname)-8s %(message)s")
log = logging.getLogger("orders")
log.debug("cart contents: ['tea', 'vada pav']")
log.info("order 184 placed")
log.warning("payment retried once")
log.error("payment failed after 3 retries")
log.critical("payment provider unreachable — page the on-call")
DEBUG cart contents: ['tea', 'vada pav']
INFO order 184 placed
WARNING payment retried once
ERROR payment failed after 3 retries
CRITICAL payment provider unreachable — page the on-call
In production you set the level to WARNING or higher and the first two lines disappear; the layering costs nothing and buys you a dial.
5. Fail creatively
Not everything should raise. Sometimes the right response to bad input is a default, an empty result, or "ask again" — reserve exceptions for the cases the caller genuinely cannot continue from (the full decision guide is in Part 6):
def to_qty(text):
try:
qty = int(text)
except ValueError:
return None
return qty if qty > 0 else None
for raw in ["3", "three", "-1"]:
qty = to_qty(raw)
print(raw, "->", qty if qty is not None else "ask again")
3 -> 3
three -> ask again
-1 -> ask again
A junk quantity in a form is normal life, not a crisis. Handle it in place and keep the program running.
🧪 Quick quiz — answer from memory, then check.
- Why should you validate a request's format before querying the database, not after?
- Your code opened a file and then crashed. Which Python construct guarantees the file still gets closed?
- A login error returns
"no row in users.db for id 42". Name two things that message leaks. - Why must
CRITICALlog messages stay rare?
Show the answers
- Fail fast: a doomed request should cost you almost nothing. If attackers can make you do expensive work before the rejection, a handful of requests can destabilize the service.
- The
withstatement (a context manager) — its cleanup runs no matter how the block exits, as the fail-safe example shows (file closed anyway? True). - The storage technology and filename (
users.db), and that id 42 is a real lookup key; the fuller version in the text also leaks the server path/srv/app/. - Critical messages are the ones that should page a human. If every failure is marked critical, real emergencies drown in noise and nobody responds to the pager.
Practice 1 — Read the Zen of Python as security advice
Python ships its own design philosophy. Run this anywhere:
import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Read it again wearing a security hat (PEP 20 is the official home) and it turns into a checklist:
| Aphorism | The security reading |
|---|---|
| Simple is better than complex | You can only secure what you can explain end to end; complexity is where bugs hide |
| Flat is better than nested | Deeply nested branches are where unchecked paths hide (see line-of-sight, below) |
| Errors should never pass silently | A swallowed exception is an attack nobody notices |
| Refuse the temptation to guess | Guessing at ambiguous input is how injection and parsing bugs start |
| One obvious way to do it | If the same job is done three ways in one codebase, at least two are reviewed less carefully |
| If the implementation is hard to explain, it's a bad idea | If nobody can explain it in review, nobody can vouch for its safety |
In practice, applying the Zen comes down to four properties — make your code explicit (names say exactly what things do), readable (short lines, clear structure), consistent (similar problems solved the same way), and singular (one job, one place — don't repeat the same operation in three spots, because you will fix a bug in only two of them).
The most concrete payoff is knowing when to refactor a function. Any of these six smells means it is time:
| Trigger | Why it matters for security |
|---|---|
| More than 3 parameters | Too many ways to call it wrong; callers start guessing |
| A boolean parameter | The function secretly does two jobs — review covers one of them |
Piles of *args / **kwargs |
Nobody, including the type checker, knows what goes in |
More than 3 return statements |
Too many exits to keep in your head during review |
| Nesting deeper than 2 levels | The inner branches stop getting read carefully |
| Too long to see at once | What scrolls off the screen scrolls out of the review |
The boolean-parameter one surprises people, so here it is:
def send_receipt(order, email=True): # boolean parameter = two jobs
return f"emailed {order}" if email else f"printed {order}"
def email_receipt(order): # split: each does one job
return f"emailed {order}"
def print_receipt(order):
return f"printed {order}"
print(send_receipt(184), "|", send_receipt(184, email=False))
print(email_receipt(184), "|", print_receipt(184))
emailed 184 | printed 184
emailed 184 | printed 184
Same behavior, but the split versions are each half the size, named after what they do, and testable in isolation.
Practice 2 — Automate style in your toolchain
PEP 8 is the shared style guide that makes every Python codebase on Earth feel familiar — and familiarity is what lets a reviewer spot the line that doesn't belong. But style arguments waste review time, and PEP 8 doesn't settle every question. The fix: let tools decide, automatically, so humans never discuss formatting again and reviews spend their attention on logic and security.
Run tools in two rings:
| When | Tools | What they catch |
|---|---|---|
| On every save | a formatter (black or ruff format) · a linter (ruff) · a type checker (mypy) · your unit tests | Style drift, obvious bugs, type mismatches — caught seconds after you create them |
| Before every commit | a dependency auditor (pip-audit) · a security linter (bandit) · integration tests · your build | Known-vulnerable packages, risky patterns (eval, hardcoded passwords, weak hashes), broken integrations |
A typical day-to-day loop looks like this (these are third-party tools, so install them in your project's venv first):
ruff format . && ruff check . && mypy . && python -m pytest # on save / before you look away
pip-audit && bandit -r src/ # before each commit
If a commit-ring tool raises a flag, fix it before code review — a reviewer's attention is the scarcest security resource you have, and every style nit it spends on is a vulnerability it might miss.
Practice 3 — Write line-of-sight code
Line-of-sight style means a reader's eyes travel straight down the left edge of your function: error cases leave early at the top, and the last line is the un-indented normal result. It has two rules: prefer early return and raise over else, and keep the indentation shallow.
The smallest version is dropping the else-return:
def badge(points):
if points >= 100:
return "gold"
else: # else-return: an extra branch for no reason
return "silver"
def badge_los(points):
if points < 100: # the less common case leaves early
return "silver"
return "gold" # the normal result, flush left
print(badge(120), badge_los(120))
print(badge(40), badge_los(40))
gold gold
silver silver
Same behavior, one line shorter, and the main path sits flush left where your eye lands. Multiply that across a codebase and there is meaningfully less code for vulnerabilities to hide in.
Now for the real case. Here is the nested shape everyone writes when chasing a deadline — the conditions funnel inward, and to understand the success path you must hold every level in your head:
def place_order(wallet, item, menu, stock):
if item in menu:
if stock.get(item, 0) > 0:
if wallet >= menu[item]:
stock[item] -= 1
return wallet - menu[item]
else:
raise ValueError("not enough money")
else:
raise ValueError("out of stock")
else:
raise ValueError("not on the menu")
print(place_order(50, "tea", {"tea": 15}, {"tea": 1}))
try:
place_order(50, "samosa", {"tea": 15}, {"tea": 1})
except ValueError as error:
print("rejected:", error)
35
rejected: not on the menu
Notice the distance: the check if item in menu sits ten lines away from its own raise. The line-of-sight rewrite reverses each condition and exits immediately:
def place_order(wallet, item, menu, stock):
if item not in menu:
raise ValueError("not on the menu")
if stock.get(item, 0) <= 0:
raise ValueError("out of stock")
if wallet < menu[item]:
raise ValueError("not enough money")
stock[item] -= 1
return wallet - menu[item]
print(place_order(50, "tea", {"tea": 15}, {"tea": 1}))
try:
place_order(50, "samosa", {"tea": 15}, {"tea": 1})
except ValueError as error:
print("rejected:", error)
35
rejected: not on the menu
Identical output, so nothing changed in behavior — but every guard now sits beside its own raise, the failure conditions read top to bottom like a checklist, and a reviewer can glance at the bottom two lines and know exactly what the function does on success. Early exits are also kinder to performance: doomed calls leave at the first guard. This is the same shape the course's own exception material builds toward in Part 6.
🧪 Quick quiz — answer from memory, then check.
- Which Zen line argues directly against the "funnel of death" nesting shape?
- Name the two tool rings and one tool that belongs in each.
- A function takes
simple=Trueas a parameter. Which refactor trigger is that, and what is the fix? - In line-of-sight style, where does the normal (success) result live?
Show the answers
- "Flat is better than nested." ("Simple is better than complex" is a close second.)
- On every save: formatter, linter, type checker, unit tests (e.g. ruff, mypy). Before every commit: dependency auditor, security linter, integration tests, build (e.g. pip-audit, bandit).
- The boolean-parameter trigger — the function does two jobs. Split it into two functions, one per job, as in the
send_receipt→email_receipt/print_receiptexample. - On the last line, flush left (un-indented) — error cases have already returned or raised earlier, so the reader finds the main outcome exactly where their eyes stop.
Practice 4 — Annotate your types (PEP 484)
PEP 484 gave Python a standard way to write down what goes into a function and what comes out. Use annotations everywhere: they make the signature self-documenting, and they give the type checker something to check. Without them you are leaning on Python's dynamic typing to "work it out" — and a value quietly flowing somewhere you never intended is exactly how control-flow bugs start.
One honest thing first: annotations are documentation plus checker fodder, not a runtime fence. Python will happily run a wrongly-typed call:
def add(a: int, b: int) -> int:
return a + b
print(add(2, 3))
print(add("se", "cure")) # wrong types — Python runs it anyway
print(add.__annotations__)
5
secure
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
The second call contradicts the annotation and still runs — the annotations just sit there as metadata (the last line). It is mypy (or ruff check with type rules) in your on-save ring from Practice 2 that turns them into a tripwire: run it and the add("se", "cure") call is flagged before the code ever ships. That catch is cheap, early, and automatic — which is the whole security argument.
Three habits make annotations pay off:
- Modern syntax. Write
str | Nonefor "a string or nothing" and use the built-in generics directly:dict[str, tuple[float, float]],list[int]. (Older code importsOptionalandDictfromtyping— same meaning, more ceremony.) - Alias the mouthfuls. A signature full of nested generics is unreadable, and unreadable signatures stop getting reviewed. Name the type once and reuse it.
- Annotate what you receive, too. Annotating the variable that takes a return value seems redundant — until a refactor changes what the function returns, and the checker catches the mismatch at every call site for you.
The second and third habits fit in one example:
type VerticeMap = dict[str, tuple[float, float]]
def load_vertices() -> VerticeMap:
return {"depot": (12.97, 77.59), "cafe": (12.93, 77.61)}
result: VerticeMap = load_vertices()
print(result["depot"])
(12.97, 77.59)
Nobody retypes dict[str, tuple[float, float]] at every signature; if load_vertices ever starts returning something else, the annotated result line is where the type checker raises its hand.
Practice 5 — Write full docstrings (PEP 257)
Nobody enjoys writing documentation, which is exactly why PEP 257 makes it a convention rather than a mood. Writing the docstring forces you through your own function one more time — the arguments, the business logic, the failure states — and that second pass is where you notice the case you forgot to handle. Think of it as an investment in the next person's understanding, because the developer who misunderstands your function is the one who refactors a vulnerability into it.
A full docstring carries a one-line summary, the arguments, the return value, and — the part people skip — what it raises. Types stay out of it: the annotations already say those, so the docstring explains meaning, not shape.
def get_rss_feed(url: str, retries: int = 3) -> str:
"""Load and validate the contents of an RSS feed.
Args:
url: the address of the feed to fetch.
retries: how many HTTP attempts to make before giving up.
Returns:
The feed's contents, decoded as UTF-8, after validation.
Raises:
ConnectionError: if every retry attempt fails.
"""
return f"(feed from {url}, fetched within {retries} tries)"
help(get_rss_feed)
Help on function get_rss_feed in module __main__:
get_rss_feed(url: str, retries: int = 3) -> str
Load and validate the contents of an RSS feed.
Args:
url: the address of the feed to fetch.
retries: how many HTTP attempts to make before giving up.
Returns:
The feed's contents, decoded as UTF-8, after validation.
Raises:
ConnectionError: if every retry attempt fails.
That help() output is what every future reader — including you in six months — gets for free, in the shell, without opening the source.
And ordinary # comments? Keep them scarce: roughly 90% of your commenting belongs in docstrings. A comment that explains what your own code does is not documentation — it is a confession that the code needs refactoring. (A comment that records a constraint the code cannot show — "the API returns dates in local time" — is the good kind.)
Practice 6 — Avoid the evil little functions
Python has a short list of built-ins that turn text into running code: eval and exec lead it. They do not belong in your codebase. Not behind a validation layer, not "just for config", not temporarily. The linter ring from Practice 2 flags them (bandit treats them as findings out of the box), and a reviewer should simply bounce them.
Here is why there is no safe amount of eval. The attacker's string below pretends to be a harmless "config value"; the demo sets up its own scratch folder with a fake customer file so you can see the reach without touching anything real:
import os, tempfile
demo = tempfile.mkdtemp() # a stand-in for your server's disk
with open(os.path.join(demo, "customers.txt"), "w") as f:
f.write("alice,[email protected]\n")
os.chdir(demo)
attacker_text = '__import__("pathlib").Path("customers.txt").read_text()'
print(eval(attacker_text), end="") # the "config value" runs as code
alice,[email protected]
One string, and the attacker is reading files. The trick is that eval has no fence around it: even if your code never imported a dangerous module, the attacker's text can call __import__ and pull in any module on the system — pathlib here, subprocess just as easily. On a real server, swap the filename and that same line reads your secrets file or the system's account list — one eval is all it takes.
When you genuinely need to turn text into data (not code), the standard library already has the safe tool:
from ast import literal_eval
print(literal_eval("[1, 2, 3]"))
print(literal_eval("{'retries': 3}"))
try:
literal_eval('__import__("pathlib")')
except ValueError:
print("rejected: not a plain literal")
[1, 2, 3]
{'retries': 3}
rejected: not a plain literal
ast.literal_eval accepts literals — numbers, strings, lists, dicts, tuples, booleans — and refuses anything that would execute. For structured config, json.loads (Part 8) is the same idea with a stricter format.
Practice 7 — Never raise a bare Exception
raise Exception("something broke") is a mystery novel with the last page torn out. The caller cannot react to it without catching every possible error, your logs cannot be filtered by failure type, and the next developer goes hunting through the codebase to figure out what actually went wrong. Exceptions should name the failure state as precisely as possible.
First choice: the built-ins you already know from Part 6 — TypeError for a wrong kind of value, ValueError for a right kind with a bad value, OSError for the operating system saying no. (Two names you may meet in older code, IOError and EnvironmentError, are literally the same class today:)
print(IOError is OSError, EnvironmentError is OSError)
True True
When no built-in fits, define a custom exception per failure state — docstringed (Practice 5), and defined next to the code that raises it, so the investigation ends where the error began instead of in a wild-goose chase across packages:
class ProductSoldOut(Exception):
"""Raised when an item's stock reaches zero."""
def buy(item, stock):
if stock.get(item, 0) <= 0:
raise ProductSoldOut(item)
stock[item] -= 1
return f"sold one {item}"
stock = {"tea": 1}
print(buy("tea", stock))
try:
buy("tea", stock)
except ProductSoldOut as error:
print("sold out:", error)
sold one tea
sold out: tea
The caller catches exactly the condition it knows how to handle — restock, show "sold out", whatever the business needs — and nothing else.
The one place a general Exception belongs is the blanket catch at the end of a try — and there it gets exactly two jobs: log, then re-raise. Your code did not anticipate this failure, so it must not pretend to handle it; let it bubble up to a level that can. Handle the states you did anticipate explicitly above it:
import logging, sys
logging.basicConfig(stream=sys.stdout, format="%(levelname)s %(message)s")
def parse_ok(text): return f"parsed {len(text)} characters"
def parse_bad(text): raise ValueError("not valid XML")
def parse_broken(text): return 1 / len("")
def sync_feed(parse):
try:
return parse("<rss>...</rss>")
except ValueError as error: # anticipated: bad feed data, retry later
print("feed skipped:", error)
except Exception: # unanticipated: log it, then pass it up
logging.error("unexpected failure in sync_feed")
raise
print(sync_feed(parse_ok))
sync_feed(parse_bad)
try:
sync_feed(parse_broken)
except ZeroDivisionError:
print("the caller handled what sync_feed could not")
parsed 14 characters
feed skipped: not valid XML
ERROR unexpected failure in sync_feed
the caller handled what sync_feed could not
Three endings, each handled at the right altitude: the expected bad feed is dealt with in place, the surprise is logged and propagated, and the caller — which knows the bigger picture — decides what a division blow-up means. (If you deliberately swallow an exception instead, say why in a comment on the pass — a silent pass in an except is the "errors should never pass silently" sin from Practice 1.)
🧪 Quick quiz — answer from memory, then check.
add(a: int, b: int)is called asadd("se", "cure"). What happens at runtime, and what catches the mistake instead?- Your docstring lists the parameter types. What does this guide tell you to do instead?
- What is the risk of leaving a function's parameters unannotated?
- Between a linter and a type checker, which one actually validates your annotations — and what does the other do?
- Why is
evalon user-supplied text unsalvageable even when your module imports nothing dangerous — and what is the safe stdlib tool for turning text into plain data? - When is
except Exceptionacceptable, and what are its only two jobs there?
Show the answers
- It runs and returns
"secure"— annotations are not enforced at runtime (the executed example shows it). The type checker in your on-save ring (mypy / ruff) is what flags the call, before the code ships. - Keep types in the annotations and use the docstring for meaning: the summary, what each argument is for, what comes back, and what the function raises.
- Every caller has to guess what the function expects, and a wrong guess sails through silently — Python's dynamic typing happily passes the wrong shape along until it breaks somewhere far from the mistake, which is exactly where type-confusion bugs and vulnerabilities come from.
- The type checker (mypy) — it follows the annotations through every call and flags inconsistent usage. A linter (ruff, pylint) checks style and known-dangerous patterns, but it does not prove your types line up.
- Because
evalhas no scope fence: attacker text can call__import__and reach any module on the system — the demo read a file viapathlibwithout the code importing it. For text-to-data, useast.literal_eval(orjson.loadsfor structured config); it accepts literals and rejects anything executable. - As the final blanket catch in a
tryblock, for failures your code did not anticipate — it logs the failure, then re-raises so the error propagates to a level that can actually decide.
Practice 8 — Eliminate empty returns
return None on failure feels polite, but it is a failure wearing a success costume: the caller gets a value, carries on, and the crash happens somewhere far from the cause — the worst place to debug it. If the function cannot do its job, say so, by name, where the problem is.
class Member:
def __init__(self, name, card_id):
self.name = name
self.card_id = card_id
def card_url_before(member):
if member.card_id is None:
return None # a failure dressed as a value
return f"https://library.example/cards/{member.card_id}.html"
url = card_url_before(Member("asha", None))
try:
print(url.upper())
except AttributeError as error:
print("crashed far from the cause:", error)
crashed far from the cause: 'NoneType' object has no attribute 'upper'
The AttributeError points at the upper() call, not at the missing card id that actually caused it. Raise a named exception instead — and annotate the return type, so the contract "this returns a str, always" is written down where the type checker can hold you to it:
class MissingCardError(Exception):
"""Raised when a member record has no card id."""
def card_url(member) -> str:
if member.card_id is None:
raise MissingCardError(f"member {member.name!r} has no card id")
return f"https://library.example/cards/{member.card_id}.html"
print(card_url(Member("asha", "A-100")))
try:
card_url(Member("ravi", None))
except MissingCardError as error:
print("named failure at the source:", error)
https://library.example/cards/A-100.html
named failure at the source: member 'ravi' has no card id
A member without a card id means something went wrong at the data level — that deserves an exception, not a quiet None. (Validation itself belongs even earlier, in the constructor, following the fail-fast discipline.)
Practice 9 — Write a last-resort decorator
Practices 1–7 handle the failures you anticipated. A last-resort decorator is for the ones you did not: it wraps an entry point, logs the full detail of any unanticipated failure, and hands the caller a named, information-free error. It is "fail conspicuously" and "never raise a bare Exception" working together — the traceback goes to the log where you can read it, never to the caller where an attacker can.
import functools, logging, sys
logging.basicConfig(stream=sys.stdout, format="%(levelname)-8s %(name)s: %(message)s")
class LastResortError(Exception):
"""Raised when an unanticipated failure hit the last-resort handler."""
def last_resort(fn):
log = logging.getLogger("last-resort")
@functools.wraps(fn)
def wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except Exception:
log.exception("unanticipated failure in %s", fn.__name__)
raise LastResortError("internal error — the details were logged") from None
return wrapper
@last_resort
def nightly_sync(records):
return records["feed"] # nothing anticipated a missing key
try:
nightly_sync({})
except LastResortError as error:
print("caller sees only:", error)
ERROR last-resort: unanticipated failure in nightly_sync
Traceback (most recent call last):
File "<stdin>", line 13, in wrapper
File "<stdin>", line 21, in nightly_sync
KeyError: 'feed'
caller sees only: internal error — the details were logged
In production, point that logger somewhere an attacker cannot quietly sweep (the system journal, a log shipper) and wire it to your paging service — this is a CRITICAL-tier signal. And watch its frequency: a last-resort handler that fires regularly is telling you either that your error handling has gaps, or that someone is probing the application. Either way, it is intelligence.
Practice 10 — Parameterize every query (then let an ORM help)
One rule is non-negotiable wherever SQL meets outside input: never build a query by gluing user text into the SQL string. The database cannot tell your SQL from the user's SQL. Watch it happen, with the standard library's sqlite3:
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE members (name TEXT, card TEXT)")
db.executemany("INSERT INTO members VALUES (?, ?)",
[("asha", "A-100"), ("ravi", "A-101")])
def find_glued(name):
return db.execute(
f"SELECT name, card FROM members WHERE name = '{name}'").fetchall()
def find_safe(name):
return db.execute(
"SELECT name, card FROM members WHERE name = ?", (name,)).fetchall()
print(find_glued("asha"))
print(find_glued("nobody' OR '1'='1"))
print(find_safe("nobody' OR '1'='1"))
[('asha', 'A-100')]
[('asha', 'A-100'), ('ravi', 'A-101')]
[]
The glued version turned a lookup for nobody into "give me every row" — that is SQL injection, in two printed lines. The parameterized version hands the same hostile text to the driver as data, and it matches nothing.
On top of that rule, an ORM (SQLAlchemy, or Django's) earns its keep: it parameterizes by default, gives your queries types and names the checker can follow, and keeps schema knowledge in one place. Use one for application code. But be honest about what it is: a layer, not a spell — raw-SQL escape hatches and badly built filters can still be injected, and our SQL course exists precisely because you should understand the queries your ORM writes.
Practice 11 — Follow import best practices
How a module gets its dependencies is a security boundary. Three habits keep it boring:
- Absolute imports only. An absolute path names one place in the project; a relative one names "wherever this file happens to live today". After a refactor or a repackaging, relative imports are how the wrong code gets found.
import orders.payments # one unambiguous place
from orders import payments # also absolute, also fine
from . import payments # relative: moves when the package moves
- No conditional imports. An import inside a
try/except ImportErrormeans development can run one code path and production another — and the linter that flags it is doing you a favor; do not silence it. If you genuinely need per-platform adapters, isolate them behind one small compatibility module instead of scattering maybe-imports.
try:
from adapters.linux import notify # which one ships to production?
except ImportError:
from adapters.windows import notify
- Scan what you import. Every dependency is code you now run; Practice 15 covers the scanners. And install only names you copied from the project's own docs — the environment section opened with typosquatting for the same reason.
Practice 12 — Respect the local namespace
When you pull individual names out of a module, they land unqualified in your namespace, where they can collide with — or silently replace — names you already use:
from json import load
def load(path):
return f"reading {path} from the cache"
print(load("settings.json")) # json.load is gone — silently replaced
import json
print(json.load is load) # the package-qualified name survives
reading settings.json from the cache
False
No error, no warning — the standard library's load was simply shadowed. Import the module and keep the qualifier: json.load, shared_memory.SharedMemory. Every call then says where it comes from, which is exactly what a reviewer scanning for tampering wants to see. The accepted exception is typing helpers (from typing import Any) — annotations would drown in qualifiers otherwise.
Practice 13 — Keep the network layer fresh
Older security guides said "never version-pin network packages — install requests, urllib3, certifi with >= so they always float". The reason behind that advice is real: the network layer is attacked more than anything else, and certifi is a dated snapshot of the certificate authorities your TLS trusts — pin it to last year and your production trust store quietly rots.
But guidance has moved on, because unpinned floats have their own failure mode: unreproducible builds, and no control over when new (possibly compromised) code arrives. The current best practice keeps both halves:
- Pin everything through a lockfile so every install is reproducible and reviewable.
- Refresh those pins frequently and automatically —
pip-auditin CI to flag known-vulnerable pins, and an update bot (Dependabot, Renovate) proposing fresh pins on a schedule, with the network layer treated as the most urgent lane.
pip-audit -r requirements.txt # fails the build on known-vulnerable pins
A date-versioned package like certifi is the canary: if its pin is months old, your update automation is broken.
Practice 14 — Build HTTP clients from one hardened factory
Many incidents begin with a carelessly constructed HTTP client: no timeout (one slow endpoint hangs the worker), verification switched off "temporarily", or a proxy environment variable silently rerouting traffic through a machine you did not choose. The fix is singular construction: one factory function builds every client, so every request inherits the same safe defaults — and a security fix lands in one place.
import httpx
def make_client() -> httpx.Client:
return httpx.Client(
timeout=httpx.Timeout(connect=1.0, read=3.0, write=3.0, pool=3.0),
verify=True, # TLS verification stays on, everywhere
trust_env=False, # ignore proxy/CA environment variables
headers={"User-Agent": "library-sync/1.0"},
)
(With requests, the equivalents are session.trust_env = False and passing timeout= on each request from a shared constant — a bare requests.Session() has no working timeout attribute, a classic copy-paste trap.) Need differently-privileged clients? Write several small factories rather than tweaking one client in place.
The one piece of this you can see from the standard library: Python's default TLS context really does verify — keep it that way.
import ssl
ctx = ssl.create_default_context()
print(ctx.verify_mode == ssl.CERT_REQUIRED, ctx.check_hostname)
True True
Practice 15 — Use more than one dependency scanner
Every scanner works from its own vulnerability feed, and no feed knows everything first. Running two (or more) different scanners meaningfully raises the odds that a bad package is caught before it ships — this is the pre-commit ring from Practice 2, widened:
pip-audit -r requirements.txt # dependency CVEs, from the PyPA advisory DB
bandit -r src/ # dangerous patterns in your own code
Add a second dependency feed with different coverage — OWASP Dependency-Check, Snyk, or Safety — and let them disagree; the union of their findings is the point. Commercial feeds are often faster with fresh advisories, and that speed is usually worth paying for.
🧪 Quick quiz — answer from memory, then check.
- A lookup function returns
Nonewhen the record is missing because of corrupt data. Why is that worse than raising, and what should it raise? - The last-resort decorator logs a full traceback but shows the caller only "internal error". Which two earlier practices is it combining?
- What is the one non-negotiable rule where SQL meets user input — and what does an ORM add on top of it?
- Why are conditional imports a security smell rather than just a style issue?
- Your lockfile pins
certififrom fourteen months ago. What is quietly going wrong, and what is the modern fix? - A platform difference makes some conditional import genuinely unavoidable. What is the one acceptable way to handle it?
- What risk does
from somepackage import somethingcarry thatimport somepackagedoes not? - Beyond the certificate store, why are out-of-date packages a risk in themselves?
Show the answers
- The
Nonetravels on as if it were a result and the crash surfaces far from the cause (the executed example blows up onurl.upper()); corrupt data deserves a named exception at the source — hereMissingCardError, raised exactly where the bad state is discovered. - Fail conspicuously (from the five fail disciplines: the full detail goes to the log, where a cluster of entries can reveal an attack) and never raise a bare
Exception(Practice 7: the caller gets a namedLastResortErrorcarrying no internals). - Never glue user text into the SQL string — pass it as a parameter (
?), as the executed demo shows hostile input matching nothing. An ORM then adds defaults that parameterize for you, typed queries, and one home for schema knowledge — but it is a layer, not immunity; its raw-SQL escape hatches can still be injected. - Because they make development and production capable of running different code: the
except ImportErrorbranch that never runs on your laptop is the one that ships, and nobody reviewed the path that actually executes. - Your production trust store is aging —
certifiis a dated snapshot of certificate authorities, so stale pins mean stale trust decisions. Keep the lockfile for reproducibility, but refresh it automatically and often:pip-auditin CI plus an update bot, with network packages treated as the most urgent lane. - Isolate it in one small, dedicated compatibility module — a compact sub-package whose only job is choosing the adapter — so the rest of the codebase imports one unambiguous name and the maybe-logic lives in a single reviewed place.
- Name collision: the imported object lands unqualified in your namespace, where a later definition (or a hostile shadow) can silently replace it — the executed demo swapped out
json.loadwithout a single warning. The package-qualified call survives. - They accumulate known vulnerabilities: every advisory published after your pin is a hole you are still shipping, already documented for any attacker who checks your versions. Fresh pins via automated updates close them as they are found.
Exercises
Write each answer as a function and call it at the bottom with the sample values so the file runs on its own.
Exercise 1: Line-of-sight library card
Scenario: A library counter program decides whether a member can borrow a book.
What to do: This nested version works — rewrite it in line-of-sight style (no else, every guard beside its exit), then print the three calls shown.
def can_borrow(card_ok, on_shelf, fines):
if card_ok:
if on_shelf:
if fines == 0:
return "borrowed"
else:
return "pay your fines first"
else:
return "not on the shelf"
else:
return "card expired"
Sample output:
borrowed
pay your fines first
card expired
💡 Hint: Reverse each condition (if not card_ok:) and return immediately; "borrowed" should be the flush-left last line.
Show a solution
def can_borrow(card_ok, on_shelf, fines):
if not card_ok:
return "card expired"
if not on_shelf:
return "not on the shelf"
if fines > 0:
return "pay your fines first"
return "borrowed"
print(can_borrow(True, True, 0))
print(can_borrow(True, True, 50))
print(can_borrow(False, True, 0))
Exercise 2: An error message that doesn't leak
Scenario: Your app failed to load its config file and currently shows the full server path to the user.
What to do: Write report_missing(path) that logs the real path at ERROR level (use logging.basicConfig(stream=sys.stdout, format="%(levelname)s %(message)s") so the log is visible here) and returns a safe user-facing message containing a support code instead of the path. Print report_missing("/srv/app/secret-config.toml").
Sample output:
ERROR config not found at /srv/app/secret-config.toml
Could not load settings. Contact support with code CFG-404.
💡 Hint: Fail conspicuously — all the detail goes to the log line, none of it to the returned message.
Show a solution
import logging, sys
logging.basicConfig(stream=sys.stdout, format="%(levelname)s %(message)s")
def report_missing(path):
logging.error("config not found at %s", path)
return "Could not load settings. Contact support with code CFG-404."
print(report_missing("/srv/app/secret-config.toml"))
Exercise 3: Fail-fast withdrawal
Scenario: A wallet app must reject bad withdrawals before touching the payment system.
What to do: Write withdraw(balance, amount) that raises ValueError("amount must be positive") for amounts of zero or less and ValueError("insufficient balance") when the amount exceeds the balance, and otherwise returns the new balance. Print withdraw(500, 200), then catch and print the rejections for amounts 0 and 900.
Sample output:
300
rejected: amount must be positive
rejected: insufficient balance
💡 Hint: Two guards at the top, the normal return flush left at the bottom — fail fast and line-of-sight in one function.
Show a solution
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("amount must be positive")
if amount > balance:
raise ValueError("insufficient balance")
return balance - amount
print(withdraw(500, 200))
for bad in (0, 900):
try:
withdraw(500, bad)
except ValueError as error:
print("rejected:", error)
Exercise 4: Retire an eval
Scenario: A settings loader currently does eval(text) to parse values like "[8080, 8081]" from a config file — which means the config file can run code.
What to do: Write load_setting(text) that parses the text with ast.literal_eval and raises ValueError("setting must be a plain Python literal") for anything that is not a literal (catch both ValueError and SyntaxError from the parse). Print load_setting("[8080, 8081]"), then catch and print the rejection for '__import__("os").getcwd()'.
Sample output:
[8080, 8081]
rejected: setting must be a plain Python literal
💡 Hint: from ast import literal_eval — it already refuses anything executable; your job is just the clean error message.
Show a solution
from ast import literal_eval
def load_setting(text):
try:
value = literal_eval(text)
except (ValueError, SyntaxError):
raise ValueError("setting must be a plain Python literal")
return value
print(load_setting("[8080, 8081]"))
try:
load_setting('__import__("os").getcwd()')
except ValueError as error:
print("rejected:", error)
Exercise 5: One exception per failure state
Scenario: A checkout function currently raises bare Exception for every problem, so callers cannot tell "empty cart" from "wrong argument".
What to do: Define CartEmptyError(Exception) with a docstring describing its failure state. Write checkout(cart) that raises TypeError("cart must be a list of item names") when cart is not a list, raises CartEmptyError("add something to the cart first") when it is empty, and otherwise returns f"charged for {len(cart)} items". Print the success for ["tea", "vada pav"], then catch each failure specifically for [] and "tea".
Sample output:
charged for 2 items
empty cart: add something to the cart first
bad call: cart must be a list of item names
💡 Hint: Two except clauses at the call site — one per failure state — is the whole point: the caller reacts to each condition by name.
Show a solution
class CartEmptyError(Exception):
"""Raised when checkout is attempted on an empty cart."""
def checkout(cart):
if not isinstance(cart, list):
raise TypeError("cart must be a list of item names")
if not cart:
raise CartEmptyError("add something to the cart first")
return f"charged for {len(cart)} items"
print(checkout(["tea", "vada pav"]))
for bad in ([], "tea"):
try:
checkout(bad)
except CartEmptyError as error:
print("empty cart:", error)
except TypeError as error:
print("bad call:", error)
Exercise 6: The withdrawal that ran shell commands
Scenario: A banking helper computes a withdrawal by building the arithmetic as a string and running it through eval — so a crafted account_balance like "__import__('os').system('echo attacked')" executes as code instead of failing as a bad number:
def withdrawal_calculation(account_balance, withdrawal, tax_percent, service_fee, fee_exemption):
tax = 0
if tax_percent > 0:
tax = withdrawal * tax_percent
if fee_exemption:
return eval("%s - (%s + %s)" % (account_balance, withdrawal, tax))
return eval("%s - (%s + %s + %s)" % (account_balance, withdrawal, tax, service_fee))
What to do: Rewrite it with no eval at all: cast account_balance with int() (attacker text must now raise ValueError) and write the arithmetic as arithmetic. Print the result for a balance of "200", a withdrawal of 100 at 0.05 tax with a fee exemption, then the same without the exemption and a service fee of 10, then catch and print the rejection for the attack string above.
Sample output:
95.0
85.0
rejected: invalid literal for int() with base 10: "__import__('os').system('echo attacked')"
💡 Hint: The eval string was only ever computing balance - (withdrawal + tax [+ service_fee]). Write that expression directly — the int() cast is your fail-fast gate, exactly like Exercise 3.
Show a solution
def withdrawal_calculation(account_balance: str, withdrawal: int, tax_percent: float,
service_fee: int, fee_exemption: bool) -> float:
balance = int(account_balance)
tax = 0
if tax_percent > 0:
tax = withdrawal * tax_percent
if fee_exemption:
return balance - (withdrawal + tax)
return balance - (withdrawal + tax + service_fee)
print(withdrawal_calculation("200", 100, 0.05, 0, True))
print(withdrawal_calculation("200", 100, 0.05, 10, False))
try:
withdrawal_calculation("__import__('os').system('echo attacked')", 100, 0.05, 0, True)
except ValueError as error:
print("rejected:", error)
Exercise 7: The search that read the whole shelf
Scenario: A catalogue search builds its query by gluing the user's title into the SQL — so a crafted search like anything' OR '1'='1 returns every book on every shelf instead of nothing.
What to do: Build an in-memory sqlite3 table books (title, shelf) with two rows, write find_book(title) using a ? parameter, and print a normal lookup followed by the hostile input — which must now match nothing.
Sample output:
[('Deep Work', 'B-2')]
[]
💡 Hint: The driver does the quoting when the value travels separately: db.execute("... WHERE title = ?", (title,)) — note the one-element tuple.
Show a solution
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE books (title TEXT, shelf TEXT)")
db.executemany("INSERT INTO books VALUES (?, ?)",
[("Deep Work", "B-2"), ("Clean Code", "B-3")])
def find_book(title):
return db.execute("SELECT title, shelf FROM books WHERE title = ?",
(title,)).fetchall()
print(find_book("Deep Work"))
print(find_book("anything' OR '1'='1"))
Exercise 8: The user that was never created
Scenario: A registration helper builds the User first and quietly returns None when the id is missing — a failure dressed as a value. A common wrong "fix" is return UserObjectError(...), which hands the caller an un-raised exception object and stops nothing.
def create_user_before(id, name, phone_number):
new_user = User(id, name, phone_number)
if id is None:
return None # the caller sails on with nothing
return new_user
What to do: Define a User class and a docstringed UserObjectError, then rewrite create_user(id, name, phone_number) so a None id raises UserObjectError("invalid user object") before any User is built. Print the id of a successful creation, then catch and print the rejection.
Sample output:
u-1
rejected: invalid user object
💡 Hint: raise, not return — returning an exception object creates it and passes it along like any value; only raise stops execution. And validate before constructing: the guard goes first, following the fail-fast discipline.
Show a solution
class User:
def __init__(self, id, name, phone_number):
self.id, self.name, self.phone_number = id, name, phone_number
class UserObjectError(Exception):
"""Raised when a user record is invalid."""
def create_user(id, name, phone_number):
if id is None:
raise UserObjectError("invalid user object")
return User(id, name, phone_number)
print(create_user("u-1", "asha", "555-0100").id)
try:
create_user(None, "asha", "555-0100")
except UserObjectError as error:
print("rejected:", error)
🧪 Quick quiz — answer from memory, then check.
- A teammate says defensive programming and secure coding are the same thing. What is the difference, and why do you want both?
- In one sentence: how does following the Zen of Python make a program more secure?
- What does line-of-sight style ask of a function?
- Someone argues that hard-to-read code is safer, because attackers cannot follow it either. What is wrong with that argument?
- A function receives input you do not control. What is its first line of defense?
- What do type annotations and docstrings have in common as security tools?
- Why is raising a specific exception (built-in or custom) better for security than raising
Exception? - Why should every HTTP client in an application come from one factory function?
- Why run more than one dependency scanner?
Show the answers
- Defensive programming anticipates what goes wrong at runtime and keeps the program standing (validate, handle, clean up); secure coding uses the language's constructs so an attacker gets the smallest possible surface (no leaked internals, no unreviewable nesting). One without the other still fails: merely defensive code can leak secrets, merely "secure" code can fall over on the first malformed request.
- It pushes you toward flat, simple, explicit code — and vulnerabilities hide in complexity, so code that one person can read end to end is code that can actually be reviewed and secured.
- That a reader's eyes can travel straight down: guard clauses raise or return early at the top, indentation stays shallow, and the normal result sits flush left on the last line.
- Obscurity does not stop attackers — they have time and tools; it stops reviewers. The security win comes from code being read, understood, and fixed, so unreadable code helps exactly the wrong side.
- Validate the input before any expensive or dangerous work (fail fast), and handle the rejection deliberately — a clean message to the caller, the detail to the log, at the right severity.
- Both force a second, deliberate pass over your own function (its shapes, its meaning, its failure states) and both hand the next developer what they need to change the code without breaking its assumptions — misunderstood code is where refactors introduce vulnerabilities.
- A specific exception names the failure state, so callers react to exactly the condition they can handle and logs can be filtered by failure type; a bare
Exceptionforces catch-everything handling and turns every incident into an investigation. - Because the dangerous mistakes — a missing timeout, verification switched off, a proxy variable silently rerouting traffic — happen when clients are built by hand, one call site at a time; a single factory applies the safe defaults everywhere and gives a security fix exactly one place to land.
- Each scanner works from its own vulnerability feed and none knows everything first; two different feeds disagree usefully, and the union of their findings catches bad packages earlier.
Key takeaways
- Defensive programming anticipates what goes wrong at runtime; secure coding uses the language so attackers get nothing to work with. Build both habits.
- Choose how you fail: fast (validate before expensive work), safe (
withcleans up), conspicuously (detail to logs, nothing to users), appropriately (layer severities, keepCRITICALrare), creatively (not everything raises). - The Zen of Python is a security checklist in disguise — flat, explicit, singular code is reviewable code, and the six refactor triggers tell you when a function has outgrown safety.
- Automate style: formatter, linter, type checker, and unit tests on save; dependency audit, security linter, and integration tests before commit — so human review spends itself on logic, not commas.
- Line-of-sight style — early exits, guards beside their raises, the success path flush left on the last line — makes code easier to read, and code that is easier to read is easier to secure.
- A failure should never travel dressed as a value: replace empty returns with named exceptions, and put a last-resort decorator on entry points — full detail to the log, an information-free named error to the caller.
- Where SQL meets user input, parameters are non-negotiable; an ORM adds a helpful layer on top but is not immunity.
- Imports are a security boundary: absolute only, never conditional, keep names package-qualified, and scan everything you depend on — with at least two scanners, since no feed knows everything first.
- Pin dependencies through a lockfile for reproducibility, but refresh the pins automatically and often — a stale
certifiis a rotting trust store — and build every HTTP client from one hardened factory (explicit timeouts, verification on, environment proxies ignored). - Annotate everything (
str | None, aliased generics, received values too): annotations are documentation plus tripwires for the type checker — not runtime enforcement. - A full docstring (summary, args, returns, raises) is your second pass over the failure states; types stay in the annotations, and a comment explaining your own code is a refactor signal.
evalandexecnever belong in a codebase — attacker text reaches__import__and the whole system; turn text into data withast.literal_evalorjson.loadsinstead.- Raise the most specific exception that fits (built-in first, one docstringed custom class per failure state, defined near its use); a blanket
except Exceptiononly ever logs and re-raises.