API Reference

exception configupdater.AlreadyAttachedError(block: str | Block = 'The block')[source]

Bases: Exception

{block} has been already attached to a container.

Try to remove it first using detach or create a copy using stdlib’s copy.deepcopy.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception configupdater.AssignMultilineValueError(block: str | Block = 'The block')[source]

Bases: Exception

Trying to assign a multi-line value to {block}. Use the set_values or append method to accomplish that.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class configupdater.Comment(container: Container | None = None)[source]

Bases: Block

Comment block

property add_after: BlockBuilder

Block builder inserting a new block after the current block

property add_before: BlockBuilder

Block builder inserting a new block before the current block

add_line(line: str) B

PRIVATE: this function is not part of the public API of Block. It is only used internally by other classes of the package during parsing.

Add a line to the current block

Parameters:

line (str) – one line to add

attach(container: Container) B

PRIVATE: Don’t use this as a user!

Rather use add_* or the bracket notation

property container: Container

Container holding the block

property container_idx: int

Index of the block within its container

detach() B

Remove and return this block from container

has_container() bool

Checks if this block has a container attached

property next_block: Block | None

Next block in the current container

property previous_block: Block | None

Previous block in the current container

property updated: bool

True if the option was changed/updated, otherwise False

class configupdater.ConfigUpdater(allow_no_value=False, *, delimiters: Tuple[str, ...] = ('=', ':'), comment_prefixes: Tuple[str, ...] = ('#', ';'), inline_comment_prefixes: Tuple[str, ...] | None = None, strict: bool = True, empty_lines_in_values: bool = True, space_around_delimiters: bool = True)[source]

Bases: Document

Tool to parse and modify existing cfg files.

ConfigUpdater follows the API of ConfigParser with some differences:

  • inline comments are treated as part of a key’s value,

  • only a single config file can be updated at a time,

  • the original case of sections and keys are kept,

  • control over the position of a new section/key.

Following features are deliberately not implemented:

  • interpolation of values,

  • propagation of parameters from the default section,

  • conversions of values,

  • passing key/value-pairs with default argument,

  • non-strict mode allowing duplicate sections and keys.

ConfigUpdater objects can be created by passing the same kind of arguments accepted by the Parser. After a ConfigUpdater object is created, you can load some content into it by calling any of the read* methods (read(), read_file() and read_string()).

Once the content is loaded you can use the ConfigUpdater object more or less in the same way you would use a nested dictionary. Please have a look into Document to understand the main differences.

When you are done changing the configuration file, you can call write() or update_file() methods.

add_section(section: str | Section)

Create a new section in the configuration.

Raise DuplicateSectionError if a section by the specified name already exists. Raise ValueError if name is DEFAULT.

Parameters:

section (str or Section) – name or Section type

clear() None.  Remove all items from D.
get(section, option, fallback=UniqueValues._UNSET)

Gets an option object for a given section or a fallback value.

Warning

Please notice this method works differently from what is expected of MutableMapping.get() (or dict.get()). Similarly to configparser.ConfigParser.get(), will take least 2 arguments, and the second argument does not correspond to a default value.

This happens because this function is not designed to return a Section of the ConfigUpdater document, but instead a nested Option.

See get_section(), if instead, you want to retrieve a Section.

Parameters:
  • section (str) – section name

  • option (str) – option name

  • fallback (T) – if the key is not found and fallback is provided, the fallback value will be returned. None is a valid fallback value.

Attention

When option is not present, the fallback value itself is returned. If you want instead to obtain a new Option object with a default value associated with it, you can try the following:

configupdater.get("section", "option", fallback=Option("name", value))

… which roughly corresponds to:

configupdater["section"].get("option", Option("name", value))
Raises:
Returns:

Option object holding key/value pair when it exists. Otherwise, the value passed via the fallback argument itself (type T).

get_section(name, default=None)

This method works similarly to dict.get(), and allows you to retrieve an entire section by its name, or provide a default value in case it cannot be found.

has_option(section: str, option: str) bool

Checks for the existence of a given option in a given section.

Parameters:
  • section (str) – name of section

  • option (str) – name of option

Returns:

whether the option exists in the given section

Return type:

bool

has_section(key) bool

Returns whether the given section exists.

Parameters:

key (str) – name of section

Returns:

wether the section exists

Return type:

bool

items(section=UniqueValues._UNSET)

Return a list of (name, value) tuples for options or sections.

