Document and Values

The Document and Value classes are used to represent the configuration data after parsing.

Usage

import erbsland.conf as elcl

def parse_configuration(file_name: str):
    doc = elcl.load(file_name)
    # Access required values and check the type.
    server_name = doc.get_text("main.server.name")
    # Provide a default if the value is optional.
    port = doc.get_int("main.server.port", default=8080)
    # Iterating over section lists naturally.
    for client_value in doc["client"]:
        name = client_value.get_text("name")
        ip = client_value.get_text("ip")
        port = client_value.get_int("port", default=9000)

        # Reading values from optional sections.
        if filter_value := client_value.get("filter", default=None):
            # Requiring lists of specific types.
            keywords = filter_value.get_list("keywords", str)
            # ...
        # ...
    # ...

def main():
    try:
        parse_configuration("quick-intro.elcl")
        # ... running the application ...
        exit(0)
    except elcl.Error as e:
        print(f"Error reading the configuration.\n{e}")
        exit(1)

if __name__ == "__main__":
    main()

Interface

class Document

A hierarchical configuration document.

abstractmethod to_flat_dict() dict[NamePath, Value]

Return all values in a flat mapping keyed by their full name paths.

class Value

Represents a single value within a configuration document.

Supported Types for expected_type and value_type

The supported native value types you can use in various interfaces are:

The type checking for all as_... and get_... methods that have a expected_type is strict; an integer is not implicitly converted to a float or string.

For relaxed type conversion, use the convert_to() method.

Options for the Parameter key

For providing name-paths, you have the following options:

str

You can provide a name-path in text format. This path is parsed and converted into a NamePath object.

int

To address a value by index, you can provide an integer. This index works almost like using <code>value[index]</code>, except that a ConfValueNotFound is thrown instead of an IndexError.

Name

Using a name is like using a name-path with a single element.

NamePath

By providing a name path object, you can address any value in the value tree, relative to the current value.

About the Exceptions Raised by this API

You can use a catch-all except Error: in your code to catch all exceptions raised by this API and output it as string to provide a user-friendly error message. The Error class is the base class for all exceptions raised by this API. The following exception are thrown by the API:

ConfSyntaxError

If the string representation of a name path contains syntax errors.

ConfValueNotFound

If no value exists at the location of key and no default value is provided.

ConfTypeMismatch

If the value at the given location does not match the expected value and no default value is provided.

KeyError

The class ConfValueNotFound is also derived from KeyError, to make value lookup compatible with other frameworks.

Error

This is the base class for all exceptions raised by this API.

Native Values for Value Types

The following table shows the native value types for each non-section/list value type:

VALUE_INT:

int

VALUE_BOOL:

bool

VALUE_FLOAT:

float

VALUE_TEXT:

str

VALUE_BYTES:

bytes

VALUE_DATE:

datetime.date

VALUE_TIME:

Time (derived from datetime.time)

VALUE_DATETIME:

DateTime (derived from datetime.datetime)

VALUE_TIMEDELTA:

TimeDelta

VALUE_REGEX:

re.Pattern

For every other value type, the native value is always None. Please note: Value lists are not stored as native lists.

abstract property type: ValueType

Return the type of this value.

abstract property name: Name | None

Return the name of this value.

abstract property name_path: NamePath

Return the full path to this value.

abstract property parent: Value | None

Get the parent of this value, or None if this is the root value.

abstract property has_parent: bool

Test if this value has a parent.

abstract property is_root: bool

Test if this is the root value (i.e. the document).

abstract property location: Location | None

Get the location of this value.

abstract property native: Any | None

Return the stored native data.

Returns:

The native values you can expect is described in Native Values for Value Types.

abstractmethod get(key: str | int | Name | NamePath, default: Any = None) Value | Any

Return a child value by name, name path, or index.

Parameters:
  • key – The key used to access the child value. See Options for the Parameter key for details.

  • default – Value to return when the child does not exist.

Returns:

The child value, or default if none is found.

Raises:

See About the Exceptions Raised by this API.

abstract property first: Value

Return the first child of this value.

Raises:

ConfValueNotFound – If the value has no children.

abstract property last: Value

