Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Modules, Files and Errors

Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md

An AI tool only knows what it can read. A tiny reading-list app called Shelf shows why small, well-named modules save context, how config.py and environment variables keep keys out of the project, and what pyproject.toml, AGENTS.md and a project map prompt tell a coding tool.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Modules, Files and Errors

What you will learn

  • Explain why clear structure gives AI tools less to read and fewer reasons to guess
  • Choose a project layout: flat, package based, feature based or layered
  • Keep settings in config.py and secrets in environment variables, never in the project
  • Describe a project to AI tools with pyproject.toml, AGENTS.md and a project map prompt

Before you start

  • Python modules, packages and imports
  • uv and pyproject.toml
  • Git and .gitignore

When an AI tool opens your project, what does it find? That question decides a lot about the answers you get. A tidy project gets better help.

Think about asking a new helper to make tea in your kitchen. Everything is in one big pile, so they dig through all of it. They can't find the sugar, so they pick up a white jar and guess. It's salt. Now label the shelves, tea here, sugar there, and the helper walks straight to the right one. An AI tool is that helper. It knows nothing about your project until it reads it, and when it can't find something it guesses, and it sounds sure. That confident wrong guess is what we call a hallucination.

Reason one: context has limited room

When you ask an AI tool for help, it sends some of your code along with your question. That's called context, and there's only so much room in it (see tokens and the context window). Put the whole app in one big file and that file fills the room, though most of it has nothing to do with your question. Split it into small files with clear names, and ask to change how a book's summary is printed: a coding agent can look at the file names first, and books.py tells it where to start. Only that file rides in, and there's room left for your question and a good answer.

Context window comparison: one big app.py file fills the whole window leaving no room; with small modules, only books.py rides in, leaving room for the question and the answer one big file app.py, all of it no room left small, named modules shelf/books.py your question room for a good answer The context window: same size on both sides.
Clear structure means less to read, and fewer guesses.

Reason two: tools expect common shapes

AI tools learned from a huge amount of code, so they expect common shapes. If main.py imports config and storage from a shelf package, a tool expects settings in config and saving in storage, and it's right. Spread the same code across files called stuff, helper2 and final_new, and there's nothing to predict from. It may call a function that isn't there, or write a second copy of one that is. You won't feel this much on a tiny script, but it grows with every file, so set it up before the app gets big.

Four common layouts

LayoutWhat it meansFits
Flatall files in one foldera small script
Package basedrelated modules in a folder Python can importa small app like Shelf
Feature baseda folder per feature: users, products, billingapps that grow by feature
Layereda folder per job: models, views, templatesweb apps (FastAPI, Flask, Django)

You don't need the perfect one. Pick the one that fits the size of the project, tell the AI tool which one, and keep to it.

The Shelf project

.env.example
.gitignore
AGENTS.md
CLAUDE.md
README.md
main.py
pyproject.toml
send.py
shelf/__init__.py
shelf/books.py
shelf/config.py
shelf/storage.py
tests/__init__.py
tests/test_books.py

Each module in shelf/ has a single job, and main.py at the top only connects them:

from shelf import config, storage
from shelf.books import Book, summary

books = [
    Book("Dune", "Frank Herbert", 412),
    Book("Emma", "Jane Austen", 474),
]
storage.save(books, config.DATA_FILE)

print(config.APP_NAME, "|", config.DATA_FILE)
for book in storage.load(config.DATA_FILE):
    print(summary(book))

key = "set" if config.API_KEY else "missing"
print("API key:", key)
Shelf | books.txt
Dune by Frank Herbert (412p)
Emma by Jane Austen (474p)
API key: missing

books.py holds the data and one function:

from dataclasses import dataclass


@dataclass
class Book:
    title: str
    author: str
    pages: int


def summary(book: Book) -> str:
    b = book
    return f"{b.title} by {b.author} ({b.pages}p)"

When you ask for a change, you and the tool both know where it goes.

Consistent names

You know PEP 8 from the OOP section, and it pays off again. Book is a class, so PascalCase; summary is a function, so snake_case; APP_NAME is a constant, so capitals. File names count too: books, storage and config each say what's inside, and utils2 says nothing. AI tools copy what they see, so consistent names lead to matching code. Put one line in your first prompt: "use PEP 8 naming". Later, a linter can check the whole project for you.

Settings in one place: config.py

import os

APP_NAME = "Shelf"
DATA_FILE = os.environ.get("SHELF_DATA", "books.txt")
API_KEY = os.environ.get("SHELF_API_KEY")


def require_key() -> str:
    if API_KEY is None:
        raise RuntimeError("Set SHELF_API_KEY first")
    return API_KEY

Every other file asks config, and nothing else reads the environment. An environment variable is a value that sits outside your code, in your shell. Run main.py with SHELF_DATA=my_books.txt and the first line becomes Shelf | my_books.txt, without touching one line of code. Set SHELF_API_KEY and the last line says API key: set. It only ever prints set or missing, never the key itself.

Why secrets stay out of the project

Paste a key into config.py and it can ride to GitHub with your next push, and into an AI tool whenever that tool reads your files. A common habit is a .env file listed in .gitignore, loaded with the small python-dotenv package, so Git leaves it alone. But .gitignore is a list for Git. Some AI tools read it and some don't, so don't count on it to hide a secret. Keep secrets in environment variables, out of the folder entirely. What the project does keep is .env.example, with the names and a placeholder:

