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 and with minimal effort.
No more val = val if val is not None else config.val if 'val' in config else val
ugliness.
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}}) # alteratively read a file
@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
Note: 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 value
Type hints allow the decorator to cast the config option to the desired type. Otherwise, the config option will be a string every time.
The parameter takes the value from the bound object, i.e. self.foo
.
>>> 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
File details
Details for the file apply_defaults-0.1.1.tar.gz
.
File metadata
- Download URL: apply_defaults-0.1.1.tar.gz
- Upload date:
- Size: 2.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.0.0 requests-toolbelt/0.8.0 tqdm/4.24.0 CPython/3.5.2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b8c1bc511a0368dabe1af4d80b97186296e25182d7e371d920a9633cf6a2a385 |
|
MD5 | 5c3d60fa1875f17ec93de70cf6006fe7 |
|
BLAKE2b-256 | 6fa1059eaf24fe528b68df5ccd2014e36241bf92261bd85f8e4d11721b9227b4 |