Return the last child of this value.

Raises:

ConfValueNotFound – If the value has no children.

abstractmethod as_type(expected_type: Type[T], *, default: T | None | MissingType = MISSING) T | None

Convert the value to value_type if this value has the correct type.

Type checking and conversion is strict; an integer is not implicitly converted to a float or string.

Note:

If you use list as type, you will get a unchecked value list as list[Value], and only if the value if of type ValueType.VALUE_LIST. Please use the method as_list() or get_list if you want to get a type checked list of values.

Parameters:
  • expected_type – The type you expect and to convert the value to. See Supported Types for expected_type and value_type for details about the supported types.

  • default – The value returned if the conversion fails. If no default is provided, an exception is raised when the conversion fails.

Returns:

The converted value, or default if the conversion fails and if it is provided, if not, an exception is raised.

Raises:

See About the Exceptions Raised by this API.

as_int(*, default: int | None | MissingType = MISSING) int | None

Shorthand for as_type(int, default).

as_bool(*, default: bool | None | MissingType = MISSING) bool | None

Shorthand for as_type(bool, default).

as_float(*, default: float | None | MissingType = MISSING) float | None

Shorthand for as_type(float, default).

as_text(*, default: str | None | MissingType = MISSING) str | None

Shorthand for as_type(str, default).

as_date(*, default: date | None | MissingType = MISSING) date | None

Shorthand for as_type(datetime.date, default).

as_time(*, default: time | None | MissingType = MISSING) time | None

Shorthand for as_type(datetime.time, default).

as_date_time(*, default: datetime | None | MissingType = MISSING) datetime | None

Shorthand for as_type(datetime.datetime, default).

as_bytes(*, default: bytes | None | MissingType = MISSING) bytes | None

Shorthand for as_type(bytes, default).

as_time_delta(*, default: TimeDelta | None | MissingType = MISSING) TimeDelta | None

Shorthand for as_type(TimeDelta, default).

as_regex(*, default: Pattern[str] | None | MissingType = MISSING) Pattern[str] | None

Shorthand for as_type(Pattern, default).

as_value_list(*, default: list | None | MissingType = MISSING) list | None

Shorthand for as_type(list, default).

abstractmethod as_list(expected_type: Type[T], *, default: list[T] | None | MissingType = MISSING) list[T] | None

Expect and return a list with elements of the type value_type.

This method first checks if it can build a list of elements with the expected type. If this is not possible, an exception is raised or, if provided, default is returned.

Hint:

We do not recommend using a default value for this method. If a single element in the list does not match the expected type, the default value will be returned, and it isn’t clear for the user why the default was used. The exception will always contain the exact location and name path to the failed entry in the list.

Important:

This method will treat a single value as a list of one element.

Parameters:
  • expected_type – The value type that is expected for all values in the returned list. See Supported Types for expected_type and value_type for details.

  • default – A default value to return if no list of elements can be built. If no default is provided, an exception is raised.

Returns:

A list with values of the expected type, or if a default is provided, the given default value.

Raises:

See About the Exceptions Raised by this API.

abstractmethod to_test_text(output: ~erbsland.conf.test_output.TestOutput = <TestOutput.DEFAULT: 0>) str

Return the canonical string representation used in conformance tests.

abstractmethod to_test_value_tree(output: ~erbsland.conf.test_output.TestOutput = <TestOutput.DEFAULT: 0>) str

Return a graphical representation of the value tree.

abstractmethod get_type(key: str | int | Name | NamePath, expected_type: Type[T], *, default: T | None | MissingType = MISSING) T | None

Get a value by name, name path, or index and check if it is of the specified type.

This method works like: self[key].as_type(value_type, default=default). See as_type for more details.

Parameters:
  • key – The key used to access the child value. See Options for the Parameter key for details.

  • expected_type – The type you expect and to convert the value to. See Supported Types for expected_type and value_type for details about the supported types.

  • default – The value returned if the conversion fails. If no default is provided, an exception is raised when the conversion fails.

Returns:

The converted value, or default if the conversion fails and if it is provided, if not, an exception is raised.

Raises:

See About the Exceptions Raised by this API.

