Skip to main content

Apply values to optional params

Project description

apply_defaults

Apply default values to functions.

Makes configuration easy! Application settings come from a config file into your code cleanly.

pip install apply_defaults

@apply_config

This decorator applies options from a ConfigParser object.

from apply_defaults import apply_config
from configparser import ConfigParser

config = ConfigParser()
config.read_dict({"general": {"option": True}})

@apply_config(config)
def func(option: bool = False) -> bool:
    return option

The option parameter takes the value from the configuration.

>>> func()
True

Override the configuration by passing a value.

>>> func(option=False)
False

If the option is not in the configuration, the default value from the parameter list is used.

>>> config.remove_option("general", "option")
>>> func()
False

ConfigParser's options are strings. Type hints in the function signature allow the apply_config decorator to cast options to the desired type. Alternatively cast the value yourself.

@apply_self

This decorator applies attributes from the bound object.

from apply_defaults import apply_self

class MyObject:
    def __init__(self):
        self.option = True

    @apply_self
    def func(self, option=False):
        return option

The parameter takes the value from the bound object, i.e. self.option.

>>> obj = MyObject()
>>> obj.func()
True

Override by passing a value.

>>> obj.func(option=False)
False

If the attribute is not in the bound object, the default value from the parameter list is used.

>>> del obj.option
>>> obj.func()
False

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

apply_defaults-0.1.5.tar.gz (3.1 kB view details)

Uploaded Source

File details

Details for the file apply_defaults-0.1.5.tar.gz.

File metadata

  • Download URL: apply_defaults-0.1.5.tar.gz
  • Upload date:
  • Size: 3.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/4.6.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.61.2 CPython/3.6.12

File hashes

Hashes for apply_defaults-0.1.5.tar.gz
Algorithm Hash digest
SHA256 7fd246314cb4bd90a6f2c4e07f6812d2dc6c85829119e591d8d8adc0993fa3cc
MD5 570534c74d9699b9120196edfd70fbf3
BLAKE2b-256 32536f20913e3a1b6902926043f7f2647dfd28b75de7cbaf97e18e31ec838d95

See more details on using hashes here.

Supported by

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