Course contentsShow
← Python
Lesson 548 of 1,0608. Professional Tooling and PackagingFree lesson

Managing Environment Specific Configuration Files

Organize your project to handle distinct settings for development, staging, and production environments using hierarchical configuration patterns.

In this lesson, you will learn how to structure your project to handle distinct settings for development, staging, and production environments using hierarchical configuration patterns.

When building professional applications, you must avoid "hard-coding" settings. Instead, you should organize your configuration so that your application behaves differently depending on where it is running, without needing to change your core code.

The Hierarchical Pattern

The most effective way to manage this is through a hierarchical configuration pattern. Instead of one monolithic file, you create a base configuration that holds shared settings, and then create environment-specific overrides.

A common professional structure looks like this:

config/
├── base.py          # Settings common to all environments
├── development.py   # Settings for local testing
├── staging.py       # Settings that mimic production
└── production.py    # Strict settings for live use

Implementing the Pattern

You can leverage pydantic-settings to merge these files effectively. Your base.py defines the schema, and your specific environment files populate that schema with the values required for that context.

For instance, you might use a config.py factory that detects the environment via an environment variable (like APP_ENV) and imports the correct settings class:

import os
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str
    debug: bool = False

# Load specific config based on environment
env = os.getenv("APP_ENV", "development")

if env == "production":
    from .production import ProductionSettings as Config
else:
    from .development import DevelopmentSettings as Config

settings = Config()

By separating your settings into distinct files, you ensure that sensitive production credentials are never accidentally used in development. This approach also allows you to enforce validation schemas (using Pydantic) so that if a configuration value is missing or the wrong type in a specific environment, your application will fail early and safely during startup, rather than crashing unexpectedly while a user is connected.

Key Takeaway: Use a hierarchical configuration structure to define shared defaults in a base file and apply environment-specific overrides, ensuring your application remains secure and portable across different deployment stages.