# Python configuration libraries

Python configuration libraries load application settings from environment variables, files, and command-line arguments. A settings loader reads each source in a fixed order of precedence and converts the raw strings into typed values. These libraries let apps and services run the same code in development, test, and production.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [python-dotenv](#python-dotenv) | 757.3M | Not on GitHub | Oct 2026 | BSD-3-Clause |
| [Pydantic Settings](#pydantic-settings) | 487.7M | 1.5K | Nov 2026 | MIT |
| [Traitlets](#traitlets) | 144.9M | Not on GitHub | Aug 2026 | BSD-3-Clause |
| [OmegaConf](#omegaconf) | 38.8M | 2.4K | Oct 2026 | BSD-3-Clause |
| [ConfigArgParse](#configargparse) | 21.8M | Not on GitHub | Nov 2026 | MIT |
| [Hydra](#hydra-core) | 17.9M | Not on GitHub | Oct 2026 | MIT |
| [django-environ](#django-environ) | 9.1M | Not on GitHub | Jun 2026 | MIT |
| [python-decouple](#python-decouple) | 7.3M | 3.0K | Mar 2023 | MIT |

Downloads: pypi, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[python-dotenv](#python-dotenv) has the most monthly downloads in this comparison, at 757.3M.

## Capabilities

| Library | Dotenv file loader | Nested configuration merge | Application CLI overrides |
| --- | --- | --- | --- |
| [python-dotenv](#python-dotenv) | Yes | No | No |
| [Pydantic Settings](#pydantic-settings) | Yes | Yes | Yes |
| [Traitlets](#traitlets) | No | Yes | Yes |
| [OmegaConf](#omegaconf) | No | Yes | Yes |
| [ConfigArgParse](#configargparse) | No | No | Yes |
| [Hydra](#hydra-core) | No | Yes | Yes |
| [django-environ](#django-environ) | Yes | No | No |
| [python-decouple](#python-decouple) | Yes | No | No |

## Libraries

### python-dotenv

[GitHub](https://github.com/theskumar/python-dotenv) · [pypi](https://pypi.org/project/python-dotenv) · [Docs](https://github.com/theskumar/python-dotenv/blob/v1.2.4/src/dotenv/main.py)

Reads key-value pairs from a .env file and sets them as environment variables.

- Downloads / mo: 757.3M
- Last release: 1.2.4
- License: BSD-3-Clause
- Capabilities: [From the python-dotenv docs](https://github.com/theskumar/python-dotenv/blob/v1.2.4/src/dotenv/main.py)

```sh
python -m pip install python-dotenv==1.2.4
```

**pydantic/pydantic-settings** (1.5K stars)

[pydantic/pydantic-settings](https://github.com/pydantic/pydantic-settings) 

```python
@staticmethod
def _static_read_env_file(
    file_path: Path,
    *,
    encoding: str | None = None,
    case_sensitive: bool = False,
    ignore_empty: bool = False,
    parse_none_str: str | None = None,
) -> Mapping[str, str | None]:
    encoding = encoding if encoding is not None else 'utf-8'
    file_vars: dict[str, str | None] = dotenv_values(file_path, encoding=encoding)
    return parse_env_vars(file_vars, case_sensitive, ignore_empty, parse_none_str)
```

[pydantic_settings/sources/providers/dotenv.py](https://github.com/pydantic/pydantic-settings/blob/50e676c2050225877a011779ef6c07a942feb335/pydantic_settings/sources/providers/dotenv.py#L82-L93) · [More projects using python-dotenv →](https://dashboard.exa.ai/playground/search?q=python-dotenv%20GitHub%20projects)

**Quickstart**

```python
from dotenv import load_dotenv

load_dotenv()

```

From [main.py](https://github.com/theskumar/python-dotenv/blob/v1.2.4/src/dotenv/main.py)

### Pydantic Settings

[GitHub](https://github.com/pydantic/pydantic-settings) · [pypi](https://pypi.org/project/pydantic-settings) · [Docs](https://docs.pydantic.dev/latest/concepts/pydantic_settings/)

Loads application settings into typed models from ordered environment, file, and custom sources.

- Downloads / mo: 487.7M
- Stars: 1.5K
- Last release: 2.16.3
- License: MIT
- Capabilities: [From the Pydantic Settings docs](https://docs.pydantic.dev/latest/concepts/pydantic_settings/)

**Strengths**

- **Validates declared settings types.** Validate configuration against a typed settings model.
- **Customizes source precedence.** Order settings sources explicitly when the defaults do not fit.

**Watch out for**

- **Dotenv rejects undeclared fields.** Extra dotenv values raise validation errors under the default forbid policy.
- **Windows environment matching ignores case.** case_sensitive cannot enforce environment-variable casing on Windows.

```sh
python -m pip install pydantic-settings==2.16.3
```

**hatchet-dev/hatchet** (8.3K stars)

[hatchet-dev/hatchet](https://github.com/hatchet-dev/hatchet) 

```python
def _ambient_client_token_source() -> str | None:
    """
    Return where a token picked up by the standard `ClientConfig` constructor
    would come from (the environment, or one of the `.env` files it reads), or
    `None` if there is none. The `.env` files are probed with `ClientConfig`'s
    own pydantic-settings dotenv source, one file at a time so the warning can
    name the file, which keeps the answer identical to what the constructor
    would actually load.
    """
    if os.environ.get("HATCHET_CLIENT_TOKEN"):
        return "the environment"

    env_prefix = str(ClientConfig.model_config.get("env_prefix", ""))
    env_file_setting = ClientConfig.model_config.get("env_file")

    env_files: tuple[Path | str, ...]
    if env_file_setting is None:
        env_files = ()
    elif isinstance(env_file_setting, (str, Path)):
        env_files = (env_file_setting,)
    else:
        env_files = tuple(env_file_setting)

    for name in env_files:
        source = DotEnvSettingsSource(
            ClientConfig, env_file=name, env_prefix=env_prefix
        )
        if source().get("token"):
            return str(name)

    return None
```

[sdks/python/hatchet_sdk/embedded.py](https://github.com/hatchet-dev/hatchet/blob/762e6018e9a48f39fa02993fb080391c7e201906/sdks/python/hatchet_sdk/embedded.py#L287-L317) · [More projects using Pydantic Settings →](https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20pydantic-settings%20for%20settings-source%20precedence%2C%20layered%20overrides%2C%20configuration%20composition%20and%20migration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    app_name: str = "demo"

print(Settings().app_name)

```

From [pydantic_settings.md](https://docs.pydantic.dev/latest/concepts/pydantic_settings/)

### Traitlets

[GitHub](https://github.com/ipython/traitlets) · [pypi](https://pypi.org/project/traitlets) · [Docs](https://traitlets.readthedocs.io/en/stable/config.html)

Provides a configuration system for Python applications.

- Downloads / mo: 144.9M
- Last release: 5.16.1
- License: BSD-3-Clause
- Capabilities: [From the Traitlets docs](https://traitlets.readthedocs.io/en/stable/config.html)

```sh
python -m pip install traitlets==5.16.1
```

**jupyter/jupyter_core** (219 stars)

[jupyter/jupyter_core](https://github.com/jupyter/jupyter_core) 

```python
def load_config_file(self, suppress_errors: bool = True) -> None:  # type:ignore[override]
    """Load the config file.

    By default, errors in loading config are handled, and a warning
    printed on screen. For testing, the suppress_errors option is set
    to False, so errors will make tests fail.
    """
    self.log.debug("Searching %s for config files", self.config_file_paths)
    base_config = "jupyter_config"
    try:
        super().load_config_file(
            base_config,
            path=self.config_file_paths,
        )
    except ConfigFileNotFound:
        # ignore errors loading parent
        self.log.debug("Config file %s not found", base_config)

    if self.config_file:
        path, config_file_name = os.path.split(self.config_file)
    else:
        path = self.config_file_paths  # type:ignore[assignment]
        config_file_name = self.config_file_name

        if not config_file_name or (config_file_name == base_config):
            return

    try:
        super().load_config_file(config_file_name, path=path)
    except ConfigFileNotFound:
        self.log.debug("Config file not found, skipping: %s", config_file_name)
    except Exception:
        # Reraise errors for testing purposes, or if set in
        # self.raise_config_file_errors
        if (not suppress_errors) or self.raise_config_file_errors:
            raise
        self.log.warning("Error loading config file: %s", config_file_name, exc_info=True)
```

[jupyter_core/application.py](https://github.com/jupyter/jupyter_core/blob/21b34b5a662165a4ea3dd5f86bc6e06374393468/jupyter_core/application.py#L188-L224) · [More projects using Traitlets →](https://dashboard.exa.ai/playground/search?q=traitlets%20GitHub%20projects)

**Quickstart**

```python
from traitlets import Integer
from traitlets.config import Config, Configurable

class App(Configurable):
    workers = Integer(2).tag(config=True)

print(App(config=Config({"App": {"workers": 4}})).workers)

```

From [config.html](https://traitlets.readthedocs.io/en/stable/config.html)

### OmegaConf

[GitHub](https://github.com/hydra-ecosystem/omegaconf) · [pypi](https://pypi.org/project/omegaconf) · [Docs](https://omegaconf.readthedocs.io/en/latest/usage.html)

Builds hierarchical configuration objects with interpolation, structured schemas, and configuration composition.

- Downloads / mo: 38.8M
- Stars: 2.4K
- Last release: 2.4.0
- License: BSD-3-Clause
- Capabilities: [From the OmegaConf docs](https://omegaconf.readthedocs.io/en/latest/usage.html)

**Strengths**

- **Interpolates related settings lazily.** Reference other configuration values and resolve them when accessed.
- **Validates structured configuration.** Use dataclass or attrs schemas to validate assignments at runtime.

**Watch out for**

- **Implicit conversions emit warnings.** Use matching types or OmegaConf.update to request conversion explicitly.
- **Resolution in place removes expressions.** Copy configuration before resolve when lazy references must be preserved.

```sh
python -m pip install omegaconf==2.4.0
```

**hydra-ecosystem/hydra** (10.8K stars)

[hydra-ecosystem/hydra](https://github.com/hydra-ecosystem/hydra) 

```python
@staticmethod
def _embed_result_config(
    ret: ConfigResult, package_override: str | None
) -> ConfigResult:
    package = ret.header["package"]
    if package_override is not None:
        package = package_override

    if package is not None and package != "":
        cfg = OmegaConf.create()
        OmegaConf.update(cfg, package, ret.config, merge=False)
        ret = copy.copy(ret)
        ret.config = cfg

    return ret
```

[hydra/_internal/config_loader_impl.py](https://github.com/hydra-ecosystem/hydra/blob/fdd1cbb80369222e9e132f107456a9c8af1842cb/hydra/_internal/config_loader_impl.py#L708-L722) · [More projects using OmegaConf →](https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20omegaconf%20for%20settings-source%20precedence%2C%20layered%20overrides%2C%20configuration%20composition%20and%20migration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from omegaconf import OmegaConf

cfg = OmegaConf.create({"server": {"port": 8000}})
print(cfg.server.port)

```

From [usage.html](https://omegaconf.readthedocs.io/en/latest/usage.html)

### ConfigArgParse

[GitHub](https://github.com/bw2/ConfigArgParse) · [pypi](https://pypi.org/project/configargparse) · [Docs](https://github.com/bw2/ConfigArgParse/blob/v1.10.1/configargparse.py)

Extends argparse so options can also come from config files or environment variables.

- Downloads / mo: 21.8M
- Last release: 1.10.1
- License: MIT
- Capabilities: [From the ConfigArgParse docs](https://github.com/bw2/ConfigArgParse/blob/v1.10.1/configargparse.py)

```sh
python -m pip install configargparse==1.10.1
```

**Quickstart**

```python
import configargparse

parser = configargparse.ArgParser()
parser.add("--workers", type=int, default=2, env_var="WORKERS")
print(parser.parse_args(["--workers", "4"]).workers)

```

From [configargparse.py](https://github.com/bw2/ConfigArgParse/blob/v1.10.1/configargparse.py) · [Find projects using ConfigArgParse →](https://dashboard.exa.ai/playground/search?q=configargparse%20GitHub%20projects)

### Hydra

[GitHub](https://github.com/hydra-ecosystem/hydra) · [pypi](https://pypi.org/project/hydra-core) · [Docs](https://hydra.cc/docs/advanced/compose_api/)

Provides a framework for configuring complex applications.

- Downloads / mo: 17.9M
- Last release: 1.3.8
- License: MIT
- Capabilities: [From the Hydra docs](https://hydra.cc/docs/advanced/compose_api/)

```sh
python -m pip install hydra-core==1.3.8
```

**JonasGeiping/cramming** (1.4K stars)

[JonasGeiping/cramming](https://github.com/JonasGeiping/cramming) 

```python
def get_backend_config(backend="torch-default", overrides=[]):
    """Return default hydra config for a given attack."""
    with hydra.initialize(config_path="config/impl"):
        cfg = hydra.compose(config_name=backend, overrides=overrides)
        print(f"Loading backend {cfg.name}.")
    return cfg
```

[cramming/__init__.py](https://github.com/JonasGeiping/cramming/blob/196c9912d8c5b06a05e9a58edd1521e3d38f7c0c/cramming/__init__.py#L39-L44) · [More projects using Hydra →](https://dashboard.exa.ai/playground/search?q=hydra-core%20GitHub%20projects)

**Quickstart**

```python
from hydra import compose, initialize

with initialize(version_base=None, config_path=None):
    cfg = compose(overrides=["+message=hello"])
print(cfg.message)

```

From [README.md](https://hydra.cc/docs/advanced/compose_api/)

### django-environ

[GitHub](https://github.com/joke2k/django-environ) · [pypi](https://pypi.org/project/django-environ) · [Docs](https://django-environ.readthedocs.io/en/latest/api.html)

Configures Django applications from environment variables in the twelve-factor style.

- Downloads / mo: 9.1M
- Last release: 0.14.0
- License: MIT
- Capabilities: [From the django-environ docs](https://django-environ.readthedocs.io/en/latest/api.html)

```sh
python -m pip install django-environ==0.14.0
```

**HumanSignal/label-studio** (28.7K stars)

[HumanSignal/label-studio](https://github.com/HumanSignal/label-studio) 

```python
def generate_secret_key_if_missing(data_dir: str) -> str:
    env_key = 'SECRET_KEY'
    env = environ.Env()
    env_filepath = os.path.join(data_dir, '.env')
    restrict_env_file_permissions(env_filepath)
    environ.Env.read_env(env_filepath)

    if existing_secret := env.str(env_key, ''):
        return existing_secret

    logger.warning(f'Warning: {env_key} not found in environment variables. Will generate a random key.')
    new_secret = get_random_secret_key()

    if is_collectstatic():
        logger.info(
            'Random SECRET_KEY was generated, but it is not being persisted because this is a collectstatic run'
        )
        return new_secret

    try:
        # SECRET_KEY also signs JWTs, so the file must not be readable by other local users
        fd = os.open(env_filepath, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
        with os.fdopen(fd, 'a') as f:
            f.write(f'\n{env_key}={new_secret}\n')  # nosec
    except Exception as e:
        logger.warning(
            f'Warning: failed to write {env_key} to .env file: {e}, new key will be regenerated on every '
            f'server restart. If this key is used for signing, it will invalidate all existing sessions '
            f'or tokens. Please set {env_key} in your environment variables to avoid this warning.'
        )

    os.environ[env_key] = new_secret
    return new_secret
```

[label_studio/core/utils/secret_key.py](https://github.com/HumanSignal/label-studio/blob/bce6c7ba79c3a0d4c4c6b54de98d2e8e9586c1b6/label_studio/core/utils/secret_key.py#L29-L61) · [More projects using django-environ →](https://dashboard.exa.ai/playground/search?q=django-environ%20GitHub%20projects)

**Quickstart**

```python
import environ

env = environ.Env(DEBUG=(bool, False))
print(env("DEBUG"))

```

From [quickstart.html](https://django-environ.readthedocs.io/en/latest/quickstart.html)

### python-decouple

[GitHub](https://github.com/HBNetwork/python-decouple) · [pypi](https://pypi.org/project/python-decouple) · [Docs](https://github.com/HBNetwork/python-decouple/blob/v3.8/decouple.py)

Looks up settings in environment variables and INI or dotenv files, with defaults and explicit casts.

- Downloads / mo: 7.3M
- Stars: 3.0K
- Last release: 3.8
- License: MIT
- Capabilities: [From the python-decouple docs](https://github.com/HBNetwork/python-decouple/blob/v3.8/decouple.py)

**Strengths**

- **Environment values take precedence.** Environment variables override matching settings-file values.
- **Casts values at lookup.** Apply bool, int, or custom casts when retrieving a setting.

**Watch out for**

- **Values start as strings.** Request explicit casts when booleans, numbers, or lists are needed.
- **Missing required values raise errors.** Provide a default or handle UndefinedValueError for missing settings.

```sh
python -m pip install python-decouple==3.8
```

**RoboSats/robosats** (1.0K stars)

[RoboSats/robosats](https://github.com/RoboSats/robosats) 

```python
@shared_task(name="follow_send_payment", time_limit=180, soft_time_limit=175)
def follow_send_payment(hash):
    """Sends sats to buyer, continuous update"""

    from datetime import timedelta

    from decouple import config
    from django.utils import timezone

    from api.lightning.node import LNNode
    from api.models import LNPayment

    if config("DEBUG_PERMISSIONED_PAYOUTS", cast=bool, default=False):
        return

    lnpayment = LNPayment.objects.get(payment_hash=hash)
    lnpayment.last_routing_time = timezone.now()
    lnpayment.save(update_fields=["last_routing_time"])

    # Checked against the lightning node before every attempt; a payout that fails it
    # is held (and retried in an hour) until the coordinator looks at it.
    from api.logics import payout_problem

    problem = payout_problem(lnpayment)
    if problem:
        print(f"PAYOUT HELD {hash}: {problem}", flush=True)
        from api.models import Order

        order = Order.objects.filter(payout=lnpayment).first()
        if order and "PAYOUT HELD" not in (order.logs or ""):
            order.log(f"PAYOUT HELD: {problem}", level="WARN")
        lnpayment.last_routing_time = timezone.now() + timedelta(hours=1)
        lnpayment.save(update_fields=["last_routing_time"])
        return

    # Default is 0ppm. Set by the user over API. Client's default is 1000 ppm.
    fee_limit_sat = int(
        float(lnpayment.num_satoshis) * float(lnpayment.routing_budget_ppm) / 1_000_000
    )
    timeout_seconds = config("PAYOUT_TIMEOUT_SECONDS", cast=int, default=90)
    try:
        results = LNNode.follow_send_payment(lnpayment, fee_limit_sat, timeout_seconds)

    except SoftTimeLimitExceeded:
        # If the 175 seconds have been consumed without follow_send_payment()
        # returning, we set the last routing time as 'in 10 minutes'
        # so the next check happens in 10 minutes, instead of right now.
        lnpayment.last_routing_time = timezone.now() + timedelta(minutes=10)
        lnpayment.save(update_fields=["last_routing_time"])
        print(
            f"Order: {lnpayment.order_paid_LN.id} SOFT TIME LIMIT REACHED. Hash: {hash}"
        )
        results = {}

    return results
```

[api/tasks.py](https://github.com/RoboSats/robosats/blob/babf62e2238f262182d0bf638496aaa53e286853/api/tasks.py#L76-L130) · [More projects using python-decouple →](https://dashboard.exa.ai/playground/search?q=Python%20applications%20using%20python-decouple%20for%20settings-source%20precedence%2C%20layered%20overrides%2C%20configuration%20composition%20and%20migration&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from decouple import config

print(config("DEBUG", default=False, cast=bool))

```

From [README.rst](https://github.com/HBNetwork/python-decouple/blob/master/README.rst)

## FAQ

### Which Python configuration library should I use?

[Pydantic Settings](#pydantic-settings) suits applications that validate settings against a typed model. [python-dotenv](#python-dotenv) suits scripts that only need the values from a .env file. [OmegaConf](#omegaconf) and [Hydra](#hydra-core) suit nested configurations with command-line overrides.

### What is python-dotenv?

[python-dotenv](#python-dotenv) reads key-value pairs from a .env file and sets them as environment variables. It does not build typed settings models or merge nested configuration.

### What is Pydantic Settings?

[Pydantic Settings](#pydantic-settings) loads settings into typed models from environment variables, dotenv files, secrets files, and custom sources. It validates each value against the declared field types.

### What is OmegaConf?

[OmegaConf](#omegaconf) builds hierarchical configuration objects with interpolation between values, structured schemas, and recursive merging. [Hydra](#hydra-core) builds configuration composition on top of it.

### What is Hydra in Python?

[Hydra](#hydra-core) composes an application's configuration from modular groups and command-line overrides. It runs on OmegaConf and adds launch and multirun workflows.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python configuration libraries Pydantic Settings Dynaconf OmegaConf python-decouple code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
