Picture by Creator
# Introduction
AI coding instruments are getting impressively good at writing Python code that works. They will construct complete functions and implement complicated algorithms in minutes. Nevertheless, the code AI generates is usually a ache to take care of.
If you’re utilizing instruments like Claude Code, GitHub Copilot, or Cursor’s agentic mode, you could have most likely skilled this. The AI helps you ship working code quick, however the price reveals up later. You’ve possible refactored a bloated perform simply to know the way it works weeks after it was generated.
The issue is not that AI writes dangerous code — although it generally does — it’s that AI optimizes for “working now” and finishing the necessities in your immediate, when you want code that’s readable and maintainable in the long run. This text reveals you the way to bridge this hole with a deal with Python-specific methods.
# Avoiding the Clean Canvas Lure
The most important mistake builders make is asking AI to start out from scratch. AI brokers work finest with constraints and pointers.
Earlier than you write your first immediate, arrange the fundamentals of the undertaking your self. This implies selecting your undertaking construction — putting in your core libraries and implementing just a few working examples — to set the tone. This may appear counterproductive, however it helps with getting AI to put in writing code that aligns higher with what you want in your software.
Begin by constructing a few options manually. If you’re constructing an API, implement one full endpoint your self with all of the patterns you need: dependency injection, correct error dealing with, database entry, and validation. This turns into the reference implementation.
Say you write this primary endpoint manually:
from fastapi import APIRouter, Relies upon, HTTPException
from sqlalchemy.orm import Session
router = APIRouter()
# Assume get_db and Consumer mannequin are outlined elsewhere
async def get_user(user_id: int, db: Session = Relies upon(get_db)):
consumer = db.question(Consumer).filter(Consumer.id == user_id).first()
if not consumer:
increase HTTPException(status_code=404, element="Consumer not discovered")
return consumer
When AI sees this sample, it understands how we deal with dependencies, how we question databases, and the way we deal with lacking information.
The identical applies to your undertaking construction. Create your directories, arrange your imports, and configure your testing framework. AI shouldn’t be making these architectural selections.
# Making Python’s Sort System Do the Heavy Lifting
Python’s dynamic typing is versatile, however that flexibility turns into a legal responsibility when AI is writing your code. Make sort hints important guardrails as a substitute of a nice-to-have in your software code.
Strict typing catches AI errors earlier than they attain manufacturing. While you require sort hints on each perform signature and run mypy in strict mode, the AI can not take shortcuts. It can not return ambiguous varieties or settle for parameters that is likely to be strings or is likely to be lists.
Extra importantly, strict varieties power higher design. For instance, an AI agent attempting to put in writing a perform that accepts information: dict could make many assumptions about what’s in that dictionary. Nevertheless, an AI agent writing a perform that accepts information: UserCreateRequest the place UserCreateRequest is a Pydantic mannequin has precisely one interpretation.
# This constrains AI to put in writing right code
from pydantic import BaseModel, EmailStr
class UserCreateRequest(BaseModel):
identify: str
e mail: EmailStr
age: int
class UserResponse(BaseModel):
id: int
identify: str
e mail: EmailStr
def process_user(information: UserCreateRequest) -> UserResponse:
cross
# Quite than this
def process_user(information: dict) -> dict:
cross
Use libraries that implement contracts: SQLAlchemy 2.0 with type-checked fashions and FastAPI with response fashions are wonderful selections. These usually are not simply good practices; they’re constraints that preserve AI on observe.
Set mypy to strict mode and make passing sort checks non-negotiable. When AI generates code that fails sort checking, it’ll iterate till it passes. This computerized suggestions loop produces higher code than any quantity of immediate engineering.
# Creating Documentation to Information AI
Most tasks have documentation that builders ignore. For AI brokers, you want documentation they really use — like a README.md file with pointers. This implies a single file with clear, particular guidelines.
Create a CLAUDE.md or AGENTS.md file at your undertaking root. Don’t make it too lengthy. Give attention to what is exclusive about your undertaking quite than basic Python finest practices.
Your AI pointers ought to specify:
- Challenge construction and the place several types of code belong
- Which libraries to make use of for frequent duties
- Particular patterns to comply with (level to instance information)
- Express forbidden patterns
- Testing necessities
Right here is an instance AGENTS.md file:
# Challenge Tips
## Construction
/src/api - FastAPI routers
/src/companies - enterprise logic
/src/fashions - SQLAlchemy fashions
/src/schemas - Pydantic fashions
## Patterns
- All companies inherit from BaseService (see src/companies/base.py)
- All database entry goes by means of repository sample (see src/repositories/)
- Use dependency injection for all exterior dependencies
## Requirements
- Sort hints on all features
- Docstrings utilizing Google model
- Features underneath 50 traces
- Run `mypy --strict` and `ruff verify` earlier than committing
## By no means
- No naked besides clauses
- No sort: ignore feedback
- No mutable default arguments
- No world state
The bottom line is being particular. Don’t merely say “comply with finest practices.” Level to the precise file that demonstrates the sample. Don’t solely say “deal with errors correctly;” present the error dealing with sample you need.
# Writing Prompts That Level to Examples
Generic prompts produce generic code. Particular prompts that reference your present codebase produce extra maintainable code.
As an alternative of asking AI to “add authentication,” stroll it by means of the implementation with references to your patterns. Right here is an instance of such a immediate that factors to examples:
Implement JWT authentication in src/companies/auth_service.py. Observe the identical construction as UserService in src/companies/user_service.py. Use bcrypt for password hashing (already in necessities.txt).
Add authentication dependency in src/api/dependencies.py following the sample of get_db.
Create Pydantic schemas in src/schemas/auth.py much like consumer.py.
Add pytest exams in exams/test_auth_service.py utilizing fixtures from conftest.py.
Discover how each instruction factors to an present file or sample. You aren’t asking AI to construct out an structure; you might be asking it to use what you have to a brand new characteristic.
When the AI generates code, evaluate it towards your patterns. Does it use the identical dependency injection strategy? Does it comply with the identical error dealing with? Does it arrange imports the identical method? If not, level out the discrepancy and ask it to align with the prevailing sample.
# Planning Earlier than Implementing
AI brokers can transfer quick, which may sometimes make them much less helpful if velocity comes on the expense of construction. Use plan mode or ask for an implementation plan earlier than any code will get written.
A planning step forces the AI to assume by means of dependencies and construction. It additionally provides you an opportunity to catch architectural issues — comparable to round dependencies or redundant companies — earlier than they’re carried out.
Ask for a plan that specifies:
- Which information can be created or modified
- What dependencies exist between elements
- Which present patterns can be adopted
- What exams are wanted
Overview this plan such as you would evaluate a design doc. Examine that the AI understands your undertaking construction. Confirm it’s utilizing the suitable libraries and ensure it’s not reinventing one thing that already exists.
If the plan appears to be like good, let the AI execute it. If not, right the plan earlier than any code will get written. It’s simpler to repair a foul plan than to repair dangerous code.
# Asking AI to Write Exams That Really Take a look at
AI is nice and tremendous quick at writing exams. Nevertheless, AI just isn’t environment friendly at writing helpful exams except you might be particular about what “helpful” means.
Default AI check conduct is to check the blissful path and nothing else. You get exams that confirm the code works when the whole lot goes proper, which is precisely when you do not want exams.
Specify your testing necessities explicitly. For each characteristic, require:
- Completely happy path check
- Validation error exams to verify what occurs with invalid enter
- Edge case exams for empty values, None, boundary situations, and extra
- Error dealing with exams for database failures, exterior service failures, and the like
Level AI to your present check information as examples. If in case you have good check patterns already, AI will write helpful exams, too. For those who would not have good exams but, write just a few your self first.
# Validating Output Systematically
After AI generates code, don’t simply verify if it runs. Run it by means of a guidelines.
Your validation guidelines ought to embrace questions like the next:
- Does it cross mypy strict mode
- Does it comply with patterns from present code
- Are all features underneath 50 traces
- Do exams cowl edge instances and errors
- Are there sort hints on all features
- Does it use the desired libraries accurately
Automate what you possibly can. Arrange pre-commit hooks that run mypy, Ruff, and pytest. If AI-generated code fails these checks, it doesn’t get dedicated.
For what you can not automate, you’ll spot frequent anti-patterns after reviewing sufficient AI code — comparable to features that do an excessive amount of, error dealing with that swallows exceptions, or validation logic combined with enterprise logic.
# Implementing a Sensible Workflow
Allow us to now put collectively the whole lot we’ve mentioned up to now.
You begin a brand new undertaking. You spend time establishing the construction, selecting and putting in libraries, and writing a few instance options. You create CLAUDE.md together with your pointers and write particular Pydantic fashions.
Now you ask AI to implement a brand new characteristic. You write an in depth immediate pointing to your examples. AI generates a plan. You evaluate and approve it. AI writes the code. You run sort checking and exams. Every little thing passes. You evaluate the code towards your patterns. It matches. You commit.
Whole time from immediate to commit could solely be round quarter-hour for a characteristic that will have taken you an hour to put in writing manually. However extra importantly, the code you get is simpler to take care of — it follows the patterns you established.
The following characteristic goes quicker as a result of AI has extra examples to study from. The code turns into extra constant over time as a result of each new characteristic reinforces the prevailing patterns.
# Wrapping Up
With AI coding instruments proving tremendous helpful, your job as a developer or a knowledge skilled is altering. You at the moment are spending much less time writing code and extra time on:
- Designing methods and selecting architectures
- Creating reference implementations of patterns
- Writing constraints and pointers
- Reviewing AI output and sustaining the standard bar
The ability that issues most just isn’t writing code quicker. Quite, it’s designing methods that constrain AI to put in writing maintainable code. It’s understanding which practices scale and which create technical debt. I hope you discovered this text useful even when you don’t use Python as your programming language of selection. Tell us what else you assume we will do to maintain AI-generated Python code maintainable. Maintain exploring!
Bala Priya C is a developer and technical author from India. She likes working on the intersection of math, programming, information science, and content material creation. Her areas of curiosity and experience embrace DevOps, information science, and pure language processing. She enjoys studying, writing, coding, and occasional! At the moment, she’s engaged on studying and sharing her information with the developer neighborhood by authoring tutorials, how-to guides, opinion items, and extra. Bala additionally creates partaking useful resource overviews and coding tutorials.







