configupdater package

Submodules

configupdater.block module

Together with container this module forms the basis of the class hierarchy in ConfigUpdater.

The Block is the parent class of everything that can be nested inside a configuration file, e.g. comments, sections, options and even sequences of white space.

exception configupdater.block.AlreadyAttachedError(block: Union[str, configupdater.block.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.

args
with_traceback()

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

class configupdater.block.Block(container: Optional[Container] = None)[source]

Bases: abc.ABC

Abstract Block type holding lines

Block objects hold original lines from the configuration file and hold a reference to a container wherein the object resides.

The type variable T is a reference for the type of the sibling blocks inside the container.

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) configupdater.block.B[source]

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) configupdater.block.B[source]

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() configupdater.block.B[source]

Remove and return this block from container

has_container() bool[source]

Checks if this block has a container attached

property lines: List[str]
property next_block: Optional[configupdater.block.Block]

Next block in the current container

property previous_block: Optional[configupdater.block.Block]

Previous block in the current container

property updated: bool

True if the option was changed/updated, otherwise False

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

Bases: configupdater.block.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) configupdater.block.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) configupdater.block.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() configupdater.block.B

Remove and return this block from container

has_container() bool

Checks if this block has a container attached

property lines: List[str]
property next_block: Optional[configupdater.block.Block]

Next block in the current container

property previous_block: Optional[configupdater.block.Block]

Previous block in the current container

property updated: bool

True if the option was changed/updated, otherwise False

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

Bases: Exception

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

args
with_traceback()

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

class configupdater.block.Space(container: Optional[Container] = None)[source]

Bases: configupdater.block.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) configupdater.block.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) configupdater.block.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() configupdater.block.B

Remove and return this block from container

has_container() bool

Checks if this block has a container attached

property lines: List[str]
property next_block: Optional[configupdater.block.Block]

Next block in the current container

property previous_block: Optional[configupdater.block.Block]

Previous block in the current container

property updated: bool

True if the option was changed/updated, otherwise False

configupdater.builder module

Core of the fluent API used by ConfigUpdater to make editing configuration files easier.

class configupdater.builder.BlockBuilder(container: Container, idx: int)[source]

Bases: object

Builder that injects blocks at a given index position.

comment(text: str, comment_prefix='#') configupdater.builder.T[source]

Creates a comment block

Parameters
  • text (str) – content of comment without #

  • comment_prefix (str) – character indicating start of comment

Returns

self for chaining

option(key, value: Optional[str] = None, **kwargs) configupdater.builder.T[source]

Creates a new option inside a section

Parameters
  • key (str) – key of the option

  • value (str or None) – value of the option

  • **kwargs – are passed to the constructor of Option

Returns

self for chaining

section(section: Union[str, Section]) configupdater.builder.T[source]

Creates a section block

Parameters

section (str or Section) – name of section or object

Returns

self for chaining

space(newlines: int = 1) configupdater.builder.T[source]

Creates a vertical space of newlines

Parameters

newlines (int) – number of empty lines

Returns

self for chaining

configupdater.configupdater module

As the main entry point of the ConfigUpdater library, this module is responsible for combining the data layer provided by the configupdater.document module and the parsing capabilities of configupdater.parser.

To complete the API, this module adds file handling functions, so that you can read a configuration file from the disk, change it to your liking and save the updated content.

exception configupdater.configupdater.AlreadyAttachedError(block: Union[str, configupdater.block.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.

args
with_traceback()

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

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

Bases: configupdater.block.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) configupdater.block.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) configupdater.block.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() configupdater.block.B

Remove and return this block from container

has_container() bool

Checks if this block has a container attached

property lines: List[str]
property next_block: Optional[configupdater.block.Block]

Next block in the current container

property previous_block: Optional[configupdater.block.Block]

Previous block in the current container

property updated: bool

True if the option was changed/updated, otherwise False

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

