# 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_spec` supports the following features:

    - Filter out some values, e.g. `-foo,bar` expands to all items except for `foo` and `bar`, it is no error if `foo` or `bar` are not contained

    - Get the length, `len` expands to the number of items

    - Get extreme values, `min` expands to the smallest item and `max` expands to the biggest item, raises `TypeError` if 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_key` has 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 `type` attribute of settings.

  config_key: str | None = None
  abstract expand_value(config_file: ConfigFile, value: T, format_spec: str) → str
    Parameters:

      - config_file – has e.g. the `ITEM_SEP` attribute

      - value – The value to be formatted

      - format_spec – A format specifier

    Returns:

      `value` formatted according to `format_spec`

    Raises:

      ValueError, LookupError – If `format_spec` is invalid

  abstract format_value(config_file: ConfigFile, value: T) → str
  abstract get_completions(config_file: ConfigFile, start_of_line: str, start: str, end_of_line: str) → tuple[str, list[str], str]
  abstract get_description(config_file: ConfigFile) → str
  abstract get_primitives() → Sequence[Primitive[Any]]

    If self is a Primitive data type, return self. If self is a Collection, return self.item_type.

  abstract parse_value(config_file: ConfigFile, value: str) → T
    Parameters:

      - config_file – Is needed e.g. to call `get_description()` in error messages

      - value – The value to be parsed

    Returns:

      The parsed value

    Raises:

      ValueError – If value cannot be parsed

  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_key` has already been set.

class confattr.formatters.CopyableAbstractFormatter

  Bases: `AbstractFormatter`[`T`]

  abstract 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()` if `format_spec` has the pattern `{^key1,key2}`.

  expand_length(config_file: ConfigFile, values: Collection[T], int_format_spec: str) → str

    Is called by `expand_value()` if `format_spec` is `len`.

  expand_select(config_file: ConfigFile, values: Mapping[T_key, T_val], keys_select: str, item_format_spec: str) → str

    Is called by `expand_value()` if `format_spec` has 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()` and `expand_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()` if `format_spec` has the pattern `[key]` or `[key|default]`.

  expand_value(config_file: ConfigFile, values: Mapping[T_key, T_val], format_spec: str) → str

    `format_spec` supports the following features:

    - Get a single value, e.g. `[key1]` expands to the value corresponding to `key1`, a `KeyError` is raised if `key1` is not contained in the dict

    - Get a single value or a default value, e.g. `[key1|default]` expands to the value corresponding to `key1` or to `default` if `key1` is not contained

    - Get values with their corresponding keys, e.g. `{key1,key2}` expands to `key1:val1,key2:val2`, if a key is not contained it is skipped

    - Filter out elements, e.g. `{^key1}` expands to all `key:val` pairs except for `key1`

    - Get the length, `len` expands 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 messages

      - value – 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)

  Bases: `Primitive`[`int`]

  Parameters:

    - type – `str`, `int`, `float`, `bool`, a subclass of `enum.Enum` or any class which looks like `AbstractType`

    - unit – 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()` (if `get_type_name()` is used) or `PATTERN_ONE_OF` (if `get_allowed_values()` returns an empty sequence). This is assumed to be false if `plural` is 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_name` has been passed to the constructor this is used instead and the list of possible values is moved to the output of `get_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()` or `format_indefinite_singular_article()` or by changing the value of `PATTERN_ONE_OF`, `PATTERN_ALLOWED_VALUES_UNIT` or `PATTERN_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 not `get_type_name()`.

    Returns:

      The corresponding value in `help_dict`, the value of an attribute called `help` on the `type` or None if the return value of `get_allowed_values()` is empty.

    Raises:

      - TypeError – If the `help` attribute is not a str. If you have no influence over this attribute you can avoid checking it by adding a corresponding value to `help_dict`.

      - NotImplementedError – If there is no help or list of allowed values. If this is raised add a `help` attribute to the class or a value for it in `help_dict`.

  parse_value(config_file: ConfigFile, value: str) → int
    Parameters:

      - config_file – Is needed e.g. to call `get_description()` in error messages

      - value – 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_spec` supports all features inherited from `AbstractCollection.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 an `IndexError` is raised

    - Access 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_slice(s: str) → slice
  parse_slices(indices: str) → Iterator[slice]
  parse_value(config_file: ConfigFile, values: str) → list[T]
    Parameters:

      - config_file – Is needed e.g. to call `get_description()` in error messages

      - value – 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 of `enum.Enum` or any class which looks like `AbstractType`

    - unit – 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_articles

    This 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()` (if `get_type_name()` is used) or `PATTERN_ONE_OF` (if `get_allowed_values()` returns an empty sequence). This is assumed to be false if `plural` is 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_name` has been passed to the constructor this is used instead and the list of possible values is moved to the output of `get_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()` or `format_indefinite_singular_article()` or by changing the value of `PATTERN_ONE_OF`, `PATTERN_ALLOWED_VALUES_UNIT` or `PATTERN_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 not `get_type_name()`.

    Returns:

      The corresponding value in `help_dict`, the value of an attribute called `help` on the `type` or None if the return value of `get_allowed_values()` is empty.

    Raises:

      - TypeError – If the `help` attribute is not a str. If you have no influence over this attribute you can avoid checking it by adding a corresponding value to `help_dict`.

      - NotImplementedError – If there is no help or list of allowed values. If this is raised add a `help` attribute to the class or a value for it in `help_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 `unit` or `allowed_values`). This can be used in `get_description()` if the type can have more than just a couple of values. If that is the case a help should be provided by `get_help()`.

    Returns:

      `type_name` if it has been passed to the constructor, the value of an attribute of `type` called `type_name` if existing or the lower case name of the class stored in `type` otherwise

  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 messages

      - value – 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 of `enum.Enum` or any class that follows the pattern of `confattr.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 of `get_help()`.

  unit: str | None

    The unit of a number

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 messages

      - value – The value to be parsed

    Returns:

      The parsed value

    Raises:

      ValueError – If value cannot be parsed

confattr.formatters.format_primitive_value(value: object) → str