confattr package

Submodules

Module contents

Config Attributes

A python library to read and write config files with a syntax inspired by vimrc and ranger config.

class confattr.Config(key: str, default: T, *, help: Optional[Union[str, dict[T, str]]] = None, unit: Optional[str] = None, parent: Optional[DictConfig[Any, T]] = None, allowed_values: Optional[Sequence[T]] = 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 value if 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 instance.

Parameters:
  • key – The name of this setting in the config file

  • default – The default value of this setting

  • help – A description of this setting

  • unit – The unit of an int or float value

T can be one of:
  • str

  • int

  • float

  • bool

  • a subclass of enum.Enum

  • a class where __str__() returns a string representation which can be passed to the constructor to create an equal object. If that class has a str attribute type_name this is used instead of the class name inside of config file. If that class has a str attribute help this is used instead of the doc string when explaining the type at the beginning of the config file.

Raises:

ValueError – if key is not unique

LIST_SEP = ','
default_config_id = 'general'
format_allowed_values(t: Optional[type[Any]] = None) str
format_allowed_values_or_type(t: Optional[type[Any]] = None) str
format_any_value(value: Any) str
format_type(t: Optional[type[Any]] = None) str
format_value(config_id: Optional[ConfigId]) str
instances: dict[str, confattr.config.Config[Any]] = {}
property key: str
parse_and_set_value(config_id: Optional[ConfigId], value: str) None
parse_value(value: str) T
parse_value_part(t: type[T1], value: str) T1
Raises:

ValueError – if value is invalid

wants_to_be_exported() bool
class confattr.ConfigFile(ui_callback: Callable[[NotificationLevel, str | BaseException], None], *, appname: str, authorname: Optional[str] = None, config_instances: dict[str, confattr.config.Config[Any]] = {})

Bases: object

Read or write a config file.

Parameters:
  • ui_callback – A function to display messages to the user

  • appname – The name of the application, required for generating the path of the config file if you use load() or save()

  • authorname – The name of the developer of the application, on MS Windows useful for generating the path of the config file if you use load() or save()

  • config_instances – The Config instances to load or save

COMMENT = '#'
COMMENT_PREFIXES = ('"', '#')
ENTER_GROUP_PREFIX = '['
ENTER_GROUP_SUFFIX = ']'
FILENAME = 'config'
INCLUDE = ('include',)
KEY_VAL_SEP = '='
SET = ('set',)
enter_group(ln: str) bool

Check if ln starts a new group and set config_id if it does.

Parameters:

ln – The current line

Returns:

True if ln starts a new group

format_value(instance: Config[Any], config_id: Optional[ConfigId]) str
get_app_dirs() AppDirs

Create or get a cached AppDirs instance with multipath support enabled.

When creating a new instance, platformdirs, xdgappdirs and appdirs are tried, in that order. The first one installed is used. appdirs, the original of the two forks and the only one of the three with type stubs, is specified in pyproject.toml as a hard dependency so that at least one of the three should always be available. I am not very familiar with the differences but if a user finds that appdirs does not work for them they can choose to use an alternative with pipx inject appname xdgappdirs|platformdirs.

include(fn: str | None, cmd: Sequence[str]) None
is_comment(ln: str) bool

Check if ln is a comment.

Parameters:

ln – The current line

Returns:

True if ln is a comment

iter_config_paths() Iterator[str]

Iterate over all paths which are checked for config files, user specific first.

Use this method if you want to tell the user where the application is looking for it’s config file. The first existing file yielded by this method is used by load(). The paths are based on get_app_dirs().

iter_user_site_config_paths() Iterator[str]

Iterate over all directories which are searched for config files.

load() None

Load the first existing config file returned by iter_config_paths().

If there are several config files a user specific config file is preferred. If a user wants a system wide config file to be loaded, too, they can explicitly include it in their config file.

load_file(fn: str) None

Load a config file and change the Config objects accordingly. Errors are communicated via ui_notifier.

Parameters:

fn – The file name of the config file (absolute or relative path)

load_without_resetting_config_id(fn: str) None
parse_and_set_value(instance: Config[Any], value: str) None
parse_error(msg: str, ln: str, lnno: int | None) None

Is called if something went wrong while trying to load a config file. This method compiles the given information into an error message and calls UiNotifier.show_error().

Parameters:
  • msg – The error message

  • ln – The line where the error occured

  • lnno – The number of the line

parse_key_and_set_value(key: str, value: str) None
parse_line(ln: str, lnno: Optional[int] = None, fn: Optional[str] = None) None
Parameters:
  • ln – The line to be parsed

  • lnno – The number of the line, used in error messages

  • fn – The name of the file from which ln was read (absolute or relative path), used in error messages and for relative imports

lnno and fn are allowed to be None in case ln is not read from a config file but from a command line.

parse_error() is called if something goes wrong, e.g. invalid key or invalid value.

parse_splitted_line(ln_splitted: Sequence[str], ln: str, lnno: Optional[int] = None, fn: Optional[str] = None) None
primitive_types = {<class 'str'>, <class 'bool'>, <class 'int'>, <class 'float'>}
save(config_instances: Optional[Iterable[Union[Config[Any], DictConfig[Any, Any]]]] = None, *, ignore: Optional[Iterable[Union[Config[Any], DictConfig[Any, Any]]]] = None, no_multi: bool = False, comments: bool = True) str

Save the current values of all settings to the first existing and writable file returned by iter_config_paths() or to the first path if none of the files are existing and writable.

Parameters:
  • config_instances – Do not save all settings but only those given. If this is a list they are written in the given order. If this is a set they are sorted by their keys.

  • ignore – Do not write these settings to the file.

  • no_multi – Do not write several sections. For MultiConfig instances write the default values only.

  • comments – Write comments with allowed values and help.

Returns:

The path to the file which has been written

save_file(fn: str, config_instances: Optional[Iterable[Union[Config[Any], DictConfig[Any, Any]]]] = None, *, ignore: Optional[Iterable[Union[Config[Any], DictConfig[Any, Any]]]] = None, no_multi: bool = False, comments: bool = True) None

Save the current values of all settings to a specific file.

Parameters:

fn – The name of the file to write to (absolute or relative path)

For an explanation of the other parameters see save().

save_to_open_file(f: TextIO, config_instances: Optional[Iterable[Union[Config[Any], DictConfig[Any, Any]]]] = None, *, ignore: Optional[Iterable[Union[Config[Any], DictConfig[Any, Any]]]] = None, no_multi: bool = False, comments: bool = True) None

Save the current values of all settings to file-like object.

Parameters:

f – The file to write to

For an explanation of the other parameters see save().

set(cmd: Sequence[str]) None
set_multiple(cmd: Sequence[str]) None
set_with_spaces(cmd: Sequence[str]) None
static strip_indentation(lines: Iterable[str]) Iterator[str]
unknown_command(ln_splitted: Sequence[str], ln: str, lnno: int | None, fn: str | None) Optional[NoReturn]
write_data_types(f: TextIO, config_keys: Iterable[str], ignore: collections.abc.Iterable[confattr.config.Config[Any]] | None) None
write_help(f: TextIO, instance: Config[Any]) None
class confattr.ConfigTrackingChanges(key: str, default: T, *, help: Optional[Union[str, dict[T, str]]] = None, unit: Optional[str] = None, parent: Optional[DictConfig[Any, T]] = None, allowed_values: Optional[Sequence[T]] = None)

Bases: Config[T]

Parameters:
  • key – The name of this setting in the config file

  • default – The default value of this setting

  • help – A description of this setting

  • unit – The unit of an int or float value

T can be one of:
  • str

  • int

  • float

  • bool

  • a subclass of enum.Enum

  • a class where __str__() returns a string representation which can be passed to the constructor to create an equal object. If that class has a str attribute type_name this is used instead of the class name inside of config file. If that class has a str attribute help this is used instead of the doc string when explaining the type at the beginning of the config file.

Raises:

ValueError – if key is not unique

has_changed() bool
Returns:

True if value has been changed since the last call to save_value()

restore_value() None

Restore value to the value before the last call of save_value().

save_value(new_value: T) None

Save the current value and assign new_value to value.

property value: T
class confattr.DictConfig(key_prefix: str, default_values: dict[T_KEY, T], *, ignore_keys: Container[T_KEY] = {}, unit: Optional[str] = None, help: Optional[str] = None, allowed_values: Optional[Sequence[T]] = None)

Bases: Generic[T_KEY, T]

Parameters:
  • key_prefix

  • default

  • ignore_keys

  • unit

  • help

Raises:

ValueError – if a key is not unique

format_key(key: T_KEY) str
iter_keys() Iterator[str]
new_config(key: str, default: T, *, unit: str | None, help: str | dict[T, str] | None) Config[T]
class confattr.InstanceSpecificDictMultiConfig(dmc: MultiDictConfig[T_KEY, T], config_id: ConfigId)

Bases: Generic[T_KEY, T]

class confattr.MultiConfig(key: str, default: T, *, unit: Optional[str] = None, help: Optional[Union[str, dict[T, str]]] = None, parent: Optional[MultiDictConfig[Any, T]] = None, allowed_values: Optional[Sequence[T]] = None)

Bases: Config[T]

Parameters:
  • key – The name of this setting in the config file

  • default – The default value of this setting

  • help – A description of this setting

  • unit – The unit of an int or float value

T can be one of:
  • str

  • int

  • float

  • bool

  • a subclass of enum.Enum

  • a class where __str__() returns a string representation which can be passed to the constructor to create an equal object. If that class has a str attribute type_name this is used instead of the class name inside of config file. If that class has a str attribute help this is used instead of the doc string when explaining the type at the beginning of the config file.

Raises:

ValueError – if key is not unique

config_ids: list[confattr.config.ConfigId] = []
format_value(config_id: Optional[ConfigId]) str
parse_and_set_value(config_id: Optional[ConfigId], value: str) None
classmethod reset() None
class confattr.MultiDictConfig(key_prefix: str, default_values: dict[T_KEY, T], *, ignore_keys: Container[T_KEY] = {}, unit: Optional[str] = None, help: Optional[str] = None, allowed_values: Optional[Sequence[T]] = None)

Bases: DictConfig[T_KEY, T]

Parameters:
  • key_prefix

  • default

  • ignore_keys

  • unit

  • help

Raises:

ValueError – if a key is not unique

new_config(key: str, default: T, *, unit: str | None, help: str | dict[T, str] | None) MultiConfig[T]
exception confattr.MultipleParseExceptions(exceptions: Sequence[ParseException])

Bases: Exception

This is raised and caught inside of ConfigFile to communicate errors while parsing a config file where multiple settings are set in the same line. If you don’t intend to subclass ConfigFile you do not need to worry about this class.

class confattr.NotificationLevel(value)

Bases: Enum

An enumeration.

ERROR = 'error'
INFO = 'info'
exception confattr.ParseException

Bases: Exception

This is raised and caught inside of ConfigFile to communicate errors while parsing a config file. If you don’t intend to subclass ConfigFile you do not need to worry about this class.

confattr.readable_quote(value: str) str

This function has the same goal like shlex.quote() but tries to generate better readable output.

Parameters:

value – A value which is intended to be used as a command line argument

Returns:

A POSIX compliant quoted version of value