Bases: configupdater.document.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: Union[str, configupdater.section.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

append(block: configupdater.container.T) configupdater.container.C
clear() None.  Remove all items from D.
property first_block: Optional[configupdater.container.T]
get(section, option, fallback=UniqueValues._UNSET)

Gets an option value for a given section.

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 – if the key is not found and fallback is provided, it will be returned. None is a valid fallback value.

Raises
Returns

Option object holding key/value pair

Return type

Option

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[configupdater.container.T]

Iterate over all blocks inside container.

iter_sections() Iterator[configupdater.section.Section]

Iterate only over section blocks

keys() a set-like object providing a view on D's keys
property last_block: Optional[configupdater.container.T]
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: Union[str, bytes, os.PathLike], encoding: Optional[str] = None) configupdater.configupdater.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: Optional[str] = None) configupdater.configupdater.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>') configupdater.configupdater.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[configupdater.section.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: Union[None, str, Iterable[str]] = None) configupdater.document.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
property structure: List[configupdater.container.T]
property syntax_options: Mapping
to_dict() Dict[str, Dict[str, Optional[str]]]

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) configupdater.configupdater.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.configupdater.NoConfigFileReadError[source]

Bases: configparser.Error

Raised when no configuration file was read but update requested.

args
with_traceback()

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

exception configupdater.configupdater.NoneValueDisallowed[source]

Bases: SyntaxWarning

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

args
classmethod warn(option)[source]
with_traceback()

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

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

Bases: Exception

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

args
with_traceback()

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

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

Bases: configupdater.block.Block

Option block holding a key/value pair.

key

name of the key

Type

str

value

stored value

Type

str

updated

indicates name change or a new section

Type

bool

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: Optional[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.

attach(container: Container) configupdater.block.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() configupdater.block.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 lines: List[str]
property next_block: Optional[configupdater.block.Block]

Next block in the current container

property previous_block: Optional[configupdater.block.Block]

Previous block in the current container

property raw_key: str

Equivalent to key, but before applying optionxform().

property section: Section
set_values(values: Iterable[str], separator='\n', indent='    ')[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 (str) – indentation depth in case of line separator

property updated: bool

True if the option was changed/updated, otherwise False

property value: Optional[str]
class configupdater.configupdater.Parser(allow_no_value=False, *, delimiters: Tuple[str, ...] = ('=', ':'), comment_prefixes: Tuple[str, ...] = ('#', ';'), inline_comment_prefixes: Optional[Tuple[str, ...]] = None, strict: bool = True, empty_lines_in_values: bool = True, space_around_delimiters: bool = True, optionxform: 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.

NONSPACECRE = re.compile('\\S')
OPTCRE = re.compile('\n        (?P<option>.*?)                    # very permissive!\n        \\s*(?P<vi>=|:)\\s*              # any number of space/tab,\n                                           # followed by any of t, re.VERBOSE)
OPTCRE_NV = re.compile('\n        (?P<option>.*?)                    # very permissive!\n        \\s*(?:                             # any number of space/tab,\n        (?P<vi>=|:)\\s*                 # optionally followed , re.VERBOSE)
SECTCRE = re.compile('\n        \\[                                 # [\n        (?P<header>[^]]+)                  # very permissive!\n        \\]                                 # ]\n        (?P<raw_comment>.*)         , re.VERBOSE)
optionxform(string: str) str[source]
read(filename: Union[str, bytes, os.PathLike], encoding: Optional[str] = None) configupdater.document.Document[source]
read(filename: Union[str, bytes, os.PathLike], encoding: str, into: configupdater.parser.D) configupdater.parser.D
read(filename: Union[str, bytes, os.PathLike], *, into: configupdater.parser.D, encoding: Optional[str] = 'None') configupdater.parser.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: Optional[str]) configupdater.document.Document[source]
read_file(f: Iterable[str], source: Optional[str], into: configupdater.parser.D) configupdater.parser.D
read_file(f: Iterable[str], *, into: configupdater.parser.D, source: Optional[str] = 'None') configupdater.parser.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>') configupdater.document.Document[source]
read_string(string: str, source: str, into: configupdater.parser.D) configupdater.parser.D
read_string(string: str, *, into: configupdater.parser.D, source: str = "'<string>'") configupdater.parser.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

property syntax_options: Mapping
class configupdater.configupdater.Section(name: str, container: Optional[Document] = None)[source]

Bases: configupdater.block.Block, configupdater.container.Container[Union[Option, Comment, Space]], MutableMapping[str, Option]

Section block holding options

name

name of the section

Type

str

updated

indicates name change or a new section

Type

bool

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) configupdater.section.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) configupdater.block.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: configupdater.option.Option) configupdater.section.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) configupdater.section.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

append(block: configupdater.container.T) configupdater.container.C
attach(container: Container) configupdater.block.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: Optional[str] = None) configupdater.option.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() configupdater.block.B