get_int(key: str | int | Name | NamePath, *, default: int | None | MissingType = MISSING) int | None

Shorthand for get_type(key, int, default).

get_bool(key: str | int | Name | NamePath, *, default: bool | None | MissingType = MISSING) bool | None

Shorthand for get_type(key, bool, default).

get_float(key: str | int | Name | NamePath, *, default: float | None | MissingType = MISSING) float | None

Shorthand for get_type(key, float, default).

get_text(key: str | int | Name | NamePath, *, default: str | None | MissingType = MISSING) str | None

Shorthand for get_type(key, str, default).

get_date(key: str | int | Name | NamePath, *, default: date | None | MissingType = MISSING) date | None

Shorthand for get_type(key, datetime.date, default).

get_time(key: str | int | Name | NamePath, *, default: time | None | MissingType = MISSING) time | None

Shorthand for get_type(key, datetime.time, default).

get_date_time(key: str | int | Name | NamePath, *, default: datetime | None | MissingType = MISSING) datetime | None

Shorthand for get_type(key, datetime.datetime, default).

get_bytes(key: str | int | Name | NamePath, *, default: bytes | None | MissingType = MISSING) bytes | None

Shorthand for get_type(key, bytes, default).

get_time_delta(key: str | int | Name | NamePath, *, default: TimeDelta | None | MissingType = MISSING) TimeDelta | None

Shorthand for get_type(key, TimeDelta, default).

get_regex(key: str | int | Name | NamePath, *, default: Pattern[str] | None | MissingType = MISSING) Pattern[str] | None

Shorthand for get_type(key, Pattern, default).

get_value_list(key: str | int | Name | NamePath, *, default: list | None | MissingType = MISSING) list | None

Shorthand for get_type(key, list, default).

abstractmethod get_list(key: str | int | Name | NamePath, expected_type: Type[T], *, default: list[T] | None | MissingType = MISSING) list[T] | None

Get and expect a list with elements of the type value_type.

This method works like value[key].as_list(expected_type, default=default). See as_list for important details.

Parameters:
Returns:

A list with values of the expected type, or if a default is provided, the given default value.

Raises:

See About the Exceptions Raised by this API.

abstractmethod convert_to(value_type: Type[T]) T

Best effort conversion to the specified type.

If the conversion fails, a default value for the type is returned.

Parameters:

value_type – The type you expect and to convert the value to. See Supported Types for expected_type and value_type for details about the supported types.

Returns:

You always get a value of the specified type.

class ValueType(*values)

All possible types of configuration values.

UNDEFINED = 'Undefined'

An undefined value type.

INTEGER = 'Integer'

An integer value.

BOOLEAN = 'Boolean'

A boolean value.

FLOAT = 'Float'

A floating-point value.

TEXT = 'Text'

A text value.

DATE = 'Date'

A date value.

TIME = 'Time'

A time value.

DATE_TIME = 'DateTime'

A date-time value.

BYTES = 'Bytes'

A bytes value.

TIME_DELTA = 'TimeDelta'

A time-delta value.

REGEX = 'RegEx'

A regular expression value.

VALUE_LIST = 'ValueList'

A list of values.

SECTION_LIST = 'SectionList'

A list of sections.

INTERMEDIATE_SECTION = 'IntermediateSection'

An intermediate section.

SECTION_WITH_NAMES = 'SectionWithNames'

A section containing named values.

SECTION_WITH_TEXTS = 'SectionWithTexts'

A section containing text values.

DOCUMENT = 'Document'

The root document value.

is_single_value() bool

Return True if this type represents a single scalar value.

is_list() bool

Return True if this type represents a list.

is_map() bool

Return True if this type represents a mapping.

is_container() bool

Return True if this type can contain other values.

is_section() bool

Return True if this type represents a section or a section list.

class TestOutput(*values)

Format flags for displaying test output.

CONTAINER_SIZE = 1

Display the container size.

POSITION = 2

Display the position in the document.

SOURCE_ID = 4

Display the source identifier.

MINIMAL_ESC = 8

Only escape special characters.

ALIGN_VALUES = 16

Align the arrows and values in value tree output.

DEFAULT = 0

Default format.