confattr.config module
- class confattr.config.Config(key: str, default: T, *, type: AbstractFormatter[T] | None = None, unit: str | None = None, allowed_values: Sequence[T] | dict[str, T] | None = None, help: str | dict[T, str] | None = None, parent: DictConfig[Any, T] | None = None)
Bases:
Generic[T]Each instance of this class represents a setting which can be changed in a config file.
This class implements the descriptor protocol to return
valueif an instance of this class is accessed as an instance attribute. If you want to get this object you need to access it as a class attribute.- Parameters:
key¶ – The name of this setting in the config file
default¶ – The default value of this setting
type¶ – How to parse, format and complete a value. Usually this is determined automatically based on
default. But ifdefaultis an empty list the item type cannot be determined automatically so that this argument must be passed explicitly. This also gives the possibility to format a standard type differently e.g. asHex. It is not permissible to reuse the same object for different settings, otherwiseAbstractFormatter.set_config_key()will throw an exception.unit¶ – The unit of an int or float value (only if type is None)
allowed_values¶ – The possible values this setting can have. Values read from a config file or an environment variable are checked against this. The
defaultvalue is not checked. (Only if type is None.)help¶ – A description of this setting
parent¶ – Applies only if this is part of a
DictConfig
Tcan be one of:a subclass of
enum.Enum(the value used in the config file is the name in lower case letters with hyphens instead of underscores)a class where
__str__()returns a string representation which can be passed to the constructor to create an equal object. A help which is written to the config file must be provided as a str in the class attributehelpor by adding it toPrimitive.help_dict. If that class has a str attributetype_namethis is used instead of the class name inside of config file.a
listof any of the afore mentioned data types. The list may not be empty when it is passed to this constructor so that the item type can be derived but it can be emptied immediately afterwards. (The type of the items is not dynamically enforced—that’s the job of a static type checker—but the type is mentioned in the help.)
- Raises:
ValueError – if key is not unique
TypeError – if
defaultis an empty list/set because the first element is used to infer the data type to which a value given in a config file is convertedTypeError – if this setting is a number or a list of numbers and
unitis not givenTimingError – if this setting is defined after creating a
ConfigFileobject without passing a list or set of settings toconfig_instances
- default_config_id = 'general'
- get_value(config_id: ConfigId | None) T
- Returns:
This getter is only to have a common interface for
ConfigandMultiConfig
- help: str | dict[T, str] | None
A description of this setting or a description for each allowed value.
- instances: dict[str, Config[Any]] = {}
A mapping of all
Configinstances. The key in the mapping is thekeyattribute. The value is theConfiginstance. NewConfiginstances add themselves automatically in their constructor.
- is_value_valid() bool
- Returns:
true unless the value of an
ExplicitConfiginstance has not been set yet
- classmethod iter_instances() Iterator[Config[Any] | DictConfig[Any, Any]]
Yield the instances in
instancesbut mergeDictConfigitems to a singleDictConfiginstance so that they can be sorted differently.
- property key: str
The name of this setting which is used in the config file. This must be unique. You can change this attribute but only as long as no
ConfigFileorConfigManagerhas been instantiated.
- classmethod pop_key_changer() Callable[[str], str]
Undo the last call to
push_key_changer().
- classmethod push_key_changer(callback: Callable[[str], str]) None
Modify the key of all settings which will be defined after calling this method.
Call this before an
importandpop_key_changer()after it if you are unhappy with the keys of a third party library. If you import that library in different modules make sure you do this at the import which is executed first.- Parameters:
callback¶ – A function which takes the key as argument and returns the modified key.
- set_value(config_id: ConfigId | None, value: T) None
This method is just to provide a common interface for
ConfigandMultiConfig. If you know that you are dealing with a normalConfigyou can setvaluedirectly.
- type: AbstractFormatter[T]
Information about data type, unit and allowed values for
valueand methods how to parse, format and complete it.
- value: T
The value of this setting.
- class confattr.config.ConfigId
An identifier to specify which value of a
MultiConfigorMultiDictConfigshould be used for a certain object.alias of
str
- class confattr.config.DictConfig(key_prefix: str, default_values: dict[T_KEY, T], *, type: CopyableAbstractFormatter[T] | None = None, ignore_keys: Container[T_KEY] = {}, unit: str | None = None, allowed_values: Sequence[T] | dict[str, T] | None = None, help: str | None = None, sort: Sort = Sort.NAME)
Bases:
Generic[T_KEY,T]A container for several settings which belong together. Except for
__eq__()and__ne__()it behaves like a normalMappingbut internally the items are stored inConfiginstances.In contrast to a
Configinstance it does not make a difference whether an instance of this class is accessed as a type or instance attribute.- Parameters:
key_prefix¶ – A common prefix which is used by
format_key()to generate thekeyby which the setting is identified in the config filedefault_values¶ – The content of this container. A
Configinstance is created for each of these values (except if the key is contained inignore_keys). Seeformat_key().type¶ – How to parse, format and complete a value. Usually this is determined automatically based on
default_values. But if you want more control you can implement your own class and pass it to this parameter.ignore_keys¶ – All items which have one of these keys are not stored in a
Configinstance, i.e. cannot be set in the config file.unit¶ – The unit of all items (only if type is None)
allowed_values¶ – The possible values these settings can have. Values read from a config file or an environment variable are checked against this. The
default_valuesare not checked. (Only if type is None.)help¶ – A help for all items
sort¶ – How to sort the items of this dictionary in the config file/documentation
- Raises:
ValueError – if a key is not unique
- format_key(key: T_KEY) str
Generate a key by which the setting can be identified in the config file based on the dict key by which the value is accessed in the python code.
- Returns:
key_prefix+ dot +key
- iter_configs() Iterator[Config[T]]
Iterate over the
Configinstances contained in this dict, sorted by the argument passed tosortin the constructor
- class confattr.config.ExplicitConfig(key: str, type: AbstractFormatter[T] | type[T] | None = None, *, unit: str | None = None, allowed_values: Sequence[T] | dict[str, T] | None = None, help: str | dict[T, str] | None = None, parent: DictConfig[Any, T] | None = None)
Bases:
Config[T]A setting without a default value which requires the user to explicitly set a value in the config file or pass it as command line argument.
You can use
is_value_valid()in order to check whether this config has a value or not.If you try to use the value before it has been set: If you try to access the config as instance attribute (
object.config) aTypeErroris thrown. Otherwise (config.value)Noneis returned.- Parameters:
key¶ – The name of this setting in the config file
type¶ – How to parse, format and complete a value. Any class which can be passed to
Primitiveor an object of a subclass ofAbstractFormatter.unit¶ – The unit of an int or float value (only if type is not an
AbstractFormatter)allowed_values¶ – The possible values this setting can have. Values read from a config file or an environment variable are checked against this. The
defaultvalue is not checked. (Only if type is not anAbstractFormatter.)help¶ – A description of this setting
parent¶ – Applies only if this is part of a
DictConfig
- is_value_valid() bool
- Returns:
true unless the value of an
ExplicitConfiginstance has not been set yet
- class confattr.config.InstanceSpecificDictMultiConfig(mdc: MultiDictConfig[T_KEY, T], config_id: ConfigId)
Bases:
Generic[T_KEY,T]An intermediate instance which is returned when accsessing a
MultiDictConfigas an instance attribute. Can be indexed like a normaldict.
- class confattr.config.MultiConfig(key: str, default: T, *, type: AbstractFormatter[T] | None = None, unit: str | None = None, allowed_values: Sequence[T] | dict[str, T] | None = None, help: str | dict[T, str] | None = None, parent: MultiDictConfig[Any, T] | None = None, check_config_id: Callable[[MultiConfig[T], ConfigId], None] | None = None)
Bases:
Config[T]A setting which can have different values for different objects.
This class implements the descriptor protocol to return one of the values in
valuesdepending on aconfig_idattribute of the owning object if an instance of this class is accessed as an instance attribute. If there is no value for theconfig_idinvaluesvalueis returned instead. If the owning instance does not have aconfig_idattribute anAttributeErroris raised.In the config file a group can be opened with
[config-id]. Then all followingsetcommands set the value for the specified config id.- Parameters:
key¶ – The name of this setting in the config file
default¶ – The default value of this setting
help¶ – A description of this setting
type¶ – How to parse, format and complete a value. Usually this is determined automatically based on
default. But ifdefaultis an empty list the item type cannot be determined automatically so that this argument must be passed explicitly. This also gives the possibility to format a standard type differently e.g. asHex. It is not permissible to reuse the same object for different settings, otherwiseAbstractFormatter.set_config_key()will throw an exception.unit¶ – The unit of an int or float value (only if type is None)
allowed_values¶ – The possible values this setting can have. Values read from a config file or an environment variable are checked against this. The
defaultvalue is not checked. (Only if type is None.)parent¶ – Applies only if this is part of a
MultiDictConfigcheck_config_id¶ – Is called every time a value is set in the config file (except if the config id is
default_config_id—that is always allowed). The callback should raise aParseExceptionif the config id is invalid.
- check_config_id: Callable[[MultiConfig[T], ConfigId], None] | None
The callable which has been passed to the constructor as
check_config_id
- config_ids: list[ConfigId] = []
A list of all config ids for which a value has been set in any instance of this class (regardless of via code or in a config file and regardless of whether the value has been deleted later on). This list is cleared by
reset().
- classmethod reset() None
Clear
config_idsand clearvaluesfor all instances inConfig.instances
- set_value(config_id: ConfigId | None, value: T) None
Check
config_idby callingcheck_config_id()and set the value for the object(s) identified byconfig_id.If you know that
config_idis valid you can also change the items ofvaluesdirectly. That is especially useful in test automation withpytest.MonkeyPatch.setitem().If you want to set the default value you can also set
valuedirectly.
- class confattr.config.MultiDictConfig(key_prefix: str, default_values: dict[T_KEY, T], *, type: CopyableAbstractFormatter[T] | None = None, ignore_keys: Container[T_KEY] = {}, unit: str | None = None, allowed_values: Sequence[T] | dict[str, T] | None = None, help: str | None = None, check_config_id: Callable[[MultiConfig[T], ConfigId], None] | None = None)
Bases:
DictConfig[T_KEY,T]A container for several settings which can have different values for different objects.
This is essentially a
DictConfigusingMultiConfiginstead of normalConfig. However, in order to return different values depending on theconfig_idof the owning instance, it implements the descriptor protocol to return anInstanceSpecificDictMultiConfigif it is accessed as an instance attribute.- Parameters:
key_prefix¶ – A common prefix which is used by
format_key()to generate thekeyby which the setting is identified in the config filedefault_values¶ – The content of this container. A
Configinstance is created for each of these values (except if the key is contained inignore_keys). Seeformat_key().type¶ – How to parse, format and complete a value. Usually this is determined automatically based on
default_values. But if you want more control you can implement your own class and pass it to this parameter.ignore_keys¶ – All items which have one of these keys are not stored in a
Configinstance, i.e. cannot be set in the config file.unit¶ – The unit of all items (only if type is None)
allowed_values¶ – The possible values these settings can have. Values read from a config file or an environment variable are checked against this. The
default_valuesare not checked. (Only if type is None.)help¶ – A help for all items
check_config_id¶ – Is passed through to
MultiConfig
- Raises:
ValueError – if a key is not unique
- exception confattr.config.TimingError
Bases:
ExceptionIs raised when trying to instantiate
Configif aConfigFilehas been instantiated before without passing an explicit list or set toconfig_instancesor when trying to change akeyafter creating anyConfigFilebecause such changes would otherwise be silently ignored by thatConfigFile.