Remove and return this block from container

property document: Document
property first_block: Optional[configupdater.container.T]
get(key: str) Optional[Option][source]
get(key: str, default: configupdater.section.T) Union[Option, configupdater.section.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) configupdater.builder.BlockBuilder[source]

Returns a builder inserting a new block at the given index

Parameters

idx (int) – index where to insert

items() List[Tuple[str, configupdater.option.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[configupdater.container.T]

Iterate over all blocks inside container.

iter_options() Iterator[configupdater.option.Option][source]

Iterate only over option blocks

keys() a set-like object providing a view on D's keys
property last_block: Optional[configupdater.container.T]
property lines: List[str]
property name: str
property next_block: Optional[configupdater.block.Block]

Next block in the current container

option_blocks() List[configupdater.option.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: Optional[configupdater.block.Block]

Previous block in the current container

property raw_comment

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

set(option: str, value: Union[None, str, Iterable[str]] = None) configupdater.section.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
property structure: List[configupdater.container.T]
to_dict() Dict[str, Optional[str]][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.configupdater.Space(container: Optional[Container] = None)[source]

Bases: configupdater.block.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) configupdater.block.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) configupdater.block.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() configupdater.block.B

Remove and return this block from container

has_container() bool

Checks if this block has a container attached

property lines: List[str]
property next_block: Optional[configupdater.block.Block]

Next block in the current container

property previous_block: Optional[configupdater.block.Block]

Previous block in the current container

property updated: bool

True if the option was changed/updated, otherwise False

configupdater.container module

Together with block this module forms the basis of the class hierarchy in ConfigUpdater.

The Container is the parent class of everything that can contain configuration blocks, e.g. a section or the entire file itself.

class configupdater.container.Container[source]

Bases: abc.ABC, Generic[configupdater.container.T]

Abstract Mixin Class describing a container that holds blocks of type T

append(block: configupdater.container.T) configupdater.container.C[source]
property first_block: Optional[configupdater.container.T]
iter_blocks() Iterator[configupdater.container.T][source]

Iterate over all blocks inside container.

property last_block: Optional[configupdater.container.T]
property structure: List[configupdater.container.T]

configupdater.document module

This module focus in the top level data layer API of ConfigUpdater, i.e. how to access and modify the sections of the configurations.

Differently from configparser, the different aspects of the ConfigUpdater API are split between several modules.

class configupdater.document.Document[source]

Bases: configupdater.container.Container[Union[Section, Comment, Space]], MutableMapping[str, configupdater.section.Section]

Access to the data manipulation API from ConfigUpdater.

A Document object tries to implement a familiar dict-like interface, via MutableMapping. However, it also tries to be as compatible as possible with the stdlib’s ConfigParser. This means that there are a few methods that will work differently from what users familiar with dict-like interfaces would expect. The most notable example is get().

A important difference between ConfigUpdater’s Document model and ConfigParser is the behaviour of the Section objects. If we represent the type of a dict-like (or MutableMapping) object by M[K, V], where K is the type of its keys and V is the type of the associated values, ConfigUpdater’s sections would be equivalent to M[str, Option], while ConfigParser’s would be M[str, str].

This means that when you try to access a key inside a section in ConfigUpdater, you are going to receive a Option object, not its value. To access the value of the option you need to call Option.value.

add_section(section: Union[str, configupdater.section.Section])[source]

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

append(block: configupdater.container.T) configupdater.container.C
clear() None.  Remove all items from D.[source]
property first_block: Optional[configupdater.container.T]
get(section: str, option: str) configupdater.option.Option[source]
get(section: str, option: str, fallback: configupdater.document.T) Union[configupdater.option.Option, configupdater.document.T]

Gets an option value for a given section.

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 – if the key is not found and fallback is provided, it will be returned. None is a valid fallback value.

Raises
Returns

Option object holding key/value pair

Return type

Option

get_section(name: str) Optional[configupdater.section.Section][source]
get_section(name: str, default: configupdater.document.T) Union[configupdater.section.Section, configupdater.document.T]

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[source]

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() List[Tuple[str, configupdater.section.Section]][source]
items(section: str) List[Tuple[str, configupdater.option.Option]]

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[configupdater.container.T]

Iterate over all blocks inside container.

iter_sections() Iterator[configupdater.section.Section][source]

Iterate only over section blocks

keys() a set-like object providing a view on D's keys
property last_block: Optional[configupdater.container.T]
options(section: str) List[str][source]

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[source]

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.

remove_option(section: str, option: str) bool[source]

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[source]

Remove a file section.

Parameters

name – name of the section

Returns

whether the section was actually removed

Return type

bool

section_blocks() List[configupdater.section.Section][source]

Returns all section blocks

Returns

list of Section blocks

Return type

list

sections() List[str][source]

Return a list of section names

Returns

list of section names

Return type

list

set(section: str, option: str, value: Union[None, str, Iterable[str]] = None) configupdater.document.D[source]

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
property structure: List[configupdater.container.T]
to_dict() Dict[str, Dict[str, Optional[str]]][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

validate_format(**kwargs)[source]

Call ConfigParser to validate config

Parameters

kwargs – are passed to configparser.ConfigParser

Raises

configparser.ParsingError – if syntax errors are found

Returns

True when no error is found

values() an object providing a view on D's values

configupdater.option module

Options are the ultimate mean of configuration inside a configuration value.

They are always associated with a key (or the name of the configuration parameter) and a value.

Options can also have multi-line values that are usually interpreted as a list of values.

When editing configuration files with ConfigUpdater, a handy way of setting a multi-line (or comma separated value) for an specific option is to use the set_values() method.

exception configupdater.option.NoneValueDisallowed[source]

Bases: SyntaxWarning

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

args
classmethod warn(option)[source]
with_traceback()

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

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

Bases: configupdater.block.Block

Option block holding a key/value pair.

key

name of the key

Type

str

value

stored value

Type

str

updated

indicates name change or a new section

Type

bool

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: Optional[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.

attach(container: Container) configupdater.block.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() configupdater.block.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 lines: List[str]
property next_block: Optional[configupdater.block.Block]

Next block in the current container

property previous_block: Optional[configupdater.block.Block]

Previous block in the current container

property raw_key: str

Equivalent to key, but before applying optionxform().

property section: Section
set_values(values: Iterable[str], separator='\n', indent='    ')[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 (str) – indentation depth in case of line separator

property updated: bool

True if the option was changed/updated, otherwise False

property value: Optional[str]

configupdater.parser module

Parser for configuration files (normally *.cfg/*.ini)

A configuration file consists of sections, lead by a “[section]” header, and followed by “name: value” entries, with continuations and such in the style of RFC 822.

The basic idea of ConfigUpdater is that a configuration file consists of three kinds of building blocks: sections, comments and spaces for separation. A section itself consists of three kinds of blocks: options, comments and spaces. This gives us the corresponding data structures to describe a configuration file.

A general block object contains the lines which were parsed and make up the block. If a block object was not changed then during writing the same lines that were parsed will be used to express the block. In case a block, e.g. an option, was changed, it is marked as updated and its values will be transformed into a corresponding string during an update of a configuration file.

Note

ConfigUpdater is based on Python’s ConfigParser source code, specially regarding the parser module. The main parsing rules and algorithm are preserved, however ConfigUpdater implements its own modified version of the abstract syntax tree to support retaining comments and whitespace in an attempt to provide format-preserving document manipulation. The copyright and license of the original ConfigParser code is included as an attachment to ConfigUpdater’s own license, at the root of the source code repository; see the file LICENSE for details.

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

Bases: configparser.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.

args
with_traceback()

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

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

Bases: configparser.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.

args
with_traceback()

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

exception configupdater.parser.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.

args
with_traceback()

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

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

Bases: configparser.ParsingError

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

append(lineno, line)
args
property filename

Deprecated, use `source’.

with_traceback()

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

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

Bases: configparser.Error

A requested option was not found.

args
with_traceback()

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

exception configupdater.parser.NoSectionError(section)[source]

Bases: configparser.Error

Raised when no section matches a requested option.

args
with_traceback()

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

class configupdater.parser.Parser(allow_no_value=False, *, delimiters: Tuple[str, ...] = ('=', ':'), comment_prefixes: Tuple[str, ...] = ('#', ';'), inline_comment_prefixes: Optional[Tuple[str, ...]] = None, strict: bool = True, empty_lines_in_values: bool = True, space_around_delimiters: bool = True, optionxform: 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.

NONSPACECRE = re.compile('\\S')
OPTCRE = re.compile('\n        (?P<option>.*?)                    # very permissive!\n        \\s*(?P<vi>=|:)\\s*              # any number of space/tab,\n                                           # followed by any of t, re.VERBOSE)
OPTCRE_NV = re.compile('\n        (?P<option>.*?)                    # very permissive!\n        \\s*(?:                             # any number of space/tab,\n        (?P<vi>=|:)\\s*                 # optionally followed , re.VERBOSE)
SECTCRE = re.compile('\n        \\[                                 # [\n        (?P<header>[^]]+)                  # very permissive!\n        \\]                                 # ]\n        (?P<raw_comment>.*)         , re.VERBOSE)
optionxform(string: str) str[source]
read(filename: Union[str, bytes, os.PathLike], encoding: Optional[str] = None) configupdater.document.Document[source]
read(filename: Union[str, bytes, os.PathLike], encoding: str, into: configupdater.parser.D) configupdater.parser.D
read(filename: Union[str, bytes, os.PathLike], *, into: configupdater.parser.D, encoding: Optional[str] = 'None') configupdater.parser.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: Optional[str]) configupdater.document.Document[source]
read_file(f: Iterable[str], source: Optional[str], into: configupdater.parser.D) configupdater.parser.D
read_file(f: Iterable[str], *, into: configupdater.parser.D, source: Optional[str] = 'None') configupdater.parser.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>') configupdater.document.Document[source]
read_string(string: str, source: str, into: configupdater.parser.D) configupdater.parser.D
read_string(string: str, *, into: configupdater.parser.D, source: str = "'<string>'") configupdater.parser.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

property syntax_options: Mapping
exception configupdater.parser.ParsingError(source=None, filename=None)[source]

Bases: configparser.Error

Raised when a configuration file does not follow legal syntax.

append(lineno, line)[source]
args
property filename

Deprecated, use `source’.

with_traceback()

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

configupdater.section module

Sections are intermediate containers in ConfigUpdater’s data model for configuration files.

They are at the same time containers that hold options and blocks nested inside the top level configuration Document.

Note

Please remember that Section.get() method is implemented to mirror the ConfigParser API and do not correspond to the more usual get() method of dict-like objects.

class configupdater.section.Section(name: str, container: Optional[Document] = None)[source]

Bases: configupdater.block.Block, configupdater.container.Container[Union[Option, Comment, Space]], MutableMapping[str, Option]

Section block holding options

name

name of the section

Type

str

updated

indicates name change or a new section

Type

bool

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) configupdater.section.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) configupdater.block.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: configupdater.option.Option) configupdater.section.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) configupdater.section.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

append(block: configupdater.container.T) configupdater.container.C
attach(container: Container) configupdater.block.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: Optional[str] = None) configupdater.option.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() configupdater.block.B

Remove and return this block from container

property document: Document
property first_block: Optional[configupdater.container.T]
get(key: str) Optional[Option][source]
get(key: str, default: configupdater.section.T) Union[Option, configupdater.section.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) configupdater.builder.BlockBuilder[source]

Returns a builder inserting a new block at the given index

Parameters

idx (int) – index where to insert

items() List[Tuple[str, configupdater.option.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[configupdater.container.T]

Iterate over all blocks inside container.

iter_options() Iterator[configupdater.option.Option][source]

Iterate only over option blocks

keys() a set-like object providing a view on D's keys
property last_block: Optional[configupdater.container.T]
property lines: List[str]
property name: str
property next_block: Optional[configupdater.block.Block]

Next block in the current container

option_blocks() List[configupdater.option.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: Optional[configupdater.block.Block]

Previous block in the current container

property raw_comment

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

set(option: str, value: Union[None, str, Iterable[str]] = None) configupdater.section.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
property structure: List[configupdater.container.T]
to_dict() Dict[str, Optional[str]][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

Module contents