SHELF_DATA=books.txt
SHELF_API_KEY=put-your-key-here

A script that can't work without the key should fail early and clearly:

from shelf import config

key = config.require_key()
print("Sending with a key of length", len(key))
Traceback (most recent call last):
  File "S07L03_Structure/send.py", line 3, in <module>
    key = config.require_key()
  File "S07L03_Structure/shelf/config.py", line 10, in require_key
    raise RuntimeError("Set SHELF_API_KEY first")
RuntimeError: Set SHELF_API_KEY first

With the variable set, it prints Sending with a key of length 12. It prints the length, not the key. For the setup side of keys, see Python project setup with uv and API keys.

The files a project needs

  • README.md: what the project is and how to run it, for people and for tools.
  • pyproject.toml: the standard place to describe a Python project.
  • .gitignore: what Git should skip, like .venv/ and .env.
  • __init__.py: marks a folder as a package, so from shelf import config works. The tests folder has one too, which is how python -m unittest finds the test.
  • tests/: lets you and the tool check that a change didn't break anything.
[project]
name = "shelf"
version = "0.1.0"
description = "A tiny reading list"
requires-python = ">=3.12"
dependencies = []

requires-python tells a tool which Python it's writing for. dependencies is empty because Shelf uses only the standard library, so a tool can see what's installed instead of guessing a package. You'll still see requirements.txt in plenty of projects, but it's only a list of packages; pyproject.toml is where a project describes itself. More in uv and pyproject.toml.

AGENTS.md: instructions coding agents read

A coding agent starts each session knowing nothing about your project. AGENTS.md is a plain markdown file at the top of the project with instructions for coding agents. There's no special syntax.

# Shelf

A tiny reading list written in plain Python.

## Layout
- shelf/books.py: the Book class and summary()
- shelf/storage.py: save and load books
- shelf/config.py: settings from environment variables
- main.py: the entry point
- tests/: unittest tests

## Commands
- Run: python main.py
- Test: python -m unittest

## Rules
- Standard library only.
- Add type hints to every function.
- Read settings from shelf/config.py only.
- Never write a secret into a file. Use SHELF_API_KEY.

Layout says where to look, Commands says how to run and test, and Rules says how you want things done. Many agents read this file on their own, so your instructions come along with every request. It's guidance, not a lock, so you still read what comes back. Not every tool looks for the same file: Claude Code reads CLAUDE.md, and Shelf's is one line, "See AGENTS.md for the project instructions." One set of rules, two tools reach it, nothing drifts apart. (More on that file in the CLAUDE.md hierarchy.)

The commands matter because an agent that knows them can check its own work:

python -m unittest
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

A project map for a plain chatbot

A plain chatbot can't see your files and hasn't read AGENTS.md, so you describe the project yourself:

  1. The map: "I have a Python project with this structure, and main.py is the entry point."
  2. One line per module: books.py has Book and summary, storage.py saves and loads, config.py reads the settings.
  3. The task: "Add a function to books.py that returns the total pages, and use the Book class."
  4. The limits: "Standard library only, and change only that file."

Without the map, the tool invents its own files and its own Book class. With it, the code fits yours.

Scaffold first

Think of the frame around a building before the walls go up. Scaffolding means creating the folders and empty files before any logic. Ask an AI tool: "Write a script that creates this structure, with empty files only." Then read the tree before you go on. An empty file is easy to move; a finished app isn't. From there, ask for one module at a time, and every piece of code already has a home.

Quick recap

  • Structure gives AI tools less to read and fewer reasons to guess. Pick a common layout and keep names consistent.
  • Settings go through config.py; secrets stay in environment variables; .env.example holds only names.
  • pyproject.toml and AGENTS.md tell tools about your project. A tool only knows what it can read, so make your project easy to read.

Keep going in Python · 34 of 48

Previous
Python Practice: Build a Log File Analyzer and a File Organizer
Next post
Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Set Up a Python AI Project with uv, VS Code and an API Key in .env

One environment for every AI project: uv brings Python 3.12 and pinned packages from uv.lock, a check script fails four times on plain python and passes after uv sync, VS Code points at .venv, the API key stays in .env, and a stand-in test model answers when there is no key.

uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project

One tool instead of venv, activate, pip install and pip freeze. Build a small chatbot project with uv init, hit ModuleNotFoundError, fix it with uv add, read pyproject.toml and uv.lock, then delete .venv and rebuild it with uv sync.

Python try and except Basics: Catch an Error and Keep Going

An exception is the object Python creates when something goes wrong. Catch it with try and a named except, read it with as, add else and finally, retry bad input in a loop, and see why a bare except hides your bugs.

Read and Write a File in Python: open, with, Modes and Encoding

Make your data outlive the program: write notes.txt with open and with, read it back three ways, see how w wipes a file and a appends, why encoding matters, and what to do when a file isn't there.

On this page

  • Reason one: context has limited room
  • Reason two: tools expect common shapes
  • Four common layouts
  • The Shelf project
  • Consistent names
  • Settings in one place: config.py
  • Why secrets stay out of the project
  • The files a project needs
  • AGENTS.md: instructions coding agents read
  • A project map for a plain chatbot
  • Scaffold first
  • Quick recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.