confattr package
Submodules
- confattr.config module
Config
Config.LIST_SEP
Config.allowed_values
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.get_allowed_values()
Config.get_stringified_allowed_values()
Config.help
Config.instances
Config.key
Config.parse_value()
Config.parse_value_part()
Config.set_value()
Config.unit
Config.value
Config.wants_to_be_exported()
DictConfig
InstanceSpecificDictMultiConfig
MultiConfig
MultiDictConfig
- confattr.configfile module
ArgPos
ArgumentParser
ConfigFile
ConfigFile.COMMENT
ConfigFile.COMMENT_PREFIXES
ConfigFile.ENTER_GROUP_PREFIX
ConfigFile.ENTER_GROUP_SUFFIX
ConfigFile.config_directory
ConfigFile.config_id
ConfigFile.config_instances
ConfigFile.config_name
ConfigFile.config_path
ConfigFile.context_file_name
ConfigFile.context_line
ConfigFile.context_line_number
ConfigFile.create_formatter()
ConfigFile.enable_config_ids
ConfigFile.enter_group()
ConfigFile.env_variables
ConfigFile.envprefix
ConfigFile.find_arg()
ConfigFile.get_app_dirs()
ConfigFile.get_command()
ConfigFile.get_completions()
ConfigFile.get_completions_command()
ConfigFile.get_completions_command_name()
ConfigFile.get_completions_enter_group()
ConfigFile.get_env_name()
ConfigFile.get_help()
ConfigFile.get_help_config_id()
ConfigFile.get_save_path()
ConfigFile.is_comment()
ConfigFile.iter_config_paths()
ConfigFile.iter_user_site_config_paths()
ConfigFile.load()
ConfigFile.load_env()
ConfigFile.load_file()
ConfigFile.load_without_resetting_config_id()
ConfigFile.parse_error()
ConfigFile.parse_line()
ConfigFile.parse_split_line()
ConfigFile.quote()
ConfigFile.save()
ConfigFile.save_file()
ConfigFile.save_to_open_file()
ConfigFile.save_to_writer()
ConfigFile.set_save_default_arguments()
ConfigFile.set_ui_callback()
ConfigFile.split_line()
ConfigFile.split_line_ignore_errors()
ConfigFile.write_config_id()
ConfigFile.write_help()
ConfigFileArgparseCommand
ConfigFileArgparseCommand.after_positional_argument_marker()
ConfigFileArgparseCommand.get_action_for_option()
ConfigFileArgparseCommand.get_action_for_positional_argument()
ConfigFileArgparseCommand.get_completions()
ConfigFileArgparseCommand.get_completions_for_action()
ConfigFileArgparseCommand.get_completions_for_option_argument()
ConfigFileArgparseCommand.get_completions_for_option_name()
ConfigFileArgparseCommand.get_completions_for_positional_argument()
ConfigFileArgparseCommand.get_help()
ConfigFileArgparseCommand.get_option_name_if_it_takes_an_argument()
ConfigFileArgparseCommand.get_position()
ConfigFileArgparseCommand.init_parser()
ConfigFileArgparseCommand.is_option_start()
ConfigFileArgparseCommand.run()
ConfigFileArgparseCommand.run_parsed()
ConfigFileCommand
ConfigFileCommand.add_help_to()
ConfigFileCommand.aliases
ConfigFileCommand.config_file
ConfigFileCommand.create_formatter()
ConfigFileCommand.delete_command_type()
ConfigFileCommand.get_command_types()
ConfigFileCommand.get_completions()
ConfigFileCommand.get_completions_for_file_name()
ConfigFileCommand.get_help()
ConfigFileCommand.get_help_attr_or_doc_str()
ConfigFileCommand.get_name()
ConfigFileCommand.get_names()
ConfigFileCommand.help
ConfigFileCommand.name
ConfigFileCommand.quote_path()
ConfigFileCommand.run()
ConfigFileCommand.save()
ConfigFileCommand.should_write_heading
ConfigFileCommand.ui_notifier
ConfigFileWriter
DEFAULT_COMMAND
FormattedWriter
HelpWriter
Include
Message
MultipleParseExceptions
NotificationLevel
ParseException
SaveKwargs
SectionLevel
Set
Set.KEY_VAL_SEP
Set.add_config_help()
Set.add_help_for_data_types()
Set.add_help_to()
Set.aliases
Set.config_file
Set.format_value()
Set.get_completions()
Set.get_completions_for_key()
Set.get_completions_for_ranger_style_arg()
Set.get_completions_for_value()
Set.get_completions_for_vim_style_arg()
Set.get_data_type_name_to_help_map()
Set.get_help_for_data_types()
Set.help
Set.help_for_types
Set.is_vim_style()
Set.iter_config_instances_to_be_saved()
Set.name
Set.parse_key_and_set_value()
Set.parse_value()
Set.run()
Set.save()
Set.save_config_instance()
Set.set_help_for_type()
Set.set_multiple()
Set.set_value()
Set.set_with_spaces()
Set.ui_notifier
Set.write_config_help()
TextIOWriter
UiNotifier
UnknownCommand
- confattr.subprocess_pipe module
- confattr.types module
Regex
SubprocessCommand
SubprocessCommand.has_python_callback()
SubprocessCommand.help
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: str) NoReturn
Raise a
ParseException
.
- class confattr.Config(key: str, default: T_co, *, help: str | dict[+T_co, str] | None = None, unit: str | None = None, parent: DictConfig[Any, T_co] | None = None, allowed_values: Sequence[T_co] | None = None)
Bases:
Generic
[T_co
]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:
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
parent¶ – Applies only if this is part of a
DictConfig
allowed_values¶ – The possible values this setting can have. Values read from a config file or an environment variable are checked against this. The
default
value is not checked.
T_co
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. A help which is written to the config file must be provided as a str in the class attributehelp
or by callingSet.set_help_for_type()
. If that class has a str attributetype_name
this is used instead of the class name inside of 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
ValueError – if
default
is an empty list 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
unit
is not given
- LIST_SEP = ','
- allowed_values: Sequence[T_co] | None
The values which are allowed for this setting. Trying to set this setting to a different value in the config file is considered an error. If you set this setting in the program the value is not checked.
- default_config_id = 'general'
- help: str | dict[+T_co, str] | None
A description of this setting or a description for each allowed value.
- 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(value: str) T_co
Parse a value to the data type of this setting.
- Parameters:
value¶ – The value to be parsed
- Raises:
ValueError – if
value
is invalid
- parse_value_part(t: type[T], value: str) T
Parse a value to the given data type.
- Parameters:
- Raises:
ValueError – if
value
is invalid
- set_value(config_id: ConfigId | None, value: T) None
This method is just to provide a common interface for
Config
andMultiConfig
. If you know that you are dealing with a normalConfig
you can setvalue
directly.
- value: T_co
The value of this setting.
- class confattr.ConfigFile(*, notification_level: ~confattr.config.Config[~confattr.configfile.NotificationLevel] = NotificationLevel.ERROR, appname: str, authorname: str | None = None, config_instances: dict[str, confattr.config.Config[typing.Any]] = {}, commands: ~collections.abc.Sequence[type[confattr.configfile.ConfigFileCommand]] | None = None, formatter_class: type[argparse.HelpFormatter] = <class 'confattr.utils.HelpFormatter'>, check_config_id: ~collections.abc.Callable[[~confattr.config.ConfigId], None] | None = None, enable_config_ids: bool | None = None)
Bases:
object
Read or write a config file.
- Parameters:
notification_level¶ – A
Config
which the users of your application can set to choose whether they want to see information which might be interesting for debugging a config file. AMessage
with a priority lower than this value is not passed to the callback registered withset_ui_callback()
.appname¶ – The name of the application, required for generating the path of the config file if you use
load()
orsave()
and as prefix of environment variable namesauthorname¶ – 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 commands (as subclasses of
ConfigFileCommand
orConfigFileArgparseCommand
) allowed in this config file, if this isNone
: use the return value ofConfigFileCommand.get_command_types()
formatter_class¶ – Is used to clean up doc strings and wrap lines in the help
check_config_id¶ – Is called every time a configuration group is opened (except for
Config.default_config_id
—that is always allowed). The callback should raise aParseException
if the config id is invalid.enable_config_ids¶ – see
enable_config_ids
. If None: Choose True or False automatically based oncheck_config_id
and the existence ofMultiConfig
/MultiDictConfig
- COMMENT = '#'
- COMMENT_PREFIXES = ('"', '#')
- ENTER_GROUP_PREFIX = '['
- ENTER_GROUP_SUFFIX = ']'
- config_directory: str | None = None
Override the config directory which is returned by
iter_user_site_config_paths()
. You should set either this attribute orconfig_path
in your tests withmonkeypatch.setattr
. If the environment variableAPPNAME_CONFIG_DIRECTORY
is set this attribute is set to it’s value in the constructor (whereAPPNAME
is the value which is passed asappname
to the constructor but in all upper case letters and hyphens and spaces replaced by underscores.)
- config_id: ConfigId | None
While loading a config file: The group that is currently being parsed, i.e. an identifier for which object(s) the values shall be set. This is set in
enter_group()
and reset inload_file()
.
- config_name = 'config'
The name of the config file used by
iter_config_paths()
. Can be changed with the environment variableAPPNAME_CONFIG_NAME
(whereAPPNAME
is the value which is passed asappname
to the constructor but in all upper case letters and hyphens and spaces replaced by underscores.).
- config_path: str | None = None
Override the config file which is returned by
iter_config_paths()
. You should set either this attribute orconfig_directory
in your tests withmonkeypatch.setattr
. If the environment variableAPPNAME_CONFIG_PATH
is set this attribute is set to it’s value in the constructor (whereAPPNAME
is the value which is passed asappname
to the constructor but in all upper case letters and hyphens and spaces replaced by underscores.)
- context_file_name: str | None = None
The name of the file which is currently loaded. If this equals
Message.ENVIRONMENT_VARIABLES
it is no file name but an indicator that environment variables are loaded. This isNone
ifparse_line()
is called directly (e.g. the input from a command line is parsed).
- context_line_number: int | None = None
The number of the line which is currently parsed. This is
None
ifcontext_file_name
is not a file name.
- create_formatter() HelpFormatterWrapper
- enable_config_ids: bool
If true:
[config-id]
syntax is allowed in config file, config ids are included in help, config id related options are available for include. If false: It is not possible to set different values for different objects (but default values forMultiConfig
instances can be set)
- enter_group(line: str) bool
Check if
line
starts a new group and setconfig_id
if it does. Callparse_error()
ifcheck_config_id
raises aParseException
.
- env_variables: list[str]
Contains the names of the environment variables for
config_path
,config_directory
andconfig_name
—in capital letters and prefixed withenvprefix
.
- envprefix: str
A prefix that is prepended to the name of environment variables in
get_env_name()
. It is set in the constructor by first setting it to an empty str and then passing the value ofappname
toget_env_name()
and appending an underscore.
- find_arg(line: str, ln_split: list[str], cursor_pos: int) ArgPos
This is an internal method used by
get_completions_command()
- 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
.
- get_command(ln_split: Sequence[str]) ConfigFileCommand
- get_completions(line: str, cursor_pos: int) tuple[str, list[str], str]
Provide an auto completion for commands that can be executed with
parse_line()
.- Parameters:
- Returns:
start of line, completions, end of line. completions is a list of possible completions for the word where the cursor is located. If completions is an empty list there are no completions available and the user input should not be changed. If completions is not empty it should be displayed by a user interface in a drop down menu. The start of line is everything on the line before the completions. The end of line is everything on the line after the completions. In the likely case that the cursor is at the end of the line the end of line is an empty str. start of line and end of line should be the beginning and end of
line
but they may contain minor changes in order to keep quoting feasible.
- get_completions_command(line: str, cursor_pos: int) tuple[str, list[str], str]
For a description of parameters and return type see
get_completions()
.get_completions()
has stripped any indentation fromline
and will prepend it to the first item of the return value.
- get_completions_command_name(line: str, cursor_pos: int, *, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- get_completions_enter_group(line: str, cursor_pos: int) tuple[str, list[str], str]
For a description of parameters and return type see
get_completions()
.get_completions()
has stripped any indentation fromline
and will prepend it to the first item of the return value.
- get_env_name(key: str) str
Convert the key of a setting to the name of the corresponding environment variable.
- get_help() str
A convenience wrapper around
write_help()
to return the help as a str instead of writing it to a file.This uses
HelpWriter
.
- get_help_config_id() str
- Returns:
A help how to use
MultiConfig
. The return value still needs to be cleaned withinspect.cleandoc()
.
- get_save_path() str
- Returns:
The first existing and writable file returned by
iter_config_paths()
or the first path if none of the files are existing and writable.
- 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.config_name
.If
config_path
has been set this method yields that path instead and no other paths.
- 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()
unlessconfig_directory
has been set. Ifconfig_directory
has been set it’s value is yielded and nothing else.
- load(*, env: bool = True) 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. :param _sphinx_paramlinks_confattr.ConfigFile.load.env: If true: call
load_env()
after loading the config file.
- load_env() None
Load settings from environment variables. The name of the environment variable belonging to a setting is generated with
get_env_name()
.Environment variables not matching a setting or having an invalid value are reported with
self.ui_notifier.show_error()
.- Raises:
ValueError – if two settings have the same environment variable name (see
get_env_name()
) or the environment variable name for a setting collides with one of the standard environment variables listed inenv_variables
- 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) 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 callsself.ui_notifier.show_error()
.- Parameters:
msg¶ – The error message
- parse_line(line: str) bool
- Parameters:
line¶ – The line to be parsed
- Returns:
True if line is valid, False if an error has occurred
parse_error()
is called if something goes wrong (i.e. if the return value is False), e.g. invalid key or invalid value.
- parse_split_line(ln_split: Sequence[str]) bool
Call the corresponding command in
command_dict
. If anyParseException
orMultipleParseExceptions
is raised catch it and callparse_error()
.- Returns:
False if a
ParseException
orMultipleParseExceptions
has been caught, True if no exception has been caught
- 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 file returned by
get_save_path()
. 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 a file-like object by creating a
ConfigFileWriter
object and callingsave_to_writer()
.- Parameters:
f¶ – The file to write to
For an explanation of the other parameters see
save()
.
- save_to_writer(writer: FormattedWriter, **kw: Unpack[SaveKwargs]) None
Save the current values of all settings.
Ensure that all keyword arguments are passed with
set_save_default_arguments()
. Iterate over allConfigFileCommand
objects inself.commands
and do for each of them:set
should_write_heading
toTrue
ifgetattr(cmd.save, 'implemented', True)
is true for two or more of those commands or toFalse
otherwisecall
save()
- set_save_default_arguments(kw: SaveKwargs) None
Ensure that all arguments are given in
kw
.
- set_ui_callback(callback: Callable[[Message], 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
- write_config_id(writer: FormattedWriter, config_id: ConfigId) None
Start a new group in the config file so that all following commands refer to the given
config_id
.
- write_help(writer: FormattedWriter) None
- 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
.- after_positional_argument_marker(cmd: Sequence[str], argument_pos: int) bool
- Returns:
true if this can only be a positional argument. False means it can be both, option or positional argument.
- get_completions(cmd: Sequence[str], argument_pos: int, cursor_pos: int, *, in_between: bool, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- Parameters:
cmd¶ – The line split into arguments (including the name of this command as cmd[0])
argument_pos¶ – The index of the argument which shall be completed. Please note that this can be one bigger than
cmd
is long if the line ends on a space and the cursor is behind that space. In that casein_between
is true.cursor_pos¶ – The index inside of the argument where the cursor is located. This is undefined and should be ignored if
in_between
is true. The input from the start of the argument to the cursor should be used to filter the completions. The input after the cursor can be ignored.in_between¶ – If true: The cursor is between two arguments, before the first argument or after the last argument.
argument_pos
refers to the next argument,argument_pos-1
to the previous argument.cursor_pos
is undefined.start_of_line¶ – The first return value. If
cmd[argument_pos]
has a pattern likekey=value
you can appendkey=
to this value and return only completions ofvalue
as second return value.end_of_line¶ – The third return value.
- Returns:
start of line, completions, end of line. completions is a list of possible completions for the word where the cursor is located. If completions is an empty list there are no completions available and the user input should not be changed. This should be displayed by a user interface in a drop down menu. The start of line is everything on the line before the completions. The end of line is everything on the line after the completions. In the likely case that the cursor is at the end of the line the end of line is an empty str. start of line and end of line should be the beginning and end of
line
but they may contain minor changes in order to keep quoting feasible.
- get_completions_for_action(action: Action | None, start: str, *, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- get_completions_for_option_argument(option_name: str, start: str, *, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- get_completions_for_option_name(start: str, *, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- get_completions_for_positional_argument(position: int, start: str, *, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- get_help() str
Creates a help text which can be presented to the user by calling
parser.format_help()
. The return value ofConfigFileCommand.write_help()
has been passed asdescription
to the constructor ofArgumentParser
, thereforehelp
/the doc string are included as well.
- get_position(cmd: Sequence[str], argument_pos: int) int
- Returns:
the position of a positional argument, not counting options and their arguments
- abstract init_parser(parser: ArgumentParser) None
- Parameters:
parser¶ – The parser to add arguments to. This is the same object like
parser
.
This is an abstract method which must be implemented by subclasses. Use
ArgumentParser.add_argument()
to add arguments toparser
.
- run(cmd: Sequence[str]) 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
.- add_help_to(formatter: HelpFormatterWrapper) None
Add the return value of
get_help_attr_or_doc_str()
toformatter
.
- config_file: ConfigFile
The
ConfigFile
that has been passed to the constructor. It determines for example thenotification_level
and the availablecommands
.
- create_formatter() HelpFormatterWrapper
- classmethod delete_command_type(cmd_type: type[confattr.configfile.ConfigFileCommand]) None
Delete
cmd_type
so that it is not returned anymore byget_command_types()
and that it’s name can be used by another command. Do nothing ifcmd_type
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()
- get_completions(cmd: Sequence[str], argument_pos: int, cursor_pos: int, *, in_between: bool, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- Parameters:
cmd¶ – The line split into arguments (including the name of this command as cmd[0])
argument_pos¶ – The index of the argument which shall be completed. Please note that this can be one bigger than
cmd
is long if the line ends on a space and the cursor is behind that space. In that casein_between
is true.cursor_pos¶ – The index inside of the argument where the cursor is located. This is undefined and should be ignored if
in_between
is true. The input from the start of the argument to the cursor should be used to filter the completions. The input after the cursor can be ignored.in_between¶ – If true: The cursor is between two arguments, before the first argument or after the last argument.
argument_pos
refers to the next argument,argument_pos-1
to the previous argument.cursor_pos
is undefined.start_of_line¶ – The first return value. If
cmd[argument_pos]
has a pattern likekey=value
you can appendkey=
to this value and return only completions ofvalue
as second return value.end_of_line¶ – The third return value.
- Returns:
start of line, completions, end of line. completions is a list of possible completions for the word where the cursor is located. If completions is an empty list there are no completions available and the user input should not be changed. This should be displayed by a user interface in a drop down menu. The start of line is everything on the line before the completions. The end of line is everything on the line after the completions. In the likely case that the cursor is at the end of the line the end of line is an empty str. start of line and end of line should be the beginning and end of
line
but they may contain minor changes in order to keep quoting feasible.
- get_completions_for_file_name(start: str, *, relative_to: str, exclude: str | None = None, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- Parameters:
start¶ – The start of the path to be completed
relative_to¶ – If
start
is a relative path it’s relative to this directoryexclude¶ – A regular expression. The default value
None
is interpreted differently depending on theplatform.platform()
. ForWindows
it’s$none
so that nothing is excluded. For others it’s^\.
so that hidden files and directories are excluded.
- Returns:
All files and directories that start with
start
and do not matchexclude
. Directories are appended withos.path.sep
.os.path.sep
is appended after quoting so that it can be easily stripped if undesired (e.g. if the user interface cycles through all possible completions instead of completing the longest common prefix).
- get_help() str
- Returns:
A help text which can be presented to the user.
This is generated by creating a formatter with
create_formatter()
, adding the help to it withadd_help_to()
and stripping trailing new line characters from the result ofHelpFormatterWrapper.format_help()
.Most likely you don’t want to override this method but
add_help_to()
instead.
- 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(cmd: Sequence[str]) 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(writer: FormattedWriter, **kw: Unpack[SaveKwargs]) None
Implement this method if you want calls to this command to be written by
ConfigFile.save()
.If you implement this method write a section heading with
writer.write_heading('Heading')
ifshould_write_heading
is true. If this command writes several sections then write a heading for every section regardless ofshould_write_heading
.Write as many calls to this command as necessary to the config file in order to create the current state with
writer.write_command('...')
. Write comments or help withwriter.write_lines('...')
.There is the
config_file
attribute (which was passed to the constructor) which you can use to:quote arguments with
ConfigFile.quote()
You probably don’t need the comment character
ConfigFile.COMMENT
becausewriter
automatically comments out everything except forFormattedWriter.write_command()
.The default implementation does nothing.
- should_write_heading: bool = False
If a config file contains only a single section it makes no sense to write a heading for it. This attribute is set by
ConfigFile.save_to_writer()
if there are several commands which implement thesave()
method. If you implementsave()
and this attribute is set thensave()
should write a section header. Ifsave()
writes several sections it should always write the headings regardless of this attribute.
- ui_notifier: UiNotifier
The
UiNotifier
ofconfig_file
- class confattr.ConfigFileWriter(f: TextIO | None, prefix: str)
Bases:
TextIOWriter
- write_heading(lvl: SectionLevel, heading: str) None
Write a heading.
This object should not add an indentation depending on the section because if the indentation is increased the line width should be decreased in order to keep the line wrapping consistent. Wrapping lines is handled by
confattr.utils.HelpFormatter
, i.e. before the text is passed to this object. It would be possible to useargparse.RawTextHelpFormatter
instead and handle line wrapping on a higher level but that would require to understand the help generated by argparse in order to know how far to indent a broken line. One of the trickiest parts would probably be to get the indentation of the usage right. Keep in mind that the term “usage” can differ depending on the language settings of the user.
- class confattr.DictConfig(key_prefix: str, default_values: dict[T_KEY, T], *, ignore_keys: Container[T_KEY] = {}, unit: str | None = None, help: str | None = None, allowed_values: Sequence[T] | None = None)
Bases:
Generic
[T_KEY
,T
]A container for several settings which belong together. It can be indexed like a normal
dict
but internally the items are stored inConfig
instances.In contrast to a
Config
instance 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 thekey
by which the setting is identified in the config filedefault_values¶ – The content of this container. A
Config
instance is created for each of these values (except if the key is contained inignore_keys
). Seeformat_key()
.ignore_keys¶ – All items which have one of these keys are not stored in a
Config
instance, i.e. cannot be set in the config file.unit¶ – The unit of all items
help¶ – A help for all items
allowed_values¶ – The values which the items can have
- 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
- class confattr.FormattedWriter
Bases:
ABC
- abstract write_heading(lvl: SectionLevel, heading: str) None
Write a heading.
This object should not add an indentation depending on the section because if the indentation is increased the line width should be decreased in order to keep the line wrapping consistent. Wrapping lines is handled by
confattr.utils.HelpFormatter
, i.e. before the text is passed to this object. It would be possible to useargparse.RawTextHelpFormatter
instead and handle line wrapping on a higher level but that would require to understand the help generated by argparse in order to know how far to indent a broken line. One of the trickiest parts would probably be to get the indentation of the usage right. Keep in mind that the term “usage” can differ depending on the language settings of the user.
- class confattr.HelpWriter(f: TextIO | None)
Bases:
TextIOWriter
- write_heading(lvl: SectionLevel, heading: str) None
Write a heading.
This object should not add an indentation depending on the section because if the indentation is increased the line width should be decreased in order to keep the line wrapping consistent. Wrapping lines is handled by
confattr.utils.HelpFormatter
, i.e. before the text is passed to this object. It would be possible to useargparse.RawTextHelpFormatter
instead and handle line wrapping on a higher level but that would require to understand the help generated by argparse in order to know how far to indent a broken line. One of the trickiest parts would probably be to get the indentation of the usage right. Keep in mind that the term “usage” can differ depending on the language settings of the user.
- class confattr.Include(config_file: ConfigFile)
Bases:
ConfigFileArgparseCommand
Load another config file.
This is useful if a config file is getting so big that you want to split it up or if you want to have different config files for different use cases which all include the same standard config file to avoid redundancy or if you want to bind several commands to one key which executes one command with ConfigFile.parse_line().
- get_completions_for_action(action: Action | None, start: str, *, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- help_config_id = '\n\tBy default the loaded config file starts with which ever config id is currently active.\n\tThis is useful if you want to use the same values for several config ids:\n\tWrite the set commands without a config id to a separate config file and include this file for every config id where these settings shall apply.\n\n\tAfter the include the config id is reset to the config id which was active at the beginning of the include\n\tbecause otherwise it might lead to confusion if the config id is changed in the included config file.\n\t'
- init_parser(parser: ArgumentParser) None
- Parameters:
parser¶ – The parser to add arguments to. This is the same object like
parser
.
This is an abstract method which must be implemented by subclasses. Use
ArgumentParser.add_argument()
to add arguments toparser
.
- class confattr.InstanceSpecificDictMultiConfig(mdc: MultiDictConfig[T_KEY, T], config_id: ConfigId)
Bases:
Generic
[T_KEY
,T
]An intermediate instance which is returned when accsessing a
MultiDictConfig
as an instance attribute. Can be indexed like a normaldict
.
- class confattr.Message(notification_level: NotificationLevel, message: str | BaseException, file_name: str | None = None, line_number: int | None = None, line: str = '')
Bases:
object
A message which should be displayed to the user. This is passed to the callback of the user interface which has been registered with
ConfigFile.set_ui_callback()
.If you want full control how to display messages to the user you can access the attributes directly. Otherwise you can simply convert this object to a str, e.g. with
str(msg)
. I recommend to use different colors for different values ofnotification_level
.- ENVIRONMENT_VARIABLES = 'environment variables'
The value of
file_name
while loading environment variables.
- file_name: str | None
The name of the config file which has caused this message. If this equals
ENVIRONMENT_VARIABLES
it is not a file but the message has occurred while reading the environment variables. This is None ifConfigFile.parse_line()
is called directly, e.g. when parsing the input from a command line.
- format_file_name_msg_line() str
- Returns:
The concatenation of the return values of
format_file_name()
andformat_msg_line()
- format_msg_line() str
The return value includes the attributes
message
,line_number
andline
if they are set.
- line: str
The line where the message occurred. This is an empty str if there is no line, e.g. when loading environment variables.
- line_number: int | None
The number of the line in the config file. This is None if
file_name
is not a file name.
- property lvl: NotificationLevel
An abbreviation for
notification_level
- message: str | BaseException
The string or exception which should be displayed to the user
- notification_level: NotificationLevel
The importance of this message. I recommend to display messages of different importance levels in different colors.
ConfigFile
does not output messages which are less important than thenotification_level
setting which has been passed to it’s constructor.
- classmethod reset() None
If you are using
format_file_name_msg_line()
or__str__()
you must call this method when the widget showing the error messages is cleared.
- class confattr.MultiConfig(key: str, default: T_co, *, unit: str | None = None, help: str | dict[+T_co, str] | None = None, parent: MultiDictConfig[Any, T_co] | None = None, allowed_values: Sequence[T_co] | None = None, check_config_id: Callable[[MultiConfig[T_co], ConfigId], None] | None = None)
Bases:
Config
[T_co
]A setting which can have different values for different objects.
This class implements the descriptor protocol to return one of the values in
values
depending on aconfig_id
attribute of the owning object if an instance of this class is accessed as an instance attribute. If there is no value for theconfig_id
invalues
value
is returned instead. If the owning instance does not have aconfig_id
attribute anAttributeError
is raised.In the config file a group can be opened with
[config-id]
. Then all followingset
commands 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
unit¶ – The unit of an int or float value
parent¶ – Applies only if this is part of a
MultiDictConfig
allowed_values¶ – The possible values this setting can have. Values read from a config file or an environment variable are checked against this. The
default
value is not checked.check_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 aParseException
if the config id is invalid.
- config_ids: list[confattr.config.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()
.
- format_value(config_id: ConfigId | None) str
Convert the value for the specified object(s) to a string.
- classmethod reset() None
Clear
config_ids
and clearvalues
for all instances inConfig.instances
- set_value(config_id: ConfigId | None, value: T) None
Check
config_id
by callingcheck_config_id()
and set the value for the object(s) identified byconfig_id
.If you know that
config_id
is valid you can also change the items ofvalues
directly. That is especially useful in test automation withpytest.MonkeyPatch.setitem()
.If you want to set the default value you can also set
value
directly.
- value: T_co
Stores the default value which is used if no value for the object is defined in
values
.
- values: dict[confattr.config.ConfigId, +T_co]
Stores the values for specific objects.
- class confattr.MultiDictConfig(key_prefix: str, default_values: dict[T_KEY, T], *, ignore_keys: Container[T_KEY] = {}, unit: str | None = None, help: str | None = None, allowed_values: Sequence[T] | 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
DictConfig
usingMultiConfig
instead of normalConfig
. However, in order to return different values depending on theconfig_id
of the owning instance, it implements the descriptor protocol to return anInstanceSpecificDictMultiConfig
if it is accessed as an instance attribute.- Parameters:
key_prefix¶ – A common prefix which is used by
format_key()
to generate thekey
by which the setting is identified in the config filedefault_values¶ – The content of this container. A
Config
instance is created for each of these values (except if the key is contained inignore_keys
). Seeformat_key()
.ignore_keys¶ – All items which have one of these keys are not stored in a
Config
instance, i.e. cannot be set in the config file.unit¶ – The unit of all items
help¶ – A help for all items
allowed_values¶ – The values which the items can have
check_config_id¶ – Is passed through to
MultiConfig
- Raises:
ValueError – if a key is not unique
- exception confattr.MultipleParseExceptions(exceptions: Sequence[ParseException])
Bases:
Exception
This is raised by
ConfigFileCommand
implementations in order to communicate that multiple errors have occured on the same line. Is caught inConfigFile
.
- class confattr.NotificationLevel(value)
Bases:
SortedEnum
An enumeration.
- ERROR = 'error'
- INFO = 'info'
- exception confattr.ParseException
Bases:
Exception
This is raised by
ConfigFileCommand
implementations and functions passed tocheck_config_id
in order to communicate an error in the config file like invalid syntax or an invalid value. Is caught inConfigFile
.
- class confattr.SectionLevel(value)
Bases:
SortedEnum
An enumeration.
- SECTION = 'section'
Is used to separate different commands in
ConfigFile.write_help()
andConfigFileCommand.save()
- SUB_SECTION = 'sub-section'
Is used for subsections in
ConfigFileCommand.save()
such as the “data types” section in the help of the set command
- class confattr.Set(config_file: ConfigFile)
Bases:
ConfigFileCommand
- usage: set key1=val1 [key2=val2 …] \
set key [=] val
Change the value of a setting.
In the first form set takes an arbitrary number of arguments, each argument sets one setting. This has the advantage that several settings can be changed at once. That is useful if you want to bind a set command to a key and process that command with ConfigFile.parse_line() if the key is pressed.
In the second form set takes two arguments, the key and the value. Optionally a single equals character may be added in between as third argument. This has the advantage that key and value are separated by one or more spaces which can improve the readability of a config file.
- KEY_VAL_SEP = '='
The separator which is used between a key and it’s value
- add_config_help(formatter: HelpFormatterWrapper, instance: Config[Any]) None
- add_help_for_data_types(formatter: HelpFormatterWrapper, config_instances: Iterable[Config[object]]) None
- add_help_to(formatter: HelpFormatterWrapper) None
Add the return value of
get_help_attr_or_doc_str()
toformatter
.
- format_value(instance: Config[Any], config_id: ConfigId | None) 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()
.
- get_completions(cmd: Sequence[str], argument_pos: int, cursor_pos: int, *, in_between: bool, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- Parameters:
cmd¶ – The line split into arguments (including the name of this command as cmd[0])
argument_pos¶ – The index of the argument which shall be completed. Please note that this can be one bigger than
cmd
is long if the line ends on a space and the cursor is behind that space. In that casein_between
is true.cursor_pos¶ – The index inside of the argument where the cursor is located. This is undefined and should be ignored if
in_between
is true. The input from the start of the argument to the cursor should be used to filter the completions. The input after the cursor can be ignored.in_between¶ – If true: The cursor is between two arguments, before the first argument or after the last argument.
argument_pos
refers to the next argument,argument_pos-1
to the previous argument.cursor_pos
is undefined.start_of_line¶ – The first return value. If
cmd[argument_pos]
has a pattern likekey=value
you can appendkey=
to this value and return only completions ofvalue
as second return value.end_of_line¶ – The third return value.
- Returns:
start of line, completions, end of line. completions is a list of possible completions for the word where the cursor is located. If completions is an empty list there are no completions available and the user input should not be changed. This should be displayed by a user interface in a drop down menu. The start of line is everything on the line before the completions. The end of line is everything on the line after the completions. In the likely case that the cursor is at the end of the line the end of line is an empty str. start of line and end of line should be the beginning and end of
line
but they may contain minor changes in order to keep quoting feasible.
- get_completions_for_key(start: str, *, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- get_completions_for_ranger_style_arg(cmd: Sequence[str], argument_pos: int, start: str, *, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- get_completions_for_value(key: str, start: str, *, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- get_completions_for_vim_style_arg(cmd: Sequence[str], argument_pos: int, start: str, *, start_of_line: str, end_of_line: str) tuple[str, list[str], str]
- get_data_type_name_to_help_map(config_instances: Iterable[Config[object]]) dict[str, str]
- Parameters:
config_instances¶ – All config values to be saved
- Returns:
A dictionary containing the type names as keys and the help as values
The returned dictionary contains the help for all data types except enumerations which occur in
config_instances
. The help is gathered from thehelp
attribute of the type or the str registered withset_help_for_type()
. The help is cleaned up withinspect.cleandoc()
.
- help_for_types = {<class 'str'>: 'A text. If it contains spaces it must be wrapped in single or double quotes.', <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 'float'>: 'A floating point number in python syntax, e.g. 23, 1.414, -1e3, 3.14_15_93.'}
Help for data types. This is used by
get_help_for_data_types()
. Change this withset_help_for_type()
.
- is_vim_style(cmd: Sequence[str]) bool
cmd
has one of two possible styles: - vim inspired: set takes an arbitrary number of arguments, each argument sets one setting. Is handled byset_multiple()
. - ranger inspired: set takes two arguments, the key and the value. Optionally a single equals character may be added in between as third argument. Is handled byset_with_spaces()
.- Returns:
true if cmd has a vim inspired style, false if cmd has a ranger inspired style
- 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_key_and_set_value(key: str, value: str) None
Find the corresponding
Config
instance forkey
and callset_value()
with the return value ofparse_value()
.- Raises:
ParseException – if key is invalid or if
parse_value()
orset_value()
raises aValueError
- parse_value(instance: Config[T2], value: str) T2
Parse a value to the data type of a given setting by calling
instance.parse_value(value)
- run(cmd: Sequence[str]) 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(writer: FormattedWriter, **kw: Unpack[SaveKwargs]) None
- Parameters:
writer¶ – 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 write help for 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_config_help()
) and write help for data types based onget_help_for_data_types()
.
- save_config_instance(writer: FormattedWriter, instance: Config[object], config_id: ConfigId | None, **kw: Unpack[SaveKwargs]) None
- Parameters:
writer¶ – 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_config_help()
Convert the
Config
instance into a value str withformat_value()
, wrap it in quotes if necessary withconfig_file.quote()
and write it towriter
.
- classmethod set_help_for_type(t: type[object], help_text: str) None
get_help_for_data_types()
is used bysave()
andget_help()
. Usually it uses thehelp
attribute of the class. But if the class does not have ahelp
attribute or if you want a different help text you can set the help with this method.- Parameters:
t¶ – The type for which you want to specify a help
help_text¶ – The help for
t
. It is cleaned up inget_data_type_name_to_help_map()
withinspect.cleandoc()
.
- 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_value(instance: Config[T2], value: T2) None
Assign
value
to :paramref`instance` by callingConfig.set_value()
withConfigFile.config_id
ofconfig_file
. Afterwards callUiNotifier.show_info()
.
- 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)
- write_config_help(writer: FormattedWriter, instance: Config[Any], *, group_dict_configs: bool = True) 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.