Tools
Log in
English

Learn to codePython

Python project structure

Based on Python 3.12

A Python src-layout project with pyproject.toml, venv or uv and tests, as a zip.

Make a project skeleton

Choose what to build and a package tool (pip or uv); the folder tree, file notes and layer picture follow. Click a file to see its starter code, then download the zip and run it.

Build a
Package tool
Tests

Folder tree 8 files

  • src/hello_app/
  • tests/

src/hello_app/__main__.py

The entry point for python -m. It reads arguments with argparse, hands them to the rule function and prints the result. No rules live here.

import argparseimport sys from .greeting import make_greeting def main(argv=None):    parser = argparse.ArgumentParser(prog="hello-app", description="Say hello")    parser.add_argument("name", nargs="?", default="world")    parser.add_argument("--shout", action="store_true", help="print in capitals")    args = parser.parse_args(argv)    try:        text = make_greeting(args.name, shout=args.shout)    except ValueError as e:        print(f"error: {e}", file=sys.stderr)        return 2    print(text)    return 0 if __name__ == "__main__":    sys.exit(main())

Layers

Versions written in the files Python 3.10+ · pytest 8 · setuptools 68 or newer (pip) · hatchling (uv). Library files are not inside the zip. pip or uv downloads them on the first install.

The standard src layout

PathWhat goes there
src/<package>/The program code. The folder name is the name you import.
__init__.pyLives in the package folder. Marks it as a package; re-export the public names here.
__main__.pyAlso in the package folder. The file that runs first with python -m <package>.
tests/Test code (pytest). It is not shipped with the package.
pyproject.tomlProject name, version, required Python, dependencies and build backend.
.venv/A virtual environment for this project only. Create it locally and keep it out of git.

Keeping code under src/ means it can only be imported once installed, which cuts down on "works only on my machine" problems. Tests then run against the installed package.

Splitting into layers

Put the part that takes requests, the part that decides rules and the part that stores data in separate modules. In a web API, api.py calls service.py, which calls repository.py, never the other way round.

With that split you can move storage from memory to a database without touching the service, and pytest can check service rules without starting a server.

  • api.py reads the request and builds the response; it does no calculations.
  • service.py decides the rules and knows nothing about HTTP.
  • repository.py saves and loads. Describe its shape with typing.Protocol and you can swap memory and database versions.

Naming

The project name (name in pyproject) may contain -, as in hello-app, but the package folder must be importable, so it uses underscores: hello_app.

  • Modules, packages, functions and variables use lowercase with underscores (snake_case); classes use CapWords.
  • Never name a file after a standard library module, such as json.py, random.py or test.py. Your file gets imported first and strange errors follow.
  • Keep passwords and API keys out of the code; read them from environment variables (os.environ).

Four common design patterns and dependency injection

Python passes functions around like values, so many patterns need fewer classes than in Java. All of this code was run on Python 3.12.

Singleton · when there must be exactly one

__new__ remembers the first object it made and returns it every time after. a and b are the same object, so a change through b shows through a.

In Python a module is imported only once, so creating one object inside a module and importing it is the more common and simpler choice.

class Settings:    _one = None     def __new__(cls):        if cls._one is None:            cls._one = super().__new__(cls)            cls._one.mode = "production"        return cls._one  a = Settings()b = Settings()b.mode = "test"print(a is b)print(a.mode)

Output

Truetest

Factory · deciding what to create in one place

Look at the extension and return the matching parser. Keeping functions in a dict means a new format is one more line in the dict, and case is normalized in one spot.

import json  def parse_csv(text):    return text.strip().split(",")  def parse_json(text):    return list(json.loads(text).values())  PARSERS = {"csv": parse_csv, "json": parse_json}  def parser_for(filename):    ext = filename.rsplit(".", 1)[-1].lower()    if ext not in PARSERS:        raise ValueError(f"no parser for .{ext}")    return PARSERS[ext]  print(parser_for("users.CSV")("lee,29,busan"))print(parser_for("user.json")('{"name": "lee", "age": 29}'))

Output

['lee', '29', 'busan']['lee', 29]

Strategy · swappable ways to calculate

Write each discount rule as a function and pass it to Checkout. Functions are values in Python, so no class per strategy is needed. A rule that needs settings, like coupon(3000), is a function that returns a function.

def no_discount(price):    return price  def member(price):    return round(price * 0.9)  def coupon(amount):    return lambda price: max(0, price - amount)  class Checkout:    def __init__(self, rule=no_discount):        self.rule = rule     def total(self, prices):        return self.rule(sum(prices))  cart = [12000, 8000]for rule in (no_discount, member, coupon(3000)):    print(Checkout(rule).total(cart))

Output

200001800017000

Observer · telling others when something happens

When an event such as a restock happens, every registered function is called in turn. A listener can be a lambda or an ordinary method such as list.append.

class Shelf:    def __init__(self):        self.listeners = []     def subscribe(self, fn):        self.listeners.append(fn)     def restock(self, item):        for fn in self.listeners:            fn(item)  log = []shelf = Shelf()shelf.subscribe(lambda item: print(f"Text: {item} is back"))shelf.subscribe(log.append)shelf.restock("mouse")print("Log:", log)

Output

Text: mouse is backLog: ['mouse']

Dependency injection · receiving what you need through the constructor

Greeter does not build its user store; it receives one in the constructor. Real code passes MemoryUsers, a test passes FakeUsers, which only has find(). Duck typing makes it fit without inheritance.

Features such as Depends in FastAPI do the same job: they find the right object and pass it in.

class MemoryUsers:    def __init__(self):        self.names = {1: "Hana"}     def find(self, user_id):        return self.names.get(user_id)  class Greeter:    def __init__(self, users):        self.users = users     def greet(self, user_id):        name = self.users.find(user_id) or "guest"        return f"Hi, {name}"  class FakeUsers:    def find(self, user_id):        return "Tester"  app = Greeter(MemoryUsers())print(app.greet(1))print(app.greet(7))print(Greeter(FakeUsers()).greet(1))

Output

Hi, HanaHi, guestHi, Tester

Check yourself

Question 1

Which folder stays out of git?

Show the answer

Answer: 3. .venv/ .venv/ holds packages installed on your own machine, and everyone recreates it. Put it in .gitignore.

Question 2

After installing the src-layout package hello_app, which command runs it properly?

Show the answer

Answer: 3. python -m hello_app python -m package runs the installed package's __main__.py. Running a file by path breaks relative imports such as from . import. Run it inside your .venv.

Questions people ask

How do requirements.txt and pyproject.toml differ?

pyproject.toml is the standard file for the project name, version and dependencies. requirements.txt is a list for pip to install in one go, often with exact versions.

Do I really need a virtual environment?

It keeps each project's package versions from clashing. Create one with python -m venv .venv and keep .venv out of git.

Should I pick uv or pip?

pip ships with Python, so there is nothing extra to install. uv must be installed separately but handles environments, installs and a lock file in one fast tool.