Skip to main content

Typed settings based on attrs classes

Project description

Typed Settings

PyPI PyPI - License PyPI - Python Version Documentation Status Gitlab pipeline status Gitlab code coverage Code style: black

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

The documentation contains a full list of all features.

Installation

Install and update using pip:

$ python -m pip install typed-settings

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.

Click

Optionally, click options can be generated for each option. Config files and environment variables will still be read and can be overriden by passing command line options.

# example.py
import click
import typed_settings as ts

@ts.settings
class Settings:
    a_str: str = "default"
    an_int: int = 3

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

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

Options:
  --a-str TEXT      [default: default]
  --an-int INTEGER  [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 attr.define and can optionally make your settings frozen (immutable).

  • option() and secret() are wrappers around attr.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 !.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

typed-settings-0.11.1.tar.gz (119.5 kB view details)

Uploaded Source

Built Distribution

typed_settings-0.11.1-py3-none-any.whl (28.4 kB view details)

Uploaded Python 3

File details

Details for the file typed-settings-0.11.1.tar.gz.

File metadata

  • Download URL: typed-settings-0.11.1.tar.gz
  • Upload date:
  • Size: 119.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.12

File hashes

Hashes for typed-settings-0.11.1.tar.gz
Algorithm Hash digest
SHA256 81cc8e794c91030539b3e5e840eff2334b71ed01e30ec05eca87b91d1647b48b
MD5 3b92007b9a3596fe72831a9a836bf812
BLAKE2b-256 7ee0eb4f9f968c8d2620fb2529af75ff4fb3aca5cad24510ce5210c347612906

See more details on using hashes here.

File details

Details for the file typed_settings-0.11.1-py3-none-any.whl.

File metadata

  • Download URL: typed_settings-0.11.1-py3-none-any.whl
  • Upload date:
  • Size: 28.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.8.12

File hashes

Hashes for typed_settings-0.11.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e3d29c530fff394ea94bc50bd3570afe19a0854be88f46ee56bd3672f44cbfc6
MD5 ae6c035e287b7927de7593c0e26cd196
BLAKE2b-256 0fef324d18c398442c0f1d4434b928af63f8da5f8d9ed686662f23c2477a1f7f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page