Optional parameters

Providing a value to the default keyword upon parameter instantiation will make that parameter optional in a sense that it can be omitted in the configuration source. In that case the default value will be chosen instead.

Sometimes, however, it might be useful to know whether a parameter's value was loaded from the configuration source or if it used the default. Suppose you have an Integer representing the seed for RNG and in case the user doesn't specify a RNS seed you'd like to use the current sytem time. Setting Integer(default=None) doesn't help because None is internally treated as "no default given". Instead you can set Integer(optional=True) and then check later on if the value of the parameter is None.

from hanna import Configurable, Integer

class Settings(Configurable):
    # This is treated as "no default given", i.e. the parameter is
    # non-optional and the framework will raise an exception if it
    # is not specified.
    rng_seed = Integer(default=None)
    
    # This marks the parameter explictly as optional and as a result
    # it can be omitted from the configuration source. In that case
    # the default `default` will be used (which is `None`).
    rng_seed = Integer(optional=True)

settings = Settings()
assert setting.rng_seed is None

settings = Settings({'rng_seed': 123})
assert settings.rng_seed == 123

Last updated