If section is given, return a list of tuples with (name, value) for each option in the section. Otherwise, return a list of tuples with (section_name, section_type) for each section.

Parameters:

section (str) – optional section name, default UNSET

Returns:

list of Section or Option objects

Return type:

list

iter_blocks() Iterator[T]

Iterate over all blocks inside container.

iter_sections() Iterator[Section]

Iterate only over section blocks

keys() a set-like object providing a view on D's keys
options(section: str) list[str]

Returns list of configuration options for the named section.

Parameters:

section (str) – name of section

Returns:

list of option names

Return type:

list

optionxform(optionstr) str

Converts an option key for unification

By default it uses str.lower(), which means that ConfigUpdater will compare options in a case insensitive way.

This implementation mimics ConfigParser API, and can be configured as described in configparser.ConfigParser.optionxform().

Parameters:

optionstr (str) – key name

Returns:

unified option name

Return type:

str

pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

read(filename: str | bytes | PathLike, encoding: str | None = None) T[source]

Read and parse a filename.

Parameters:
  • filename (str) – path to file

  • encoding (str) – encoding of file, default None

read_file(f: Iterable[str], source: str | None = None) T[source]

Like read() but the argument must be a file-like object.

The f argument must be iterable, returning one line at a time. Optional second argument is the source specifying the name of the file being read. If not given, it is taken from f.name. If f has no name attribute, <???> is used.

Parameters:
  • f – file like object

  • source (str) – reference name for file object, default None

read_string(string: str, source='<string>') T[source]

Read configuration from a given string.

Parameters:
  • string (str) – string containing a configuration

  • source (str) – reference name for file object, default ‘<string>’

remove_option(section: str, option: str) bool

Remove an option.

Parameters:
  • section (str) – section name

  • option (str) – option name

Returns:

whether the option was actually removed

Return type:

bool

remove_section(name: str) bool

Remove a file section.

Parameters:

name – name of the section

Returns:

whether the section was actually removed

Return type:

bool

section_blocks() list[Section]

Returns all section blocks

Returns:

list of Section blocks

Return type:

list

sections() list[str]

Return a list of section names

Returns:

list of section names

Return type:

list

set(section: str, option: str, value: None | str | Iterable[str] = None) D

Set an option.

Parameters:
  • section – section name

  • option – option name

  • value – value, default None

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
to_dict() dict[str, dict[str, str | None]]

Transform to dictionary

Returns:

dictionary with same content

Return type:

dict

update([E, ]**F) None.  Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

update_file(validate: bool = True) T[source]

Update the read-in configuration file.

Parameters:

validate (Boolean) – validate format before writing

validate_format(**kwargs)[source]

Given the current state of the ConfigUpdater object (e.g. after modifications), validate its INI/CFG textual representation by parsing it with ConfigParser.

The ConfigParser object is instead with the same arguments as the original ConfigUpdater object, but the kwargs can be used to overwrite them.

See validate_format().

values() an object providing a view on D's values
write(fp: TextIO, validate: bool = True)[source]

Write an .cfg/.ini-format representation of the configuration state.

Parameters:
  • fp (file-like object) – open file handle

  • validate (Boolean) – validate format before writing

exception configupdater.DuplicateOptionError(section, option, source=None, lineno=None)[source]

Bases: Error

Raised by strict parsers when an option is repeated in an input source.

Current implementation raises this exception only when an option is found more than once in a single file, string or dictionary.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception configupdater.DuplicateSectionError(section, source=None, lineno=None)[source]

Bases: Error

Raised when a section is repeated in an input source.

Possible repetitions that raise this exception are: multiple creation using the API or in strict parsers when a section is found more than once in a single input file, string or dictionary.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception configupdater.InconsistentStateError(msg, fpname='<???>', lineno: int = -1, line: str = '???')[source]

Bases: Exception

Internal parser error, some of the parsing algorithm assumptions was violated, and the internal state machine ended up in an unpredicted state.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception configupdater.MissingSectionHeaderError(filename, lineno, line)[source]

Bases: ParsingError

Raised when a key-value pair is found before any section header.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception configupdater.NoConfigFileReadError[source]

Bases: Error

Raised when no configuration file was read but update requested.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception configupdater.NoOptionError(option, section)[source]

Bases: Error

A requested option was not found.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception configupdater.NoSectionError(section)[source]

Bases: Error

Raised when no section matches a requested option.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception configupdater.NoneValueDisallowed[source]

Bases: SyntaxWarning

