My personal Cookiecutter template for Python projects. This is a living template that evolves as I learn and develop better patterns for Python development. It includes the foundations I've found useful in my own projects - feel free to use it if it helps your projects too!
π― Goal: Provide a solid, opinionated foundation for Python projects with security, testing, and configuration best practices built-in.
π Note: This template reflects my current understanding and preferred patterns. It will continue to evolve as I discover new tools, techniques, and best practices in Python development.
- Sensitive data filtering: Automatically masks passwords, tokens, and secrets in logs
- Structured log formatting: Consistent, readable log output
- Multiple log handlers: Console and file logging with rotation
- Hierarchical configuration: Environment variables β Config file β Defaults
- Easy access patterns: Dotted notation like
config.get('api.timeout')
- Environment validation: Checks for required variables on startup
- pytest setup: Ready-to-use testing infrastructure
- Helpful fixtures: Common testing utilities for config and environment mocking
- Example tests: Patterns I've found useful for testing Python applications
- Library: Standard Python package for reusable code
- CLI Application: Command-line tools with proper argument handling
- API Server: Basic structure for REST APIs
- Microservice: Foundation for containerized services
Why these features? These are patterns I've developed through building various Python projects. They solve common problems I encounter and provide a solid foundation for new projects.
pip install cookiecutter
cookiecutter https://github.com/ty10ng/python-template.git
You'll be prompted for project details like name, description, and which features to include.
$ cookiecutter https://github.com/ty10ng/python-template.git
project_name [My Python Project]: Data Analysis Tool
project_slug [data-analysis-tool]:
package_name [data_analysis_tool]:
project_description [A brief description of your project]: Tool for analyzing research data
python_version [3.11]:
project_type [library]: cli-application
author_name [Your Name]: Tyler Long
author_email [your.email@example.com]: ty@example.com
github_username [your-username]: ty10ng
include_docker [y]: n
include_github_actions [y]: y
include_pre_commit [y]: y
license [MIT]:
data-analysis-tool/
βββ src/
β βββ data_analysis_tool/
β βββ __init__.py # Package initialization
β βββ core.py # Main application logic
β βββ config.py # Configuration management
β βββ logger.py # Security-aware logging
βββ tests/
β βββ __init__.py # Test package initialization
β βββ test_core.py # Core functionality tests
β βββ test_config.py # Configuration tests
βββ .env.example # Environment variables template
βββ config.json # Default configuration
βββ pyproject.toml # Project metadata and dependencies
βββ README.md # Generated project documentation
βββ run_data-analysis-tool.py # CLI entry point
from data_analysis_tool.config import get_config
config = get_config()
api_timeout = config.get('api.timeout', 30) # Fallback to 30
database_url = config.get('database.url') # From env or config file
Configuration Hierarchy (highest priority first):
- Environment variables (e.g.,
API_TIMEOUT
) - Configuration file (
config.json
) - Default values
from data_analysis_tool.logger import get_logger
logger = get_logger(__name__)
logger.info("Processing user request", extra={
'user_id': 'user123', # β
Safe to log
'password': 'secret123' # β Automatically masked
})
Security Features:
- Automatic masking of sensitive fields (password, token, key, secret)
- Configurable allowed fields for logging
- Consistent formatting across all modules
The template includes comprehensive environment variable management:
# .env.example shows required and optional variables
# Required variables
DATABASE_URL=postgresql://localhost/mydb
# OPTIONAL
# Optional feature flags
FEATURE_ENABLED=false
Environment Checking:
- Validates required variables on startup
- Logs missing required variables as warnings
- Logs optional variables as info
- Supports inline documentation
# tests/conftest.py provides useful fixtures
def test_my_feature(mock_env_vars, temp_dir, sample_config_file):
# Test with isolated environment
pass
Test Features:
- Environment variable mocking
- Temporary directory creation
- Sample configuration files
- Isolated test environments
The template supports different project types to match your specific needs:
Perfect for reusable packages and utilities.
Example: Data processing library, API client, utility functions
cookiecutter https://github.com/ty10ng/python-template.git
# Choose: project_type = library
Generated structure: Standard Python package with testing and configuration
Command-line tools with professional features.
Example: File processor, data converter, system utility
cookiecutter https://github.com/ty10ng/python-template.git
# Choose: project_type = cli-application
Features included:
- Click framework with Rich output
- Shell completion for bash/zsh/fish/PowerShell
- Man page generation
- Professional help system
Usage example:
your-tool --help
your-tool process-files *.csv --output results/
your-tool completion # Setup shell completion
Planning to add API server and microservice templates based on real project needs.
cd your-new-project
pip install -e ".[dev]" # Install in development mode
cp .env.example .env # Create environment file
# Edit .env with your values
python your-project.py # Run main application
python -m pytest # Run tests
python -m pytest --cov # Run with coverage
Edit config.json
for default settings:
{
"api": {
"timeout": 30,
"base_url": "https://api.example.com"
},
"logging": {
"level": "INFO",
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
}
Override with environment variables:
export API_TIMEOUT=60
export LOG_LEVEL=DEBUG
This template supports multiple project types, each tailored for specific use cases:
- Standard Python package structure with modern packaging (pyproject.toml)
- Importable modules and functions with proper package initialization
- Comprehensive configuration management with environment variable support
- Security-aware logging with configurable levels and safe output
- Testing framework with pytest and coverage reporting
- Code quality tools (black, flake8, mypy) with sensible defaults
- Development workflow with optional GitHub Actions, Docker, and pre-commit hooks
All library features plus:
- Click-based command-line interface with rich help formatting
- Rich console output with tables, colors, and progress indicators
- Automatic entry point installation via
pip install
- Professional CLI structure with commands, options, and error handling
- Built-in commands:
status
,hello
,info
with extensible command structure
Example CLI usage:
# After installation
my-tool --help
my-tool status
my-tool hello "World" --count 3
# Or run directly
python run_my_project.py --help
Planned additions include:
- API Server type: FastAPI-based REST services with proper routing and documentation
- Microservice type: Containerized services with health checks and service discovery
Each type builds upon the core library foundation while adding specialized dependencies, entry points, and starter files.
- β Never log sensitive data directly
- β Use environment variables for secrets
- β Validate configuration on startup
- β Use the provided logging utilities
- β Use the hierarchical configuration system
- β
Document all variables in
.env.example
- β
Provide sensible defaults in
config.json
- β Validate required configuration early
- β Use the provided test fixtures
- β Test configuration scenarios
- β Mock external dependencies
- β Maintain high test coverage
This template is a living project that evolves with my Python development journey. As I discover new patterns, tools, or techniques that improve my development workflow, I'll incorporate them here.
- Better testing patterns - Exploring property-based testing and test automation
- Development tooling - Integrating more helpful pre-commit hooks and formatting tools
- Documentation - Finding better ways to maintain project documentation
- Performance - Adding profiling and performance monitoring patterns
- Container deployment patterns (when I work more with Docker/Kubernetes)
- API design patterns (as I build more REST APIs)
- Database integration patterns (when projects need persistence)
- Monitoring and observability (for production deployments)
Note: Features get added when I actually need them in my projects, not just because they're trendy. This keeps the template practical and focused.
This template was developed collaboratively with AI as a coding partner, bringing together human experience and AI perspective to create something better than either could build alone. The patterns and decisions remain under continuous review to ensure they serve real project needs.
I believe in treating AI as a respectful collaborator - like working alongside a friend with a unique perspective. All design decisions ultimately reflect my development philosophy and real-world project experience.
I welcome contributions, feedback, and suggestions! This template improves through real-world usage and community input.
- Check existing issues first
- Open a new issue with details about the problem
- Include steps to reproduce and your environment
- Open an issue to discuss new features or improvements
- Explain the use case and how it would help your projects
- Consider if it fits the template's philosophy of practical, needed features
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Test your changes with both project types (library and CLI)
- Commit with clear messages (
git commit -m 'Add amazing feature'
) - Push to your branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Documentation improvements are always welcome! This includes:
- Better examples and use cases
- Clearer setup instructions
- More comprehensive troubleshooting
This template is released under the MIT License. Feel free to use it for any purpose, modify it to fit your needs, and share it with others.
- Built with Cookiecutter
- Developed collaboratively with AI as a coding partner
- Inspired by real-world Python development challenges and solutions
Happy coding! πβ¨
This template is released under the MIT License. Projects generated from this template can use any license you prefer.
A personal template by @ty10ng - evolving with each Python project