2.3 KiB
title, last_modified
| title | last_modified |
|---|---|
| Code Styleguide — Python | 2026-02-22 |
- Standard Project Layout. Use the src/ layout to prevent accidental imports from the root and ensure your project behaves like an installed package:
my_project/ ├── pyproject.toml # Modern tool & dependency configuration ├── README.md # Instructions for humans ├── LICENSE # Usage rights ├── .gitignore # Exclude venv/, pycache/, .env ├── src/ │ └── my_project/ # Main package │ ├── init.py │ ├── main.py # Minimal entry point logic │ └── core.py # Business logic ├── tests/ # Mirror src structure for testing └── docs/ # Technical documentation
-
Virtual Environments: Always isolate project dependencies using venv or pyenv to avoid conflicts with system-wide packages.
-
Adhere to PEP 8: Use 4 spaces for indentation (no tabs), limit lines to 79 characters, and use two blank lines between top-level functions.
-
Put code in functions. If you are writing a script, put the script in a function called
mainand callmain()at the end of the script using the standard invocation:if __name__ == "__main__": main() -
Keep main.py Boring: The entry point should only orchestrate (load config, start app). Heavy business logic should live in specialized modules.
-
Config Isolation: Never hardcode secrets or database URLs. Use a .env file with libraries like python-dotenv or Pydantic Settings.
-
Logging over Printing: Use Python’s built-in logging module to track errors and application state in production.
-
Test-First: Treat your tests/ directory as first-class code. Use pytest for its powerful features and simple syntax.
-
Naming Conventions: Use snake_case for functions and variables, PascalCase for classes, and UPPER_CASE for constants.
-
pyproject.toml: Use this as the single source of truth for project metadata and tool configurations (replaces setup.py).
-
Modular Design: Group code by domain (e.g., /users, /payments) rather than function (e.g., utils.py) to maintain separation of concerns.
Author
License
MIT. See LICENSE.