5 Common Project Structures You Should Know in Python

5 Common Project Structures You Should Know in Python

In Python development, a reasonable project structure is crucial for the maintainability, scalability, and team collaboration of the code. This article introduces 5 common Python project layouts, each accompanied by usage instructions and original code examples.

1. Single File Application

Applicable Scenarios: Simple scripts, one-time tasks, small tools.

Structure Example:

calculator.py
requirements.txt
README.md

Usage Instructions:

  • All code is written in a single file

  • Suitable for small projects with no more than 200 lines of code

  • Facilitates rapid development and deployment

Code Example:

# calculator.py
"""Simple calculator application"""

def add(a, b):
    """Addition operation"""
    return a + b

def subtract(a, b):
    """Subtraction operation"""
    return a - b

def main():
    print("Simple Calculator")
    num1 = float(input("Enter the first number: "))
    num2 = float(input("Enter the second number: "))
    
    result = add(num1, num2)
    print(f"{num1} + {num2} = {result}")

if __name__ == "__main__":
    main()

2. Modular Layout

Applicable Scenarios: Medium complexity applications that require functional separation.

Structure Example:

data_processor/
├── main.py
├── data_loader.py
├── data_cleaner.py
├── analyzer.py
├── config.py
├── requirements.txt
└── README.md

Usage Instructions:

  • Different modules are divided by functionality

  • Each module is responsible for a specific function

  • Facilitates code reuse and maintenance

Code Example:

# data_loader.py
def load_csv(filepath):
    """Load CSV file"""
    import pandas as pd
    return pd.read_csv(filepath)

# data_cleaner.py  
def remove_duplicates(df):
    """Remove duplicate data"""
    return df.drop_duplicates()

# analyzer.py
def calculate_statistics(df):
    """Calculate basic statistics"""
    return df.describe()

# main.py
from data_loader import load_csv
from data_cleaner import remove_duplicates
from analyzer import calculate_statistics

def process_data(filepath):
    data = load_csv(filepath)
    clean_data = remove_duplicates(data)
    stats = calculate_statistics(clean_data)
    return stats

3. Package Layout Structure

Applicable Scenarios: Large projects that require hierarchical organization.

Structure Example:

ml_project/
├── __init__.py
├── main.py
├── data/
│   ├── __init__.py
│   ├── preprocessing.py
│   └── validation.py
├── models/
│   ├── __init__.py
│   ├── trainer.py
│   └── predictor.py
├── utils/
│   ├── __init__.py
│   └── helpers.py
├── tests/
│   ├── test_data.py
│   └── test_models.py
├── requirements.txt
└── README.md

Usage Instructions:

  • Organize related modules using package directories

  • Each directory requires an __init__.py file

  • Supports relative imports and namespace management

Code Example:

# ml_project/data/preprocessing.py
def normalize_data(data):
    """Data normalization"""
    return (data - data.mean()) / data.std()

# ml_project/models/trainer.py
from ..data.preprocessing import normalize_data

class ModelTrainer:
    def __init__(self, model):
        self.model = model
    
    def train(self, X, y):
        X_normalized = normalize_data(X)
        self.model.fit(X_normalized, y)

4. MVC Pattern Structure

Applicable Scenarios: Applications that require clear separation of concerns.

Structure Example:

task_manager/
├── models/
│   ├── __init__.py
│   └── task.py
├── views/
│   ├── __init__.py
│   └── cli.py
├── controllers/
│   ├── __init__.py
│   └── task_controller.py
├── utils/
│   └── __init__.py
└── main.py

Usage Instructions:

  • Model: Data processing and business logic

  • View: User interface display

  • Controller: Coordinates between Model and View

Code Example:

# models/task.py
class Task:
    def __init__(self, title, description):
        self.title = title
        self.description = description
        self.completed = False

# views/cli.py
class TaskView:
    def show_tasks(self, tasks):
        for i, task in enumerate(tasks, 1):
            status = "✓" if task.completed else "✗"
            print(f"{i}. [{status}] {task.title}")

# controllers/task_controller.py
from models.task import Task
from views.cli import TaskView

class TaskController:
    def __init__(self):
        self.tasks = []
        self.view = TaskView()
    
    def add_task(self, title, description):
        task = Task(title, description)
        self.tasks.append(task)

5. Web Application Structure

Applicable Scenarios: Projects using web frameworks such as Flask and Django.

Structure Example:

blog_app/
├── app/
│   ├── __init__.py
│   ├── routes.py
│   ├── models/
│   │   └── post.py
│   ├── templates/
│   │   └── index.html
│   └── static/
│       ├── css/
│       └── js/
├── tests/
├── config.py
├── run.py
└── requirements.txt

Usage Instructions:

  • Follow the framework’s prescribed structure

  • Separate static files and templates

  • Configure environment-specific settings

Code Example:

# app/__init__.py
from flask import Flask

def create_app():
    app = Flask(__name__)
    
    from .routes import main
    app.register_blueprint(main)
    
    return app

# app/routes.py
from flask import Blueprint, render_template

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return render_template('index.html')

# run.py
from app import create_app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True)

Choosing the right project structure can significantly enhance development efficiency and code quality. Depending on the project scale and development needs, flexibly choose the most suitable structural scheme.

1. Documentation Completeness: Every project should include detailedREADME documentation;

2. Dependency Management: Userequirements.txt orpyproject.toml to specify dependencies;

3. Test Coverage: Establish a complete test directory and test cases;

4. Configuration Separation: Distinguish between development, testing, and production environment configurations;

5. Version Control: Properly configure the.gitignore file;

“Practice makes perfect!” Use it if you need it!If you find this article useful, feel free tolike, share, bookmark, comment, and recommend!5 Common Project Structures You Should Know in Python—— Join the Knowledge Community and learn with more people ——

https://ima.qq.com/wiki/?shareId=f2628818f0874da17b71ffa0e5e8408114e7dbad46f1745bbd1cc1365277631c

5 Common Project Structures You Should Know in Python

https://ima.qq.com/wiki/?shareId=66042e013e5ccae8371b46359aa45b8714f435cc844ff0903e27a64e050b54b5

5 Common Project Structures You Should Know in Python

Leave a Comment