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’scopy.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
orappend
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
- detach() B ¶
Remove and return this block from container
- 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 theread*
methods (read()
,read_file()
andread_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()
orupdate_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()
(ordict.get()
). Similarly toconfigparser.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 theConfigUpdater
document, but instead a nestedOption
.See
get_section()
, if instead, you want to retrieve aSection
.- Parameters:
Attention
When
option
is not present, thefallback
value itself is returned. If you want instead to obtain a newOption
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:
NoSectionError – if
section
cannot be foundNoOptionError – if the option cannot be found and no
fallback
was given
- Returns:
Option
object holding key/value pair when it exists. Otherwise, the value passed via thefallback
argument itself (typeT
).
- 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 adefault
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.
- 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.
- keys() a set-like object providing a view on D's keys ¶
- 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()
.
- 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.
- 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 thesource
specifying the name of the file being read. If not given, it is taken from f.name. Iff
has noname
attribute,<???>
is used.- Parameters:
f – file like object
source (str) – reference name for file object, default None
- remove_section(name: str) bool ¶
Remove a file section.
- Parameters:
name – name of the section
- Returns:
whether the section was actually removed
- Return type:
- 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:
- 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 withConfigParser
.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 ¶
- 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
withConfigUpdater
.- 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
- detach() B ¶
Remove and return this block from container
- 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 aNotAttachedError
.
- 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.
- 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.
- 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 thesource
specifying the name of the file being read. If not given, it is taken from f.name. Iff
has noname
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
- 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
- property container: Container¶
Container holding the block
- 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.
- 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.
- keys() a set-like object providing a view on D's keys ¶
- options() list[str] [source]¶
Returns option names
- Returns:
list of option names as strings
- Return type:
- 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 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:
- 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
- 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
- detach() B ¶
Remove and return this block from container