Cannot represent <{option} = None>, it will be converted to <{option} = ‘’>. Please use allow_no_value=True with ConfigUpdater.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception configupdater.NotAttachedError(block: str | Block = 'The block')[source]

Bases: Exception

{block} is not attached to a container yet. Try to insert it first.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class configupdater.Option(key: str, value: str | None = None, container: Section | None = None, delimiter: str = '=', space_around_delimiters: bool = True, line: str | None = None)[source]

Bases: Block

Option block holding a key/value pair.

property add_after: BlockBuilder

Block builder inserting a new block after the current block

property add_before: BlockBuilder

Block builder inserting a new block before the current block

add_line(line: str)[source]

PRIVATE: this function is not part of the public API of Option. It is only used internally by other classes of the package during parsing.

add_value(value: str | None)[source]

PRIVATE: this function is not part of the public API of Option. It is only used internally by other classes of the package during parsing.

append(value: str, **kwargs) Option[source]

Append a value to a mult-line value

Parameters:
  • value (str) – value

  • kwargs – keyword arguments for set_values

as_list(separator='\n') list[str][source]

Returns the (multi-line/element) value as a list

Empty list if value is None, single-element list for a one-element value and an element for each line in a multi-element value.

Parameters:

separator (str) – separator for values, default: line separator

attach(container: Container) B

PRIVATE: Don’t use this as a user!

Rather use add_* or the bracket notation

property container: Container

Container holding the block

property container_idx: int

Index of the block within its container

detach() B

Remove and return this block from container

has_container() bool

Checks if this block has a container attached

property key: str

Key string associated with the option.

Please notice that the option key is normalized with optionxform().

When the option object is detached, this method will raise a NotAttachedError.

property next_block: Block | None

Next block in the current container

property previous_block: Block | None

Previous block in the current container

property raw_key: str

Equivalent to key, but before applying optionxform().

set_values(values: Iterable[str], separator='\n', indent: str | None = None, prepend_newline=True)[source]

Sets the value to a given list of options, e.g. multi-line values

Parameters:
  • values (iterable) – sequence of values

  • separator (str) – separator for values, default: line separator

  • indent (optional str) – indentation in case of line separator. If prepend_newline is True 4 whitespaces by default, otherwise determine automatically if None.

  • prepend_newline (bool) – start with a new line or not, resp.

property updated: bool

True if the option was changed/updated, otherwise False

property value: str | None

Value associated with the given option.

value_start_idx() int[source]

Index where the value of the option starts, good for indentation

class configupdater.Parser(allow_no_value=False, *, delimiters: ~typing.Tuple[str, ...] = ('=', ':'), comment_prefixes: ~typing.Tuple[str, ...] = ('#', ';'), inline_comment_prefixes: ~typing.Tuple[str, ...] | None = None, strict: bool = True, empty_lines_in_values: bool = True, space_around_delimiters: bool = True, optionxform: ~typing.Callable[[str], str] = <class 'str'>)[source]

Bases: object

Parser for updating configuration files.

ConfigUpdater’s parser follows ConfigParser with some differences:

  • inline comments are treated as part of a key’s value,

  • only a single config file can be updated at a time,

  • the original case of sections and keys are kept,

  • control over the position of a new section/key.

Following features are deliberately not implemented:

  • interpolation of values,

  • propagation of parameters from the default section,

  • conversions of values,

  • passing key/value-pairs with default argument,

  • non-strict mode allowing duplicate sections and keys.

read(filename: str | bytes | PathLike, encoding: str | None = None) Document[source]
read(filename: str | bytes | PathLike, encoding: str, into: D) D
read(filename: str | bytes | PathLike, *, into: D, encoding: str | None = None) D

Read and parse a filename.

Parameters:
  • filename (str) – path to file

  • encoding (Optional[str]) – encoding of file, default None

  • into (Optional[Document]) – object to be populated with the parsed config

read_file(f: Iterable[str], source: str | None) Document[source]
read_file(f: Iterable[str], source: str | None, into: D) D
read_file(f: Iterable[str], *, into: D, source: str | None = None) D

Like read() but the argument must be a file-like object.

The f argument must be iterable, returning one line at a time. Optional second argument is the source specifying the name of the file being read. If not given, it is taken from f.name. If f has no name attribute, <???> is used.

Parameters:
  • f – file like object

  • source (Optional[str]) – reference name for file object, default None

  • into (Optional[Document]) – object to be populated with the parsed config

