confattr.formatters module
- class confattr.formatters.AbstractCollection(item_type: Primitive[T])
Bases:
AbstractFormatter[Collection[T]]- expand_exclude_items(config_file: ConfigFile, values: Collection[T], items_to_be_excluded: str, item_format_spec: str) str
- expand_length(config_file: ConfigFile, values: Collection[T], int_format_spec: str) str
- expand_min_max(config_file: ConfigFile, values: Collection[T], func: str, item_format_spec: str) str
- expand_parsed_items(config_file: ConfigFile, values: Collection[T], item_format_spec: str) str
- expand_value(config_file: ConfigFile, values: Collection[T], format_spec: str) str
format_specsupports the following features:Filter out some values, e.g.
-foo,barexpands to all items except forfooandbar, it is no error iffooorbarare not containedGet the length,
lenexpands to the number of itemsGet extreme values,
minexpands to the smallest item andmaxexpands to the biggest item, raisesTypeErrorif the items are not comparable
To any of the above you can append another format_spec after a colon to specify how to format the items/the length.
- get_completions(config_file: ConfigFile, start_of_line: str, start: str, end_of_line: str) tuple[str, list[str], str]
- get_primitives() tuple[Primitive[T]]
If self is a Primitive data type, return self. If self is a Collection, return self.item_type.
- set_config_key(config_key: str) None
In order to generate a useful error message if parsing a value fails the key of the setting is required. This method is called by the constructor of
Config. This method must not be called more than once.- Raises:
TypeError – If
config_keyhas already been set.
- split_values(config_file: ConfigFile, values: str) Iterable[str]
- class confattr.formatters.AbstractFormatter
Bases:
Generic[T]An abstract base class for classes which define how to parse, format and complete a value. Instances of (subclasses of this class) can be passed to the
typeattribute of settings.- abstractmethod expand_value(config_file: ConfigFile, value: T, format_spec: str) str
- Parameters:
- Returns:
valueformatted according toformat_spec- Raises:
ValueError, LookupError – If
format_specis invalid
- abstractmethod format_value(config_file: ConfigFile, value: T) str
- abstractmethod get_completions(config_file: ConfigFile, start_of_line: str, start: str, end_of_line: str) tuple[str, list[str], str]
- abstractmethod get_description(config_file: ConfigFile) str
- abstractmethod get_primitives() Sequence[Primitive[Any]]
If self is a Primitive data type, return self. If self is a Collection, return self.item_type.
- abstractmethod parse_value(config_file: ConfigFile, value: str) T
- Parameters:
config_file¶ – Is needed e.g. to call
get_description()in error messagesvalue¶ – The value to be parsed
- Returns:
The parsed value
- Raises:
ValueError – If value cannot be parsed
- class confattr.formatters.CopyableAbstractFormatter
Bases:
AbstractFormatter[T]- abstractmethod copy() Self
- class confattr.formatters.Dict(key_type: Primitive[T_key], value_type: Primitive[T_val])
Bases:
AbstractFormatter[dict[T_key, T_val]]- expand_filter(config_file: ConfigFile, values: Mapping[T_key, T_val], keys_filter: str, item_format_spec: str) str
Is called by
expand_value()ifformat_spechas the pattern{^key1,key2}.
- expand_length(config_file: ConfigFile, values: Collection[T], int_format_spec: str) str
Is called by
expand_value()ifformat_specislen.
- expand_select(config_file: ConfigFile, values: Mapping[T_key, T_val], keys_select: str, item_format_spec: str) str
Is called by
expand_value()ifformat_spechas the pattern{key1,key2}.
- expand_selected(config_file: ConfigFile, values: Mapping[T_key, T_val], item_format_spec: str) str
Is called by
expand_filter()andexpand_select()to do the formatting of the filtered/selected values
- expand_single_value(config_file: ConfigFile, values: Mapping[T_key, T_val], key: str, default: str | None, item_format_spec: str) str
Is called by
expand_value()ifformat_spechas the pattern[key]or[key|default].
- expand_value(config_file: ConfigFile, values: Mapping[T_key, T_val], format_spec: str) str
format_specsupports the following features:Get a single value, e.g.
[key1]expands to the value corresponding tokey1, aKeyErroris raised ifkey1is not contained in the dictGet a single value or a default value, e.g.
[key1|default]expands to the value corresponding tokey1or todefaultifkey1is not containedGet values with their corresponding keys, e.g.
{key1,key2}expands tokey1:val1,key2:val2, if a key is not contained it is skippedFilter out elements, e.g.
{^key1}expands to allkey:valpairs except forkey1Get the length,
lenexpands to the number of items
To any of the above you can append another format_spec after a colon to specify how to format the items/the length.
- format_value(config_file: ConfigFile, values: Mapping[T_key, T_val]) str
- get_completions(config_file: ConfigFile, start_of_line: str, start: str, end_of_line: str) tuple[str, list[str], str]
- get_description(config_file: ConfigFile) str
- get_primitives() tuple[Primitive[T_key], Primitive[T_val]]
If self is a Primitive data type, return self. If self is a Collection, return self.item_type.
- parse_item(config_file: ConfigFile, item: str) tuple[T_key, T_val]
- parse_value(config_file: ConfigFile, values: str) dict[T_key, T_val]
- Parameters:
config_file¶ – Is needed e.g. to call
get_description()in error messagesvalue¶ – The value to be parsed
- Returns:
The parsed value
- Raises:
ValueError – If value cannot be parsed
- split_values(config_file: ConfigFile, values: str) Iterable[str]
- class confattr.formatters.Hex(*, allowed_values: Collection[int] | None = None)
-
- Parameters:
type¶ –
str,int,float,bool, a subclass ofenum.Enumor any class which looks likeAbstractTypeunit¶ – The unit of an int or float value
allowed_values¶ – The possible values this setting can have. Values read from a config file or an environment variable are checked against this.
type_name¶ – A name for this type which is used in the config file.
- format_value(config_file: ConfigFile, value: int) str
- get_description(config_file: ConfigFile, *, plural: bool = False, article: bool = True) str
- Parameters:
config_file¶ – May contain some additional information how to format the allowed values.
plural¶ – Whether the return value should be a plural form.
article¶ – Whether the return value is supposed to be formatted with
format_indefinite_singular_article()(ifget_type_name()is used) orPATTERN_ONE_OF(ifget_allowed_values()returns an empty sequence). This is assumed to be false ifpluralis true.
- Returns:
A short description which is displayed in the help/comment for each setting explaining what kind of value is expected. In the easiest case this is just a list of allowed value, e.g. “one of true, false”. If
type_namehas been passed to the constructor this is used instead and the list of possible values is moved to the output ofget_help(). If a unit is specified it is included, e.g. “an int in km/h”.
You can customize the return value of this method by overriding
get_type_name(),join()orformat_indefinite_singular_article()or by changing the value ofPATTERN_ONE_OF,PATTERN_ALLOWED_VALUES_UNITorPATTERN_TYPE_UNIT.
- get_help(config_file: ConfigFile) None
The help for the generic data type, independent of the unit. This is displayed once at the top of the help or the config file (if one or more settings use this type).
For example the help for an int might be:
An integer number in python 3 syntax, as decimal (e.g. 42), hexadecimal (e.g. 0x2a), octal (e.g. 0o52) or binary (e.g. 0b101010). Leading zeroes are not permitted to avoid confusion with python 2’s syntax for octal numbers. It is permissible to group digits with underscores for better readability, e.g. 1_000_000.
Return None if (and only if)
get_description()returns a simple list of all possible values and notget_type_name().- Returns:
The corresponding value in
help_dict, the value of an attribute calledhelpon thetypeor None if the return value ofget_allowed_values()is empty.- Raises:
TypeError – If the
helpattribute is not a str. If you have no influence over this attribute you can avoid checking it by adding a corresponding value tohelp_dict.NotImplementedError – If there is no help or list of allowed values. If this is raised add a
helpattribute to the class or a value for it inhelp_dict.
- parse_value(config_file: ConfigFile, value: str) int
- Parameters:
config_file¶ – Is needed e.g. to call
get_description()in error messagesvalue¶ – The value to be parsed
- Returns:
The parsed value
- Raises:
ValueError – If value cannot be parsed
- class confattr.formatters.List(item_type: Primitive[T])
Bases:
AbstractCollection[T]- expand_items(config_file: ConfigFile, values: Sequence[T], indices: str, item_format_spec: str) str
- expand_value(config_file: ConfigFile, values: Sequence[T], format_spec: str) str
format_specsupports all features inherited fromAbstractCollection.expand_value()as well as the following:Access a single item, e.g.
[0]expands to the first item,[-1]expands to the last item [1]Access several items, e.g.
[0,2,5]expands to the items at index 0, 2 and 5, if the list is not that long anIndexErroris raisedAccess a slice of items, e.g.
[:3]expands to the first three items or to as many items as the list is long if the list is not that long [1]Access a slice of items with a step, e.g.
[::-1]expands to all items in reverse order [1]
To any of the above you can append another format_spec after a colon to specify how to format the items.
[1] For more information see the common slicing operations of sequences.
- format_value(config_file: ConfigFile, values: Collection[T]) str
- get_description(config_file: ConfigFile) str
- parse_value(config_file: ConfigFile, values: str) list[T]
- Parameters:
config_file¶ – Is needed e.g. to call
get_description()in error messagesvalue¶ – The value to be parsed
- Returns:
The parsed value
- Raises:
ValueError – If value cannot be parsed
- class confattr.formatters.Primitive(type: type[T] | Callable[[...], T], *, allowed_values: Collection[T] | dict[str, T] | None = None, unit: str | None = None, type_name: str | None = None)
Bases:
CopyableAbstractFormatter[T]- Parameters:
type¶ –
str,int,float,bool, a subclass ofenum.Enumor any class which looks likeAbstractTypeunit¶ – The unit of an int or float value
allowed_values¶ – The possible values this setting can have. Values read from a config file or an environment variable are checked against this.
type_name¶ – A name for this type which is used in the config file.
- PATTERN_ALLOWED_VALUES_UNIT = '{allowed_values} (unit: {unit})'
- PATTERN_ONE_OF = 'one of {}'
- PATTERN_TYPE_UNIT = '{type} in {unit}'
- allowed_values: Collection[T] | dict[str, T] | None
If this is set and a value read from a config file is not contained it is considered invalid. If this is a mapping the keys are the string representations used in the config file.
- copy() Self
- expand_value(config_file: ConfigFile, value: T, format_spec: str) str
This method simply calls the builtin
format().
- format_allowed_values(config_file: ConfigFile, *, article: bool = True) str | None
- format_indefinite_singular_article(type_name: str) str
Getting the article right is not so easy, so a user can specify the correct article with a str attribute called
type_article. Alternatively this method can be overridden. This also gives the possibility to omit the article. https://en.wiktionary.org/wiki/Appendix:English_articles#Indefinite_singular_articlesThis is used in
get_description().
- format_value(config_file: ConfigFile, value: T) str
- get_allowed_values() Collection[T]
- get_completions(config_file: ConfigFile, start_of_line: str, start: str, end_of_line: str) tuple[str, list[str], str]
- get_description(config_file: ConfigFile, *, plural: bool = False, article: bool = True) str
- Parameters:
config_file¶ – May contain some additional information how to format the allowed values.
plural¶ – Whether the return value should be a plural form.
article¶ – Whether the return value is supposed to be formatted with
format_indefinite_singular_article()(ifget_type_name()is used) orPATTERN_ONE_OF(ifget_allowed_values()returns an empty sequence). This is assumed to be false ifpluralis true.
- Returns:
A short description which is displayed in the help/comment for each setting explaining what kind of value is expected. In the easiest case this is just a list of allowed value, e.g. “one of true, false”. If
type_namehas been passed to the constructor this is used instead and the list of possible values is moved to the output ofget_help(). If a unit is specified it is included, e.g. “an int in km/h”.
You can customize the return value of this method by overriding
get_type_name(),join()orformat_indefinite_singular_article()or by changing the value ofPATTERN_ONE_OF,PATTERN_ALLOWED_VALUES_UNITorPATTERN_TYPE_UNIT.
- get_help(config_file: ConfigFile) str | None
The help for the generic data type, independent of the unit. This is displayed once at the top of the help or the config file (if one or more settings use this type).
For example the help for an int might be:
An integer number in python 3 syntax, as decimal (e.g. 42), hexadecimal (e.g. 0x2a), octal (e.g. 0o52) or binary (e.g. 0b101010). Leading zeroes are not permitted to avoid confusion with python 2’s syntax for octal numbers. It is permissible to group digits with underscores for better readability, e.g. 1_000_000.
Return None if (and only if)
get_description()returns a simple list of all possible values and notget_type_name().- Returns:
The corresponding value in
help_dict, the value of an attribute calledhelpon thetypeor None if the return value ofget_allowed_values()is empty.- Raises:
TypeError – If the
helpattribute is not a str. If you have no influence over this attribute you can avoid checking it by adding a corresponding value tohelp_dict.NotImplementedError – If there is no help or list of allowed values. If this is raised add a
helpattribute to the class or a value for it inhelp_dict.
- get_primitives() tuple[Self]
If self is a Primitive data type, return self. If self is a Collection, return self.item_type.
- get_type_name() str
Return the name of this type (without
unitorallowed_values). This can be used inget_description()if the type can have more than just a couple of values. If that is the case a help should be provided byget_help().
- help_dict: dict[type[Any] | Callable[[...], Any], str] = {<class 'float'>: 'A floating point number in python syntax, e.g. 23, 1.414, -1e3, 3.14_15_93.', <class 'int'>: "\t\t\tAn integer number in python 3 syntax, as decimal (e.g. 42), hexadecimal (e.g. 0x2a), octal (e.g. 0o52) or binary (e.g. 0b101010).\n\t\t\tLeading zeroes are not permitted to avoid confusion with python 2's syntax for octal numbers.\n\t\t\tIt is permissible to group digits with underscores for better readability, e.g. 1_000_000.", <class 'str'>: 'A text. If it contains spaces it must be wrapped in single or double quotes.'}
Help for data types. This is used by
get_help().
- join(names: Iterable[str]) str
Join several values which have already been formatted with
format_value().
- parse_value(config_file: ConfigFile, value: str) T
- Parameters:
config_file¶ – Is needed e.g. to call
get_description()in error messagesvalue¶ – The value to be parsed
- Returns:
The parsed value
- Raises:
ValueError – If value cannot be parsed
- type: type[T] | Callable[[...], T]
str,int,float,bool, a subclass ofenum.Enumor any class that follows the pattern ofconfattr.types.AbstractType
- type_name: str | None
If this is set it is used in
get_description()and the list of possible values is moved to the output ofget_help().
- class confattr.formatters.Set(item_type: Primitive[T])
Bases:
AbstractCollection[T]- format_value(config_file: ConfigFile, values: Collection[T]) str
- get_description(config_file: ConfigFile) str
- parse_value(config_file: ConfigFile, values: str) set[T]
- Parameters:
config_file¶ – Is needed e.g. to call
get_description()in error messagesvalue¶ – The value to be parsed
- Returns:
The parsed value
- Raises:
ValueError – If value cannot be parsed