confattr.configfile module — confattr v0.4.0 documentation

# confattr.configfile module

This module defines the ConfigFile class which can be used to load and save config files.

class confattr.configfile.ConfigFile(*, notification_level: Union[Config[NotificationLevel], NotificationLevel] = NotificationLevel.ERROR, appname: str, authorname: Optional[str] = None, config_instances: dict[str, confattr.config.Config[Any]] = {})

  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()` 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.

    Use `set_ui_callback()` to get error messages which appeared while loading the config file. You can call `set_ui_callback()` after this method without loosing any messages.

    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.

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

    Raises:

      FileNotFoundError – if the directory does not exist

    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_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

  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

exception confattr.configfile.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.configfile.NotificationLevel(value)

  Bases: `SortedEnum`

  An enumeration.

  ERROR = 'error'
  INFO = 'info'

exception confattr.configfile.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.

class confattr.configfile.SortedEnum(value)

  Bases: `Enum`

  An enumeration.

class confattr.configfile.UiNotifier(notification_level: Union[Config[NotificationLevel], NotificationLevel] = NotificationLevel.ERROR)

  Bases: `object`

  Most likely you will want to load the config file before creating the UI. But if there are errors in the config file the user will want to know about them. This class takes the messages from `ConfigFile` and stores them until the UI is ready. When you call `set_ui_callback()` the stored messages will be forwarded and cleared.

  This object can also filter the messages. `ConfigFile` calls `show_info()` every time a setting is changed. If you load an entire config file this can be many messages and the user probably does not want to see them all. Therefore this object drops all messages of `NotificationLevel.INFO` by default. Pass `notification_level` to the constructor if you don’t want that.

  property notification_level: NotificationLevel
  set_ui_callback(callback: Callable[[NotificationLevel, str | BaseException], None]) → None
  show(notification_level: NotificationLevel, msg: str | BaseException, *, ignore_filter: bool = False) → None
  show_error(msg: str | BaseException, *, ignore_filter: bool = False) → None
  show_info(msg: str, *, ignore_filter: bool = False) → None

confattr.configfile.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`