confattr package¶
Submodules¶
- confattr.config module
Config
Config.LIST_SEP
Config.default_config_id
Config.format_allowed_values()
Config.format_allowed_values_or_type()
Config.format_any_value()
Config.format_type()
Config.format_value()
Config.instances
Config.key
Config.parse_and_set_value()
Config.parse_value()
Config.parse_value_part()
Config.wants_to_be_exported()
ConfigTrackingChanges
DictConfig
InstanceSpecificDictMultiConfig
MultiConfig
MultiDictConfig
- confattr.configfile module
ArgumentParser
ConfigFile
ConfigFile.COMMENT
ConfigFile.COMMENT_PREFIXES
ConfigFile.ENTER_GROUP_PREFIX
ConfigFile.ENTER_GROUP_SUFFIX
ConfigFile.FILENAME
ConfigFile.config_id
ConfigFile.enter_group()
ConfigFile.get_app_dirs()
ConfigFile.is_comment()
ConfigFile.iter_config_paths()
ConfigFile.iter_user_site_config_paths()
ConfigFile.load()
ConfigFile.load_file()
ConfigFile.load_without_resetting_config_id()
ConfigFile.parse_error()
ConfigFile.parse_line()
ConfigFile.parse_splitted_line()
ConfigFile.quote()
ConfigFile.save()
ConfigFile.save_file()
ConfigFile.save_to_open_file()
ConfigFile.set_ui_callback()
ConfigFile.write_config_id()
ConfigFileArgparseCommand
ConfigFileCommand
DEFAULT_COMMAND
Include
MultipleParseExceptions
NotificationLevel
ParseException
ParseLineKwargs
ParseSplittedLineKwargs
SaveKwargs
Set
Set.KEY_VAL_SEP
Set.aliases
Set.format_value()
Set.help
Set.iter_config_instances_to_be_saved()
Set.name
Set.parse_and_set_value()
Set.parse_key_and_set_value()
Set.primitive_types
Set.run()
Set.save()
Set.save_config_instance()
Set.set_multiple()
Set.set_with_spaces()
Set.strip_indentation()
Set.write_data_types()
Set.write_help()
SortedEnum
UiNotifier
UnknownCommand
readable_quote()
- confattr.subprocess_pipe module
- confattr.types module
Path
Regex
SubprocessCommand
SubprocessCommand.has_python_callback()
SubprocessCommand.is_installed()
SubprocessCommand.parse_str()
SubprocessCommand.python_callbacks
SubprocessCommand.register_python_callback()
SubprocessCommand.replace()
SubprocessCommand.run()
SubprocessCommand.type_name
SubprocessCommand.unregister_python_callback()
SubprocessCommandWithAlternatives
Module contents¶
Config Attributes
A python library to read and write config files with a syntax inspired by vimrc and ranger config.
- class confattr.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=<class 'argparse.HelpFormatter'>, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)¶
Bases:
ArgumentParser
- error(message: string)¶
Prints a usage message incorporating the message to stderr and exits.
If you override this in a subclass, it should not return – it should either exit or raise an exception.
- 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 attribute.- Parameters:
T
can 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. If that class has a str attributetype_name
this is used instead of the class name inside of config file. If that class has a str attributehelp
this is used instead of the doc string when explaining the type at the beginning of the config file.a
list
of 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
- LIST_SEP = ','¶
- default_config_id = 'general'¶
- instances: dict[str, confattr.config.Config[Any]] = {}¶
A mapping of all
Config
instances. The key in the mapping is thekey
attribute. The value is theConfig
instance. NewConfig
instances add themselves automatically in their constructor.
- parse_value_part(t: type[T1], value: str) T1 ¶
- Raises:
ValueError – if value is invalid
- class confattr.ConfigFile(*, notification_level: Union[Config[NotificationLevel], NotificationLevel] = NotificationLevel.ERROR, appname: str, authorname: Optional[str] = None, config_instances: dict[str, confattr.config.Config[Any]] = {}, commands: Optional[Sequence[type[confattr.configfile.ConfigFileCommand]]] = None)¶
Bases:
object
Read or write a config file.
- Parameters:
notification_level¶ – Messages of a lower priority are not passed to the callback registered with
set_ui_callback()
appname¶ – The name of the application, required for generating the path of the config file if you use
load()
orsave()
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()
orsave()
config_instances¶ – The Config instances to load or save, defaults to
Config.instances
commands¶ – The
ConfigFileCommand`s allowed in this config file, if this is :const:`None
: use the return value ofConfigFileCommand.get_command_types()
- COMMENT = '#'¶
- COMMENT_PREFIXES = ('"', '#')¶
- ENTER_GROUP_PREFIX = '['¶
- ENTER_GROUP_SUFFIX = ']'¶
- FILENAME = 'config'¶
The name of the config file used by
iter_config_paths()
. Can be changed with the environment variableCONFATTR_FILENAME
.
- 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
.These libraries should respect the environment variables
XDG_CONFIG_HOME
andXDG_CONFIG_DIRS
.
- 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 generated by joining the directories yielded by
iter_user_site_config_paths()
withConfigFile.FILENAME
(the value of the environment variableCONFATTR_FILENAME
if it is set or'config'
).
- iter_user_site_config_paths() Iterator[str] ¶
Iterate over all directories which are searched for config files, user specific first.
The directories are based on
get_app_dirs()
.
- 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.Use
set_ui_callback()
to get error messages which appeared while loading the config file. You can callset_ui_callback()
after this method without loosing any messages.- Parameters:
fn¶ – The file name of the config file (absolute or relative path)
- parse_error(msg: str, **kw: Unpack[ParseSplittedLineKwargs]) None ¶
Is called if something went wrong while trying to load a config file.
This method is called when a
ParseException
orMultipleParseExceptions
is caught. This method compiles the given information into an error message and callsUiNotifier.show_error()
.
- parse_line(line: str, **kw: Unpack[ParseLineKwargs]) None ¶
- Parameters:
line_number
andfile_name
don’t need to be passed in caseln
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], **kw: Unpack[ParseSplittedLineKwargs]) None ¶
- quote(val: str) str ¶
Quote a value if necessary so that it will be interpreted as one argument.
The default implementation calls
readable_quote()
.
- save(**kw: Unpack[SaveKwargs]) 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.In case no writable file is found the directories are created as necessary.
- 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 aset
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, **kw: Unpack[SaveKwargs]) None ¶
Save the current values of all settings to a specific file.
- Parameters:
fn¶ – The name of the file to write to. If this is not an absolute path it is relative to the current working directory.
- Raises:
FileNotFoundError – if the directory does not exist
For an explanation of the other parameters see
save()
.
- save_to_open_file(f: TextIO, **kw: Unpack[SaveKwargs]) 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_ui_callback(callback: Callable[[NotificationLevel, str | BaseException], None]) None ¶
Register a callback to a user interface in order to show messages to the user like syntax errors or invalid values in the config file.
Messages which occur before this method is called are stored and forwarded as soon as the callback is registered.
- Parameters:
ui_callback¶ – A function to display messages to the user
- class confattr.ConfigFileArgparseCommand(config_file: ConfigFile)¶
Bases:
ConfigFileCommand
An abstract subclass of
ConfigFileCommand
which usesargparse
to make parsing and providing help easier.You must implement the class method
init_parser()
to add the arguments toparser
. Instead ofrun()
you must implementrun_parsed()
. You don’t need to add a usage or the possible arguments to the doc string asargparse
will do that for you. You should, however, still give a description what this command does in the doc string.You may specify
ConfigFileCommand.name
,ConfigFileCommand.aliases
andConfigFileCommand.save()
like forConfigFileCommand
.- classmethod get_help() str ¶
- Returns:
A help text which can be presented to the user. This is generated by
ArgumentParser.format_help()
. The return value ofConfigFileCommand.get_help()
has been passed asdescription
to the constructor ofArgumentParser
, thereforehelp
/the doc string are included as well.
- abstract classmethod init_parser() None ¶
This is an abstract method which must be implemented by subclasses. Use
ArgumentParser.add_argument()
to add arguments toparser
.
- parser: ArgumentParser¶
- run(ln: Sequence[str], **kw: Unpack[ParseSplittedLineKwargs]) None ¶
Process one line which has been read from a config file
- Raises:
ParseException – if there is an error in the line (e.g. invalid syntax)
MultipleParseExceptions – if there are several errors in the same line
- class confattr.ConfigFileCommand(config_file: ConfigFile)¶
Bases:
ABC
An abstract base class for commands which can be used in a config file.
Subclasses must implement the
run()
method which is called whenConfigFile
is loading a file. Subclasses should contain a doc string so thatget_help()
can provide a description to the user. Subclasses may set thename
andaliases
attributes to change the output ofget_name()
andget_names()
.All subclasses are remembered and can be retrieved with
get_command_types()
. They are instantiated in the constructor ofConfigFile
.- classmethod delete_command_type(cmd: type[confattr.configfile.ConfigFileCommand]) None ¶
Delete
cmd
so that it is not returned anymore byget_command_types()
and that it’s name can be used by another command. Do nothing ifcmd
has already been deleted.
- classmethod get_command_types() tuple[type[confattr.configfile.ConfigFileCommand], ...] ¶
- Returns:
All subclasses of
ConfigFileCommand
which have not been deleted withdelete_command_type()
- classmethod get_help() str ¶
- Returns:
A help text which can be presented to the user. The default implementation returns
help
if given or the doc string otherwise, preprocessed byinspect.cleandoc()
.
- classmethod get_name() str ¶
- Returns:
The name which is used in config file to call this command.
If
name
is set it is returned as it is. Otherwise a name is generated based on the class name.
- classmethod get_names() Iterator[str] ¶
- Returns:
Several alternative names which can be used in a config file to call this command.
The first one is always the return value of
get_name()
. Ifaliases
is set it’s items are yielded afterwards.If one of the returned items is the empty string this class is the default command and
run()
will be called if an undefined command is encountered.
- help: str¶
A description which may be used by an in-app help. If this is not set
get_help()
uses the doc string instead.
- name: str¶
The name which is used in the config file to call this command. Use an empty string to define a default command which is used if an undefined command is encountered. If this is not set
get_name()
returns the name of this class in lower case letters and underscores replaced by hyphens.
- abstract run(ln: Sequence[str], **kw: Unpack[ParseSplittedLineKwargs]) None ¶
Process one line which has been read from a config file
- Raises:
ParseException – if there is an error in the line (e.g. invalid syntax)
MultipleParseExceptions – if there are several errors in the same line
- save(f: TextIO, **kw: Unpack[SaveKwargs]) None ¶
Write as many calls to this command as necessary to the config file in order to create the current state. There is the
config_file
attribute (which was passed to the constructor) which you can use to: - quote arguments withConfigFile.quote()
- get the comment characterConfigFile.COMMENT
- callwrite_config_id
The default implementation does nothing.
- 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:
T
can 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. If that class has a str attributetype_name
this is used instead of the class name inside of config file. If that class has a str attributehelp
this is used instead of the doc string when explaining the type at the beginning of the config file.a
list
of 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
- has_changed() bool ¶
- Returns:
True
ifvalue
has been changed since the last call tosave_value()
- restore_value() None ¶
Restore
value
to the value before the last call ofsave_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:
- Raises:
ValueError – if a key is not unique
- class confattr.Include(config_file: ConfigFile)¶
Bases:
ConfigFileCommand
- run(cmd: Sequence[str], **kw: Unpack[ParseSplittedLineKwargs]) None ¶
Process one line which has been read from a config file
- Raises:
ParseException – if there is an error in the line (e.g. invalid syntax)
MultipleParseExceptions – if there are several errors in the same line
- 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:
T
can 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. If that class has a str attributetype_name
this is used instead of the class name inside of config file. If that class has a str attributehelp
this is used instead of the doc string when explaining the type at the beginning of the config file.a
list
of 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
- 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:
- Raises:
ValueError – if a key is not unique
- 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 subclassConfigFile
you do not need to worry about this class.
- class confattr.NotificationLevel(value)¶
Bases:
SortedEnum
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 subclassConfigFile
you do not need to worry about this class.
- class confattr.SaveKwargs¶
Bases:
TypedDict
- ignore: collections.abc.Iterable[Union[confattr.config.Config[Any], confattr.config.DictConfig[Any, Any]]] | None¶
- class confattr.Set(config_file: ConfigFile)¶
Bases:
ConfigFileCommand
- KEY_VAL_SEP = '='¶
The separator which is used between a key and it’s value
- format_value(instance: Config[Any], config_id: Optional[ConfigId]) str ¶
- Parameters:
instance¶ – The config value to be saved
config_id¶ – Which value to be written in case of a
MultiConfig
, should beNone
for a normalConfig
instance
- Returns:
A str representation to be written to the config file
Convert the value of the
Config
instance into a str withConfig.format_value()
.
- iter_config_instances_to_be_saved(**kw: Unpack[SaveKwargs]) Iterator[Config[object]] ¶
-
Iterate over all given
config_instances
and expand allDictConfig
instances into theConfig
instances they consist of. Sort the resulting list ifconfig_instances
is not alist
or atuple
. Yield allConfig
instances which are not (directly or indirectly) contained inignore
and whereConfig.wants_to_be_exported()
returns true.
- parse_and_set_value(instance: Config[Any], value: str) None ¶
Parse the given value str and assign it to the given instance by calling
Config.parse_and_set_value()
withConfigFile.config_id
ofconfig_file
. Afterwards callUiNotifier.show_info()
.
- parse_key_and_set_value(key: str, value: str) None ¶
Find the corresponding
Config
instance forkey
and pass it toparse_and_set_value()
.- Raises:
ParseException – if key is invalid or
parse_and_set_value()
raises aValueError
- primitive_types = {<class 'str'>, <class 'bool'>, <class 'int'>, <class 'float'>}¶
data types which have no help, these are skipped by
write_data_types()
- run(cmd: Sequence[str], **kw: Unpack[ParseSplittedLineKwargs]) None ¶
Call
set_multiple()
if the first argument containsKEY_VAL_SEP
otherwiseset_with_spaces()
.- Raises:
ParseException – if something is wrong (no arguments given, invalid syntax, invalid key, invalid value)
- save(f: TextIO, **kw: Unpack[SaveKwargs]) None ¶
- Parameters:
f¶ – The file to write to
no_multi¶ (bool) – If true: treat
MultiConfig
instances like normalConfig
instances and only write their default value. If false: SeparateMultiConfig
instances and print them once for everyMultiConfig.config_ids
.comments¶ (bool) – If false: don’t call
write_data_types()
.
Iterate over all
Config
instances withiter_config_instances_to_be_saved()
, split them into normalConfig
andMultiConfig
and write them withsave_config_instance()
. But before that setlast_name
to None (which is used bywrite_help()
) and callwrite_data_types()
.
- save_config_instance(f: TextIO, instance: Config[object], config_id: ConfigId | None, **kw: Unpack[SaveKwargs]) None ¶
- Parameters:
f¶ – The file to write to
instance¶ – The config value to be saved
config_id¶ – Which value to be written in case of a
MultiConfig
, should beNone
for a normalConfig
instancecomments¶ (bool) – If true: call
write_help()
Convert the
Config
instance into a value str withformat_value()
, wrap it in quotes if necessary withconfig_file.quote()
and print it tof
.
- set_multiple(cmd: Sequence[str]) None ¶
Process one line of the format
set key=value [key2=value2 ...]
- Raises:
MultipleParseExceptions – if something is wrong (invalid syntax, invalid key, invalid value)
- set_with_spaces(cmd: Sequence[str]) None ¶
Process one line of the format
set key [=] value
- Raises:
ParseException – if something is wrong (invalid syntax, invalid key, invalid value)
- static strip_indentation(lines: Iterable[str]) Iterator[str] ¶
Strip the indentation of the first line from all lines.
- Raises:
AssertionError – if one of the following lines does not start with the same indentation
- write_data_types(f: TextIO, config_instances: Iterable[Config[object]]) None ¶
-
Write comments which explain all non-primitive data types occurring in
config_instances
based on theirhelp
attribute.
- write_help(f: TextIO, instance: Config[Any]) None ¶
-
Write a comment which explains the meaning and usage of this setting based on
Config.format_allowed_values_or_type()
andConfig.help
.Use
last_name
to write the help only once for allConfig
instances belonging to the sameDictConfig
instance.