Skip to main content

Typed Settings

Typed Settings allows you to cleanly structure your settings with attrs classes. Type annotations will be used to automatically convert values to the proper type (using cattrs). You can currently load settings from these sources:

  • TOML files (multiple, if you want to). Paths can be statically specified or dynamically set via an environment variable.
  • Environment variables
  • click command line options

You can use Typed settings, e.g., for

  • server processes
  • containerized apps
  • command line applications
  • scripts and tools for scientific experiments and data analysis

The documentation contains a full list of all features.

Installation

Install and update using pip:

$ python -m pip install typed-settings

You can install dependencies for optional features via

$ python -m pip install typed-settings[<feature>]

Available features:

  • typed-settings[click]: Enable support for Click options
  • typed-settings[option-groups]: Enable support for Click and Click option groups
  • typed-settings[all]: Install all optional requirements

Examples

Hello, World!, with env. vars.

This is a very simple example that demonstrates how you can load settings from environment variables.

# example.py
import typed_settings as ts

@ts.settings
class Settings:
    option: str

settings = ts.load(cls=Settings, appname="example")
print(settings)
$ EXAMPLE_OPTION="Hello, World!" python example.py
Settings(option='Hello, World!')

Nested classes and config files

Settings classes can be nested. Config files define a different section for each class.

# example.py
import click

import typed_settings as ts

@ts.settings
class Host:
    name: str
    port: int

@ts.settings(kw_only=True)
class Settings:
    host: Host
    endpoint: str
    retries: int = 3

settings = ts.load(
    cls=Settings, appname="example", config_files=["settings.toml"]
)
print(settings)
# settings.toml
[example]
endpoint = "/spam"

[example.host]
name = "example.com"
port = 443
$ python example.py
Settings(host=Host(name='example.com', port=443), endpoint='/spam', retries=3)

Configurable settings loaders

The first example used a convenience shortcut with pre-configured settings loaders. However, Typed Settings lets you explicitly configure which loaders are used and how they work:

# example.py
import typed_settings as ts

@ts.settings
class Settings:
    option: str

settings = ts.load_settings(
    cls=Settings,
    loaders=[
        ts.FileLoader(
            files=[],
            env_var="EXAMPLE_SETTINGS",
            formats={
                "*.toml": ts.TomlFormat("example"),
            },
        ),
        ts.EnvLoader(prefix="EXAMPLE_"),
      ],
)
print(settings)
$ EXAMPLE_OPTION="Hello, World!" python example.py
Settings(option='Hello, World!')

In order to write your own loaders or support new file formats, you need to implement the Loader or FileFormat protocols.

You can also pass a custom cattrs converter to add support for additional Python types.

Command Line Interfaces

Typed Settings can generate a command line interfaces (CLI) based on your settings. These CLIs will load settings as described above and let users override the loades settings with command line argumments.

Typed Settings supports argparse and click.

Argparse

# example.py
import typed_settings as ts

@ts.settings
class Settings:
    a_str: str = ts.option(default="default", help="A string")
    an_int: int = ts.option(default=3, help="An int")

@ts.cli(Settings, "example")
def main(settings):
    print(settings)

if __name__ == "__main__":
    main()
$ python example.py --help
usage: example.py [-h] [--a-str TEXT] [--an-int INT]

options:
  -h, --help    show this help message and exit

Settings:
  Settings options

  --a-str TEXT  A string [default: default]
  --an-int INT  An int [default: 3]
$ python example.py --a-str=spam --an-int=1
Settings(a_str='spam', an_int=1)

Click

# example.py
import click
import typed_settings as ts

@ts.settings
class Settings:
    a_str: str = ts.option(default="default", help="A string")
    an_int: int = ts.option(default=3, help="An int")

@click.command()
@ts.click_options(Settings, "example")
def main(settings):
    print(settings)

if __name__ == "__main__":
    main()
$ python example.py --help
Usage: example.py [OPTIONS]

Options:
  --a-str TEXT      A string  [default: default]
  --an-int INTEGER  An int  [default: 3]
  --help            Show this message and exit.
$ python example.py --a-str=spam --an-int=1
Settings(a_str='spam', an_int=1)

Features

  • Settings are defined as type-hinted attrs classes.

  • Typed Settings’ settings decorator is an alias to attrs.define and can optionally make your settings frozen (immutable).

  • option() and secret() are wrappers around attrs.field() and add meta data handling for Click options.

  • secret() attributes have string representation that masks the actual value, so that you can safely print or log settings instances.

  • Settings can currently be loaded from:

    • TOML files
    • Python files
    • Environment variables
    • Click command line options
  • Settings are converted to their correct type using cattrs.

    • Users can extend the default converter with hooks for custom types
    • Lists can be loaded from strings from environment variables. String-to-list conversion can be configured. Strings can be JSON structues or simple comma (or colon) speparated lists (e.g., "1,2,3" or "path1:path2").
  • Paths to settings files can be

    • “hard-coded” into your code,
    • dynamically searched from the CWD upwards via find(filename), or
    • specified via an environment variable.
  • Order of precedence:

    • Default value from settings class
    • First file from hard-coded config files list
    • ...
    • Last file from hard-coded config files list
    • First file from config files env var
    • ...
    • Last file from config files env var
    • Environment variable {PREFIX}_{SETTING_NAME}
    • (Value passed to Click option)
  • Config files are “optional” by default – no error is raised if a specified file does not exist.

  • Config files can be marked as mandatory by prefixing them with an !.

Metadata

Release files for typed-settings 2.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for typed-settings 2.0.2
File Size Uploaded Provenance Actions
typed_settings-2.0.2.tar.gz 2.7 MB Without provenance Details for typed_settings-2.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for typed-settings 2.0.2
File Interpreter ABI Platform Actions
typed_settings-2.0.2-py3-none-any.whl Python 3 none any Details for typed_settings-2.0.2-py3-none-any.whl

Total release size: 2.7 MB

Release files / typed_settings-2.0.2.tar.gz

Download URL typed_settings-2.0.2.tar.gz
Size 2.7 MB
Tags Source
SHA-256 checksum
How to use checksums
0181c0d71152d20f7d725a06223be2f25a0a4bf43f02d7b22e22c7f2b7fed8da
BLAKE2b-256 checksum
How to use checksums
67bf79e33157f148083de9f88d747e8c55b37c4e9144567f5be5738e3cfbfdb5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.1

Release files / typed_settings-2.0.2-py3-none-any.whl

Download URL typed_settings-2.0.2-py3-none-any.whl
Size 38.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
773cd3ae905db465983e422df0d74a39327c4288d957a0eea7391c127bd6c1fb
BLAKE2b-256 checksum
How to use checksums
ea0133266056cbc4714495f359ef25c395a72e9f00bf1db7abcb00a3dc1af849
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.11.1

Security for typed-settings 2.0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.0.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page