Apply default values to functions.
Makes configuration easy! Application settings come from a config file into your code cleanly.
pip install apply_defaultsThis 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 optionThe option parameter takes the value from the configuration.
>>> func()
TrueOverride the configuration by passing a value.
>>> func(option=False)
FalseIf the option is not in the configuration, the default value from the parameter list is used.
>>> config.remove_option("general", "option")
>>> func()
FalseConfigParser'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.
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 optionThe parameter takes the value from the bound object, i.e. self.option.
>>> obj = MyObject()
>>> obj.func()
TrueOverride by passing a value.
>>> obj.func(option=False)
FalseIf the attribute is not in the bound object, the default value from the parameter list is used.
>>> del obj.option
>>> obj.func()
False