Module 05 · Lesson 5.2
Following Existing Conventions
On this page
- What you will learn
- What a coding convention is
- Worked scenario: how create_order already rejects orders
- How to find the conventions in a codebase
- Extending the pattern: the new rule in the same style
- When to follow, depart or leave an oddity alone
- Teaching an assistant your conventions
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
When you move into a new flat, you quickly learn where the spoons live. If you put yours in a different drawer, nobody can find them. Code is the same. A team has habits for naming, errors, messages and tests. A change that follows those habits is easy to find, read and trust.
In this lesson you learn to spot the habits in code you did not write and to extend them instead of inventing your own. The example continues with the fictional Tidewell Wholesale and its minimum order value rule, as planned in Planning a Small Change. The company and data are invented.
What you will learn
- Name the conventions in a piece of code by looking at its nearest neighbours.
- Extend an existing pattern, such as how errors and messages are raised, instead of adding a new one.
- Decide when to follow, when to depart and when to leave an oddity alone.
- Tell an assistant which conventions to copy, so that its code fits in.
Before you start
- A plan with acceptance criteria and an edit list, as made in Planning a Small Change.
- Basic Python reading skills. You do not need Django for the examples.
What a coding convention is
A convention is a habit that a team follows without a rule forcing it. Nobody wrote it down, yet nearly every file obeys it. You learn it by looking, not by reading a manual.
- Convention
- A shared habit about how things are done here, such as where messages are stored. It is like the spoon drawer: the exact place does not matter, but everyone must agree on it.
- Pattern
- A way of solving a repeated problem. For example, 'stop an order by raising one known kind of error with a code and a message'.
- Nearest neighbour
- The existing code that does the most similar job to yours. Copying its shape is the fastest way to fit in.
- Exception
- An error that stops normal flow and carries a message to whoever can handle it. Raising one is like pulling a cord that stops the train.
Why bother? A new pattern costs the whole team. Reviewers must learn it. The next developer must choose between the old way and yours. And callers that already handle the old pattern will miss yours, which is how bugs get in.
Worked scenario: how create_order already rejects orders
You need to reject small orders. Before writing anything, look at how create_order already rejects an order today. This is a simplified version of the service's code, so you can run it without Django. It is the code before the change.
from invoicing.totals import price_order
from orders import messages
class OrderRejected(Exception):
"""Raised when an order must not be created. The portal shows `message`."""
def __init__(self, code, message):
super().__init__(message)
self.code = code
self.message = message
def create_order(customer, lines, source, *, stock, store):
for line in lines:
if stock.get(line.sku, 0) < line.qty:
raise OrderRejected(
"out_of_stock",
messages.OUT_OF_STOCK.format(sku=line.sku),
)
totals = price_order(lines, customer.band)
order = store.save(
{"account": customer.account, "source": source, "goods": totals["goods"]}
)
store.queue_confirmation(order)
return orderBefore the change. The simplified create_order.
OrderRejectedis the one error for 'this order must not be created'. It carries a shortcodefor programs and amessagefor people.- The stock loop raises
OrderRejectedwith the codeout_of_stockas soon as a line cannot be met. price_orderworks out the goods total. Nothing is saved yet.store.saveandstore.queue_confirmationstand in for the real database write and the confirmation task.
Now search to see whether this is a habit or a one-off. Three quick searches answer it. Each is a plain text search over the files that git tracks.
$ git grep -n "OrderRejected" -- "*.py"
orders/services.py:5:class OrderRejected(Exception):
orders/services.py:17: raise OrderRejected(
tests/orders/test_services.py:6:from orders.services import OrderRejected, create_order
tests/orders/test_services.py:49: with pytest.raises(OrderRejected) as caught:
$ git grep -n "messages\." -- "*.py"
orders/services.py:19: messages.OUT_OF_STOCK.format(sku=line.sku),
$ git grep -n "def make_\|def stock\|def store" -- tests
tests/orders/test_services.py:23:def make_customer():
tests/orders/test_services.py:31:def make_line():
tests/orders/test_services.py:39:def store():
tests/orders/test_services.py:44:def stock():In the real service the first search shows many more hits. Even this small sample is enough to read three conventions.
| Convention | What we saw | How the new rule follows it |
|---|---|---|
| Rejecting an order | raise OrderRejected(code, message) | The new rule raises OrderRejected with the code below_minimum. No new error type. |
| Customer messages | Text lives as a constant in orders/messages.py and is filled in with .format(...) | BELOW_MINIMUM goes in the same file, with the same .format style. |
| Where checks happen | Checks run in create_order before store.save | The new check also runs before the save, after the total is known. |
| Tests | tests/orders/test_services.py, with the fixtures make_customer, make_line, store and stock | New tests go in the same file and reuse the same fixtures. |
How to find the conventions in a codebase
Step 1: Find the nearest neighbour
Ask what the existing code does that most resembles your change. For a new rejection rule, it is the existing rejection. Open it and read it closely.
What you should see: One or two files or functions to copy the shape of.
Step 2: Search for the same pattern elsewhere
Use a text search for the error name, the helper or the constant style. One hit is a habit of one person. Many hits are a convention.
What you should see: A count and a list of places where the pattern appears.
Step 3: Read the tests that sit next to it
Tests show the vocabulary the team uses. Look at test names, the helper fixtures and how they check an error.
What you should see: Names of fixtures to reuse and a test layout to match.
Step 4: Check the tool settings
Look for files that set style automatically, such as a formatter or linter settings in
pyproject.toml. If the tool decides the style, run it and stop arguing.What you should see: A list of automatic checks to run before you commit.
Step 5: Look at how similar changes were made before
Run
git logon the nearest neighbour to see what a past change touched. Note which files travelled together, such as code, message and test.What you should see: A picture of the usual shape of a change like yours.
Step 6: Write the conventions down
Put the list in your notes or pull request. If you plan to depart from one, say so there and give the reason.
What you should see: A short conventions list with any departures marked.
- Nearest neighbour
The most similar code
- Search
How many places use it
- Tests
Fixtures and names
- Tool settings
Formatter and linter
- Write it down
Note any departure
Look, count, read the tests, check the tools, then record.
Extending the pattern: the new rule in the same style
Here is the new message, added beside the old one. It uses a constant and .format, just like OUT_OF_STOCK.
OUT_OF_STOCK = "Sorry, {sku} is out of stock."
BELOW_MINIMUM = (
"Orders on a Standard account must be at least £{minimum} "
"before VAT and delivery. Your basket is £{basket}."
)After the change. One constant added, nothing renamed.
And here is the rule in create_order, placed after price_order and before the save. This block shows the check only. The rest of the function is unchanged. The min_order_sources switch is explained in Feature Flags and Staged Rollout.
if (
source in min_order_sources
and source not in EXEMPT_SOURCES
and customer.band.lower() == "standard"
and totals["goods"] < MIN_ORDER_VALUE
):
if source == "edi":
logger.warning(
"Rejected EDI order below minimum: account=%s", customer.account
)
raise OrderRejected(
"below_minimum",
messages.BELOW_MINIMUM.format(
minimum=MIN_ORDER_VALUE, basket=f"{totals['goods']:.2f}"
),
)The new check, lines 34 to 49 of the finished file.
What each part does
source in min_order_sourcesmakes the rule apply only to the sources that the switch turns on.source not in EXEMPT_SOURCESkeepsreplayexempt, even if someone adds it to the switch by mistake.customer.band.lower() == "standard"compares the band ignoring letter case, as agreed. It does not editprice_order.totals["goods"] < MIN_ORDER_VALUEis strict. Exactly £75.00 is accepted.- The log line records the account code only, never an email or a name.
raise OrderRejected("below_minimum", ...)is the same pattern asout_of_stock: a code, then a message built from a constant.
The new tests reuse make_customer and make_line and check the error in the same way as the old stock test. Here is the test for the message.
def test_portal_message_shows_the_basket_amount(
make_customer, low_basket, store, stock, rule_on
):
with pytest.raises(OrderRejected) as caught:
create_order(
make_customer(), low_basket, "portal",
stock=stock, store=store, min_order_sources=rule_on,
)
assert caught.value.message == (
"Orders on a Standard account must be at least £75.00 "
"before VAT and delivery. Your basket is £62.40."
)A new test in the existing style.
When to follow, depart or leave an oddity alone
Following conventions does not mean copying every mistake. It means choosing on purpose. Use this table when you meet something you would not have written yourself.
| Situation | What to do | Example here |
|---|---|---|
| A clear convention that works | Follow it. | Use OrderRejected and a constant in messages.py. |
| A convention that is wrong for your case, and you have a reason | Depart, keep it small, and say so in the pull request. | The new rule compares the band ignoring case, though price_order compares it exactly. The agreed criteria require it. |
| An oddity next to your change that is not part of it | Leave it. Write it down and raise it separately. | The case-sensitive band check and the £7.50 charge in price_order stay as they are. |
| Two conventions that disagree | Ask the owners, or copy the newer and more common one. | If half the code uses ValueError, ask which pattern the team wants for new code. |
Teaching an assistant your conventions
An assistant writes code in the common style of the internet. It does not know your habits unless you show them. Paste the nearest neighbour, the messages file and one existing test, and say 'match these'. Then check that it did.
class MinimumOrderError(ValueError):
pass
def create_order(customer, lines, source, *, stock, store):
...
if goods < 75:
raise MinimumOrderError(f"Order too small: {goods}")Illustrative only: a typical reply when no example was pasted. Not run.
This looks fine and would run. But it adds a second error type that callers do not catch, writes the message in the code instead of in messages.py, hard-codes 75 and gives no code. The portal would show a server error instead of a friendly message. Ask the assistant to redo it using OrderRejected and a constant, or write the small change yourself.
For more on what to paste, see Giving AI Coding Assistants Useful Context. The next lesson, Directing an Assistant on a Bounded Task, turns this into a full task brief.
Conclusion and your next step
You read the conventions from the code: one rejection error with a code and a message, constants for text, checks before the save, and tests with shared fixtures. Then you extended each one instead of adding your own. Where you departed, on the band comparison, you said so, and you left the nearby oddities alone.
Your next step: with the plan and the conventions in hand, you are ready to ask an assistant for help. Continue with Directing an Assistant on a Bounded Task and learn to brief it, and to review its diff line by line.
Further reading: the Glossary of AI Engineering and Agent Terms explains terms used in this module. The blog post AI Code Review: Catching Bugs Before They Ship shows what to look for when code arrives from an assistant.
Reusable prompt
Conventions finder
Asks an assistant to list the conventions in code you paste, with a quoted example for each, so that your change can match them.
I am about to add a small rule to an existing Python service. I want my change to match the team's habits. Act as a careful reader, not an authority.
Below are three things from the codebase. Use ONLY this material.
--- orders/services.py (create_order) ---
(paste source)
--- orders/messages.py ---
(paste source)
--- tests/orders/test_services.py (one existing test and the fixtures it uses) ---
(paste source)
Produce:
1. A table of conventions you can see: how errors are raised, where message text lives, where checks happen, how tests are built. For each, quote the exact line that shows it.
2. For each convention, say whether the code gives one example or several. If only one, say "one example, not confirmed as a habit".
3. Anything in this code that looks like an oddity or a bug that I should NOT copy. Do not fix it.
4. A list of other files I should look at to confirm a convention.
Then say what you could not tell from this material.Show the reusable template
Replace each {{placeholder}} with your own details.
I am about to add a small rule to an existing {{language}} service. I want my change to match the team's habits. Act as a careful reader, not an authority.
Below are three things from the codebase. Use ONLY this material.
{{nearest_neighbour_source}}
{{messages_or_constants_source}}
{{one_existing_test_and_its_fixtures}}
Produce:
1. A table of conventions you can see: how errors are raised, where message text lives, where checks happen, how tests are built. For each, quote the exact line that shows it.
2. For each convention, say whether the code gives one example or several. If only one, say "one example, not confirmed as a habit".
3. Anything in this code that looks like an oddity or a bug that I should NOT copy. Do not fix it.
4. A list of other files I should look at to confirm a convention.
Then say what you could not tell from this material.Expected output and limitations
A table of conventions, each with a quoted line and a note on how many examples it saw; a short list of oddities not to copy; a list of files to check; and an honest note of what the pasted code could not show.
Conventions
1. Rejecting an order: raise OrderRejected(code, message). Quote: raise OrderRejected("out_of_stock", messages.OUT_OF_STOCK.format(sku=line.sku)). One example, not confirmed as a habit.
2. Message text: constants in orders/messages.py, filled with .format. Quote: OUT_OF_STOCK = "Sorry, {sku} is out of stock." One example.
3. Order of work: checks before store.save. Quote: the stock loop comes before store.save(...).
4. Tests: pytest fixtures make_customer, make_line, store, stock; errors checked with pytest.raises(OrderRejected).
Do not copy
- price_order compares the band with == "Standard", which is case-sensitive. Looks like an oddity. Not part of this change.
Files to check
- git grep -n "OrderRejected" to see how many places raise it, and where the portal catches it.
Could not tell
- How the portal view turns OrderRejected into a response. The view was not pasted.Limitations to keep in mind
- One example is not a convention. Confirm with a search across the repository.
- The assistant sees only what you paste. A convention used in files you did not paste stays hidden.
- It may call something an oddity that is a deliberate rule, or the other way round. Ask a person who knows.
- Style that a tool enforces, such as a formatter's layout, should come from the tool, not from the assistant.
Common errors and how to fix them
Adding a new error type or helper for a one-off need
Why it happens: The existing pattern was not looked at, or it seemed old-fashioned.
Fix: Find the nearest neighbour and reuse its error type, constant style and fixtures. Propose a better pattern separately.
Copying an oddity because it is nearby
Why it happens: The case-sensitive band check looked like the house style.
Fix: Treat it as a question. Decide on purpose, follow the agreed criteria, and note the departure.
Reformatting a file while adding to it
Why it happens: An editor setting or an assistant rewrote the layout of lines you did not mean to touch.
Fix: Use the project's formatter only on your lines, or turn off format on save. Check the diff for lines that changed but do not matter.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
List and follow the conventions in your repository
In a repository you may work on, find the nearest neighbour of a small change you plan. List its conventions with quoted evidence, then write the new code or a sketch of it so that it follows them.
You will need
- A repository you are allowed to read, with tests.
- A small planned change, such as a new validation rule or a new message.
- The prompt template from this lesson, if your rules allow its use with your code.
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- Search for the name of the error or helper, and count the hits.
- Check the formatter or linter settings in the project's config file before you argue about layout.
- If the repository has no tests, use the way errors are reported to users as your convention source.
Show a model answer
A strong answer starts from the nearest neighbour, for example the existing check that raises an error, and quotes it. It confirms the habit with a search that shows several hits and says how many. It names the fixtures that tests reuse. In the new code, it raises the same error type with a code and a message from the shared messages file. It also lists one oddity it noticed, such as a strict comparison or a magic number, and says it was left alone and why. A weak answer lists general good practice, such as 'use clear names', without a single quoted line or search result.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. Callers already catch OrderRejected, so reusing it means the new rule is handled for free. A new class is tempting because it looks tidier, but callers would not catch it. Returning a string breaks the pattern, and checking in the view would miss the EDI and replay callers.
Show the answer and explanation
Answer: B. One example may be one person's habit or a mistake. Several examples across files suggest a real convention. Calling it a mistake without checking is as hasty as calling it a rule.
Show the answer and explanation
Answer: C. A departure is fine when it is deliberate and explained. Editing price_order would pull a separate pricing decision into this change, and staying silent leaves the reviewer to discover it. Both choices hide risk.
Frequently asked questions
What is a coding convention?
It is a shared habit about how code is written in a project, such as where messages live or how errors are raised. It is like the place where everyone keeps the spoons. Following it makes code easy to find and read.
What if the existing style is bad?
Follow it in your small change, and raise a separate proposal to improve it. Mixing a new style into one change leaves the code with two ways of doing the same thing. Improving everything at once is a different job with its own review.
How do I find the conventions fast?
Open the code that is most like your change and search for its error type or helper to count how often it appears. Then read the tests beside it. These two steps usually show you the style in a few minutes.
Should I run a formatter on the whole file?
No. A formatter that rewrites lines you did not change makes the diff noisy and hides the real change. Format only your own lines, or make a separate formatting-only change that is reviewed alone.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- How to use fixtures - pytest documentation(opens in a new tab)
pytest · Official documentation · How fixtures such as make_customer are defined and reused. This is specific to pytest.
- logging — Logging facility for Python(opens in a new tab)
Python Software Foundation · Official documentation · The standard logging module behind the log line in the EDI rejection.
- Django settings | Django documentation(opens in a new tab)
Django Software Foundation · Official documentation · How Django settings files work. Check the version you use.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.