read_string(string: str, source: str = '<string>') Document[source]
read_string(string: str, source: str, into: D) D
read_string(string: str, *, into: D, source: str = '<string>') D

Read configuration from a given string.

Parameters:
  • string (str) – string containing a configuration

  • source (str) – reference name for file object, default ‘<string>’

  • into (Optional[Document]) – object to be populated with the parsed config

exception configupdater.ParsingError(source=None, filename=None)[source]

Bases: Error

Raised when a configuration file does not follow legal syntax.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class configupdater.Section(name: str, container: Document | None = None, raw_comment: str = '')[source]

Bases: Block, Container[Union[Option, Comment, Space]], MutableMapping[str, Option]

Section block holding options

property add_after: BlockBuilder

Block builder inserting a new block after the current block

property add_before: BlockBuilder

Block builder inserting a new block before the current block

add_comment(line: str) S[source]

Add a Comment object to the section

Used during initial parsing mainly

Parameters:

line (str) – one line in the comment

add_line(line: str) B

PRIVATE: this function is not part of the public API of Block. It is only used internally by other classes of the package during parsing.

Add a line to the current block

Parameters:

line (str) – one line to add

add_option(entry: Option) S[source]

Add an Option object to the section

Used during initial parsing mainly

Parameters:

entry (Option) – key value pair as Option object

add_space(line: str) S[source]

Add a Space object to the section

Used during initial parsing mainly

Parameters:

line (str) – one line that defines the space, maybe whitespaces

attach(container: Container) B

PRIVATE: Don’t use this as a user!

Rather use add_* or the bracket notation

clear() None.  Remove all items from D.[source]
property container: Container

Container holding the block

property container_idx: int

Index of the block within its container

create_option(key: str, value: str | None = None) Option[source]

Creates an option with kwargs that respect syntax options given to the parent ConfigUpdater object (e.g. space_around_delimiters).

Warning

This is a low level API, not intended for public use. Prefer set() or __setitem__().

detach() B

Remove and return this block from container

get(key: str) Option | None[source]
get(key: str, default: T) Option | T

This method works similarly to dict.get(), and allows you to retrieve an option object by its key.

has_container() bool

Checks if this block has a container attached

has_option(key) bool

Returns whether the given option exists.

Parameters:

option (str) – name of option

Returns:

whether the section exists

Return type:

bool

insert_at(idx: int) BlockBuilder[source]

Returns a builder inserting a new block at the given index

Parameters:

idx (int) – index where to insert

items() list[Tuple[str, Option]][source]

Return a list of (name, option) tuples for each option in this section.

Returns:

list of (name, Option) tuples

Return type:

list

iter_blocks() Iterator[T]

Iterate over all blocks inside container.

iter_options() Iterator[Option][source]

Iterate only over option blocks

keys() a set-like object providing a view on D's keys
property name: str

Name of the section

property next_block: Block | None

Next block in the current container

option_blocks() list[Option][source]

Returns option blocks

Returns:

list of Option blocks

Return type:

list

options() list[str][source]

Returns option names

Returns:

list of option names as strings

Return type:

list

pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

property previous_block: Block | None

Previous block in the current container

property raw_comment

Raw comment (includes comment mark) inline with the section header

set(option: str, value: None | str | Iterable[str] = None) S[source]

Set an option for chaining.

Parameters:
  • option – option name

  • value – value, default None

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
to_dict() dict[str, str | None][source]

Transform to dictionary

Returns:

dictionary with same content

Return type:

dict

update([E, ]**F) None.  Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

property updated: bool

True if the option was changed/updated, otherwise False

values() an object providing a view on D's values
class configupdater.Space(container: Container | None = None)[source]

Bases: Block

Vertical space block of new lines

property add_after: BlockBuilder

Block builder inserting a new block after the current block

property add_before: BlockBuilder

Block builder inserting a new block before the current block

add_line(line: str) B

PRIVATE: this function is not part of the public API of Block. It is only used internally by other classes of the package during parsing.

Add a line to the current block

Parameters:

line (str) – one line to add

attach(container: Container) B

PRIVATE: Don’t use this as a user!

Rather use add_* or the bracket notation

property container: Container

Container holding the block

property container_idx: int

Index of the block within its container

detach() B

Remove and return this block from container

has_container() bool

Checks if this block has a container attached

property next_block: Block | None

Next block in the current container

property previous_block: Block | None

Previous block in the current container

property updated: bool

True if the option was changed/updated, otherwise False