config - Configuration definitions¶
Overview¶
Complex applications (and some library modules like logging) could be often parametrized
via configuration. This module provides a framework for unified structured configuration
that supports:
configuration options of various data type, including lists and other complex types
validation
direct manipulation of configuration values
reading from (and writing into) configuration in
configparserformatexchanging configuration (for example between processes) using Google protobuf messages
Architecture¶
The framework is based around two classes:
Config- Collection of configuration options and sub-collections. Particular configuration is then realized as descendant from this class, that defines configuration options in constructor, and customize the validation when required.Option- Abstract base class for configuration options, where descendants implement handling of particular data type. This module provides implementation for next data types:str,int,float,bool,Decimal,Enum,Flag,UUID,MIME,ZMQAddress,list,dataclass,PyExpr,PyCodeandPyCallable. It also provides special optionsConfigOptionandConfigListOption.
Additionally, the DirectoryScheme abstract base class defines set of mostly
used application directories. The function get_directory_scheme() could be then used
to obtain instance that implements platform-specific standards for file-system location
for these directories. Currently, only “Windows”, “Linux” and “MacOS” directory schemes
are supported.
Tip
You may use get_directory_scheme() function to get the scheme suitable for platform
where your application is running.
Tip
If your configurations contain secrets like passwords or access tokens, that would be
read from files via configparser, you should consider to use EnvExtendedInterpolation
that has support for option values defined via environment variables.
Usage¶
First, you need to define your own configuration.
from enum import IntEnum
from firebird.base.config import Config, StrOption, IntOption, ListOption
class SampleEnum(IntEnum):
"Enum for testing"
UNKNOWN = 0
READY = 1
RUNNING = 2
WAITING = 3
SUSPENDED = 4
FINISHED = 5
ABORTED = 6
class DbConfig(Config):
"Simple database config"
def __init__(self, name: str):
super().__init__(name)
# options
self.database: StrOption = StrOption('database', 'Database connection string',
required=True)
self.user: StrOption = StrOption('user', 'User name', required=True,
default='SYSDBA')
self.password: StrOption = StrOption('password', 'User password')
class SampleConfig(Config):
"""Sample Config.
Has three options and two sub-configs.
"""
def __init__(self):
super().__init__('sample-config')
# options
self.opt_str: StrOption = StrOption('opt_str', "Sample string option")
self.opt_int: IntOption = StrOption('opt_int', "Sample int option")
self.enum_list: ListOption = ListOption('enum_list', "List of enum values",
item_type=SampleEnum)
# sub configs
self.master_db: DbConfig = DbConfig('master-db')
self.backup_db: DbConfig = DbConfig('backup-db')
Important
Option must be assigned to Config attributes with the same name as option name.
Typically you need only one instance of your configuration class in application.
app_config: SampleConfig = SampleConfig()
Typically, your application is configured using file(s) in configparser format. You may
create initial one using Config.get_config() method.
Note
Config.get_config() works with current configuration values. When called on “empty”
instance it returns “default” configuration. Option values that match the default are
returned as commented out.
>>> print(app_config.get_config())
[sample-config]
;
; Sample Config.
;
; Has three options and two sub-configs.
;
; opt_str
; -------
;
; data type: str
;
; [optional] Sample string option
;
;opt_str = <UNDEFINED>
; opt_int
; -------
;
; data type: str
;
; [optional] Sample int option
;
;opt_int = <UNDEFINED>
; enum_list
; ---------
;
; data type: list
;
; [optional] List of enum values
;
;enum_list = <UNDEFINED>
[master-db]
;
; Simple DB config
;
; database
; --------
;
; data type: str
;
; [REQUIRED] Database connection string
;
;database = <UNDEFINED>
; user
; ----
;
; data type: str
;
; [REQUIRED] User name
;
;user = SYSDBA
; password
; --------
;
; data type: str
;
; [optional] User password
;
;password = <UNDEFINED>
[backup-db]
;
; Simple DB config
;
; database
; --------
;
; data type: str
;
; [REQUIRED] Database connection string
;
;database = <UNDEFINED>
; user
; ----
;
; data type: str
;
; [REQUIRED] User name
;
;user = SYSDBA
; password
; --------
;
; data type: str
;
; [optional] User password
;
;password = <UNDEFINED>
To read the configuration from file, use the ConfigParser and pass it
to Config.load_config() method.
Example configuration file:
; myapp.cfg
[DEFAULT]
password = masterkey
[sample-config]
opt_str = Lorem ipsum
enum_list = ready, finished, aborted
[master-db]
database = primary
user = tester
password = lockpick
[backup-db]
database = secondary
from configparser import ConfigParser
cfg = ConfigParser()
cfg.read('myapp.cfg')
app_config.load_config(cfg)
Access to configuration values is through attributes on your Config instance, and
their value attribute.
>>> app_config.opt_str.value
Lorem ipsum
>>> app_config.opt_int.value
>>> app_config.enum_list.value
[READY, FINISHED, ABORTED]
>>> app_config.master_db.database.value
primary
>>> app_config.master_db.user.value
tester
>>> app_config.master_db.password.value
lockpick
>>> app_config.backup_db.database.value
secondary
>>> app_config.backup_db.user.value
SYSDBA
>>> app_config.backup_db.password.value
masterkey
ConfigProto¶
You can transfer configuration (state) between instances of your Config classes using
Google Protocol Buffer message firebird.base.ConfigProto and methods
save_proto() and load_proto().
The protobuf message is defined in /proto/config.proto.
syntax = "proto3";
package firebird.base;
import "google/protobuf/any.proto";
import "google/protobuf/struct.proto";
message Value {
oneof kind {
string as_string = 2 ;
bytes as_bytes = 3 ;
bool as_bool = 4 ;
double as_double = 5 ;
float as_float = 6 ;
sint32 as_sint32 = 7 ;
sint64 as_sint64 = 8 ;
uint32 as_uint32 = 9 ;
uint64 as_uint64 = 10 ;
google.protobuf.Any as_msg = 11 ;
}
}
message ConfigProto {
map<string, Value> options = 1 ;
map<string, ConfigProto> configs = 2 ;
}
Note
You can use it directly or via protobuf registry.
# Direct use
from firebird.base.config import ConfigProto
cfg_msg = ConfigProto()
Because the proto file is NOT registered in protobuf registry, you must register
it manually. The proto file is listed in pyproject.toml under “firebird.base.protobuf”
entrypoint, so use load_registered('firebird.base.protobuf') for its registration.
from firebird.base.protobuf import load_registered, create_message
load_registered('firebird.base.protobuf')
cfg_msg = create_message('firebird.base.ConfigProto')
Important
Although Option also provides methods save_proto() and load_proto()
to transfer option value in/out ConfigProto message, you should always use methods
on Config instance because option’s serialization may relly on Config instance that
owns them.
See also
Constants¶
- firebird.base.config.PROTO_CONFIG Fully qualified name for `ConfigProto`_ protobuf.¶
Tip
To address ConfigProto in functions like create_message(),
use PROTO_CONFIG constant.
Application Directory Scheme¶
New in version 1.1.0.
Changed in version 1.2.0.
- class firebird.base.config.DirectoryScheme(name: str, version: str | None = None, *, force_home: bool = False)[source]¶
Bases:
objectClass that provide paths to typically used application directories.
Default scheme uses HOME directory as root for other directories. The HOME is determined as follows:
If environment variable
<app_name>_HOMEexists, its value is used as HOME directory.HOME directory is set to current working directory.
Note
All paths are set when the instance is created and can be changed later.
- Parameters:
Example:
scheme = get_directory_scheme("MyApp", "1.0") config_path = scheme.config / "settings.ini" log_file = scheme.logs / "app.log" user_cache_dir = scheme.user_cache print(f"Config dir: {scheme.config}") print(f"User cache: {user_cache_dir}")
- has_home_env() bool[source]¶
Returns True if HOME directory is set by “<app_name>_HOME” environment variable.
- Return type:
- property cache: Path¶
Directory for application cache data.
Such data are locally generated as a result of time-consuming I/O or calculation. The application must be able to regenerate or restore the data. The cached files can be deleted without loss of data.
- property data: Path¶
Directory for state information / persistent data modified by application as it runs.
- property home: Path¶
HOME directory. Initial value is path set by
<app_name>_HOMEenvironment variable, or to current working directory when variable is not defined.Important
When new value is assigned, the general directories (i.e. all except user-specific and TMP) are redefined as subdirectories of new home path ONLY when HOME was initially defined using
<app_name>_HOMEenvironment variable, or instance was created withforce_home= True.However, all paths could be still changed individually to any value.
- class firebird.base.config.WindowsDirectoryScheme(name: str, version: str | None = None, *, force_home: bool = False)[source]¶
Bases:
DirectorySchemeDirectory scheme conforming to Windows standards (e.g., APPDATA, PROGRAMDATA).
If HOME is defined using “<app_name>_HOME” environment variable, or
force_homeparameter is True, only user-specific directories and TMP are set according to platform standars, while general directories remain as defined by baseDirectoryScheme.
- class firebird.base.config.LinuxDirectoryScheme(name: str, version: str | None = None, *, force_home: bool = False)[source]¶
Bases:
DirectorySchemeDirectory scheme that conforms to Linux standards.
If HOME is defined using “<app_name>_HOME” environment variable, or
force_homeparameter is True, only user-specific directories and TMP are set according to platform standars, while general directories remain as defined by baseDirectoryScheme.
- class firebird.base.config.MacOSDirectoryScheme(name: str, version: str | None = None, *, force_home: bool = False)[source]¶
Bases:
DirectorySchemeDirectory scheme that conforms to MacOS standards.
If HOME is defined using “<app_name>_HOME” environment variable, only user-specific directories and TMP are set according to platform standars, while general directories remain as defined by base
DirectoryScheme.
- firebird.base.config.get_directory_scheme(app_name: str, version: str | None = None, *, force_home: bool = False) DirectoryScheme[source]¶
Returns directory scheme for current platform.
- Parameters:
app_name (str) – Application name
version (str | None) – Application version string
force_home (bool) – When True, the general directies are always set to subdirectories of
DirectoryScheme.homedirectory. When False, then home is used ONLY when it’s set by “<app_name>_HOME” environment variable.
- Return type:
Configparser interpolation¶
- class firebird.base.config.EnvExtendedInterpolation[source]¶
Bases:
ExtendedInterpolationNew in version 1.8.0.
Modified version of
configparser.ExtendedInterpolationclass that adds special handling for “env” section that returns value of specified environment variable, or empty string if such variable is not defined.Example:
${env:path} is reference to PATH environment variable.
Config¶
- class firebird.base.config.Config(name: str, *, optional: bool = False, description: str | None = None)[source]¶
Bases:
objectCollection of configuration options, potentially nested.
- Parameters:
name (str) – Name associated with Config (default section name).
optional (bool) – Whether config is optional (True) or mandatory (False) for configuration file (see
load_config()for details).description (str | None) – Optional configuration description. Can span multiple lines.
Important
Descendants must define individual options and sub configs as instance attributes.
Attributes defined as instances of
Optionsubclasses represent individual configuration settings. Attributes defined as instances ofConfigsubclasses represent nested configuration sections with fixed names. Attributes defined asConfigOptionorConfigListOptionallow for referring to nested sections whose names (section headers) are themselves configurable.- clear(*, to_default: bool = True) None[source]¶
Clears all owned options and options in owned sub-configs.
- Parameters:
to_default (bool) – If True, sets the option values to defaults, else to None.
- Return type:
None
- get_config(*, plain: bool = False) str[source]¶
Returns string containing text lines suitable for use in configuration file processed with
ConfigParser.Important
When config is optional and the name is an empty string, it returns empty string.
- get_description() str[source]¶
Configuration description. Can span multiple lines.
Note: If description is not provided on instance creation, class doc string.
- Return type:
- load_config(config: ConfigParser, section: str | None = None) None[source]¶
Update configuration values from a
ConfigParserinstance.- Parameters:
config (ConfigParser) –
ConfigParserinstance containing configuration values.section (str | None) – Name of the
ConfigParsersection corresponding to thisConfiginstance. IfNone, usesself.name.
- Return type:
None
- Behavior:
Reads values for directly owned
Optioninstances from the specifiedsection.Recursively calls
load_configon directly ownedConfiginstances using their respectivenameattribute as the section name.Recursively calls
load_configonConfiginstances referenced by ownedConfigOptionandConfigListOptionvalues, using the section names stored within those options.
- Raises:
Error – If
sectiondoes not exist inconfigandself.optionalisFalse(unlesssectionisDEFAULTSECT). Also wraps underlyingValueErrororKeyErrorfrom option parsing.KeyError – Propagated if an invalid section name is used for a nested config.
ValueError – Propagated if an option string cannot be parsed correctly.
- Parameters:
config (ConfigParser) –
section (str | None) –
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains option values and sub-configs.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option values and sub-configs should be stored.
- Return type:
None
- validate() None[source]¶
Recursively validates all directly owned options and sub-configs.
- Checks whether:
all required options have a non-
Nonevalue.required
ConfigOptionvalues have a non-empty section name.required
ConfigListOptionvalues have a non-empty list.all options are defined as instance attributes with the same name as
option.name.calls
validate()on all nestedConfiginstances (direct attributes, values ofConfigOption, and items inConfigListOption).
- Raises:
Error – When any validation constraint is violated.
- Return type:
None
- property configs: list[Config]¶
List of nested
Configinstances associated with this instance.Includes:
Configinstances directly assigned as attributes.The
Configinstance held by anyConfigOptionattribute.All
Configinstances within the list held by anyConfigListOptionattribute.
- property optional: bool¶
Whether config is optional (False) or mandatory (True) for configuration file (see
load_config()for details).
Options¶
- class firebird.base.config.Option(name: str, datatype: type[T], description: str, *, required: bool = False, default: T | None = None)[source]¶
-
Generic abstract base class for configuration options.
- Parameters:
- _get_config_lines(*, plain: bool = False) list[str][source]¶
Returns list of strings containing text lines suitable for use in configuration file processed with
ConfigParser.Text lines with configuration start with comment marker
;and end with newline.- Parameters:
plain (bool) – When True, it outputs only the option value. When False, it includes also option description and other helpful information.
- Return type:
Note
This function is intended for internal use. To get string describing current configuration that is suitable for configuration files, use
get_configmethod.
- abstract clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- get_config(*, plain: bool = False) str[source]¶
Returns string containing text lines suitable for use in configuration file processed with
ConfigParser.
- load_config(config: ConfigParser, section: str) None[source]¶
Update option value from
ConfigParserinstance.- Parameters:
config (ConfigParser) – ConfigParser instance.
section (str) – Name of ConfigParser section that should be used to get new option value.
- Raises:
ValueError – When option value cannot be loadded.
KeyError – If section does not exists, and it’s not
configparser.DEFAULTSECT.
- Return type:
None
- abstract load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contain this option’s value under
proto.options[self.name].- Raises:
TypeError – If the protobuf field type is incompatible with the option.
ValueError – If the deserialized value content is invalid for the option.
- Return type:
None
- abstract save_proto(proto: ConfigProto) None[source]¶
Serialize the current value into
ConfigProtomessage.The value is stored in
proto.options[self.name]using an appropriate protobuf field type (e.g.,as_string,as_sint64). If the current value isNone, nothing is saved for this option.- Parameters:
proto (ConfigProto) – Protobuf message where the option value should be stored.
- Return type:
None
- abstract set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- abstract set_value(value: T | None) None[source]¶
Set new option value.
- Parameters:
value (T | None) – New option value.
- Raises:
TypeError – When the new value is not of the expected
datatype.ValueError – When the
valuecontent is invalid for the specific option type (e.g., disallowed enum member, negative for unsigned int).
- Return type:
None
- validate() None[source]¶
Validates option state.
- Raises:
Error – When required option does not have a value.
- Return type:
None
- default: T¶
Default option value.
- class firebird.base.config.StrOption(name: str, description: str, *, required: bool = False, default: str | None = None)[source]¶
-
Configuration option with string value.
New in version 1.6.1: Support for verticals to preserve leading whitespace.
- Parameters:
Important
Multiline string values could contain significant leading whitespace, but ConfigParser multiline string values have leading whitespace removed. To circumvent this, the
StrOptionsupports assignment of text values where lines start with|character. This character is removed, along with any number of subsequent whitespace characters that are between|and first non-whitespace character on first line starting with|.- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.IntOption(name: str, description: str, *, required: bool = False, default: int | None = None, signed: bool = False)[source]¶
-
Configuration option with integer value.
- Parameters:
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.FloatOption(name: str, description: str, *, required: bool = False, default: float | None = None)[source]¶
-
Configuration option with float value.
- Parameters:
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.DecimalOption(name: str, description: str, *, required: bool = False, default: Decimal | None = None)[source]¶
-
Configuration option with decimal.Decimal value.
- Parameters:
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto)[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- save_proto(proto: ConfigProto)[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.BoolOption(name: str, description: str, *, required: bool = False, default: bool | None = None)[source]¶
-
Configuration option with boolean value.
- Parameters:
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.ZMQAddressOption(name: str, description: str, *, required: bool = False, default: ZMQAddress = None)[source]¶
Bases:
Option[ZMQAddress]Configuration option with
ZMQAddressvalue.- Parameters:
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- get_value() ZMQAddress | None[source]¶
Returns current option value.
- Return type:
ZMQAddress | None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- set_value(value: ZMQAddress | None) None[source]¶
Set new option value.
- Parameters:
value (ZMQAddress | None) – New option value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- property value: ZMQAddress | None¶
Current option value
- class firebird.base.config.EnumOption(name: str, enum_class: type[E], description: str, *, required: bool = False, default: E | None = None, allowed: list | None = None)[source]¶
-
Configuration option with enum value.
- Parameters:
name (str) – Option name.
description (str) – Option description. Can span multiple lines.
required (bool) – True if option must have a value.
default (T) – Default option value.
allowed (list | None) – List of allowed Enum members. When not defined, all members of enum type are allowed.
enum_class (type[E]) –
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains option value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.FlagOption(name: str, flag_class: type[F], description: str, *, required: bool = False, default: F | None = None, allowed: list | None = None)[source]¶
-
Configuration option with flag value.
- Parameters:
name (str) – Option name.
description (str) – Option description. Can span multiple lines.
required (bool) – True if option must have a value.
default (T) – Default option value.
allowed (list | None) – List of allowed Flag members. When not defined, all members of flag type are allowed.
flag_class (type[F]) –
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains option value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.UUIDOption(name: str, description: str, *, required: bool = False, default: UUID | None = None)[source]¶
-
Configuration option with UUID value.
- Parameters:
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.MIMEOption(name: str, description: str, *, required: bool = False, default: MIME = None)[source]¶
-
Configuration option with MIME type specification value.
- Parameters:
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.ListOption(name: str, item_type: type | Sequence[type], description: str, *, required: bool = False, default: list | None = None, separator: str | None = None)[source]¶
-
Configuration option with list of values.
- Parameters:
name (str) – Option name.
item_type (type | Sequence[type]) – Datatype of list items. It could be a type or sequence of types. If multiple types are provided, each value in config file must have format:
type_name:value_as_str.description (str) – Option description. Can span multiple lines.
required (bool) – True if option must have a value.
default (T) – Default option value.
separator (str | None) – String that separates list item values when options value is read from
ConfigParser. It’s possible to use a line break as separator. If separator isNone[default] and the value contains line breaks, it uses the line break as separator, otherwise it uses comma as separator.
Important
When option is read from
ConfigParser, empty values are ignored.- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- set_value(value: list | None) None[source]¶
Set new option value.
- Parameters:
value (list | None) – New option value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- item_types: Sequence[type]¶
Datatypes of list items. If there is more than one type, each value in config file must have format:
type_name:value_as_str.
- separator: str | None¶
String that separates list item values when options value is read from
ConfigParser. Default separator is None. It’s possible to use a line break as separator. If separator isNoneand the value contains line breaks, it uses the line break as separator, otherwise it uses comma as separator.
- class firebird.base.config.DataclassOption(name: str, dataclass: type, description: str, *, required: bool = False, default: Any | None = None, separator: str | None = None, fields: dict[str, type] | None = None)[source]¶
-
Configuration option holding an instance of a Python dataclass.
Parses configuration from a string representation where each field of the dataclass is defined on its own line or separated by a defined
separator. The format for each field within the string isfield_name: value_as_str.Relies on the
firebird.base.strconvmodule to convert thevalue_as_strpart for each field into the appropriate Python type based on the dataclass’s type hints or the explicitly providedfieldsmapping.Important
Ensure type hints in the dataclass are concrete types (or provide the
fieldsmapping) and thatstrconvhas registered convertors for all field types used.When read from
ConfigParser, empty field definitions in the value string might be ignored or cause errors depending on parsing.
- Parameters:
name (str) – Option name.
dataclass (type) – The dataclass type this option holds an instance of.
description (str) – Option description.
required (bool) – If True, the option must have a value (cannot be None).
default (T) – Default instance of the dataclass.
separator (str | None) – String separating
field:valuepairs in the config file string. Handles line breaks automatically ifNone. See class docs.fields (dict[str, type] | None) – Optional override mapping field names to types. Useful if type hints are complex or need overriding. If None, uses
get_type_hints.
Example:
from dataclasses import dataclass, field from firebird.base.config import Config, DataclassOption from firebird.base.strconv import register_convertor # If custom types needed from configparser import ConfigParser import io @dataclass class DBInfo: host: str user: str port: int = 5432 # Field with default ssl_mode: bool = field(default=False) class AppSettings(Config): def __init__(self): super().__init__('app') self.database = DataclassOption('database', DBInfo, 'Database connection details') # --- Configuration File Content --- config_data = ''' [app] database = host: db.example.com user: app_user port: 15432 ''' # Note: ssl_mode uses its default (False) as it's not specified. # --- Loading --- app_config = AppSettings() parser = ConfigParser() parser.read_string(config_data) app_config.load_config(parser) # --- Accessing --- db_info = app_config.database.value print(f"Is DBInfo instance: {isinstance(db_info, DBInfo)}") # Output: True print(f"DB Host: {db_info.host}") # Output: db.example.com print(f"DB Port: {db_info.port}") # Output: 15432 (overrode default) print(f"DB User: {db_info.user}") # Output: app_user print(f"DB SSL: {db_info.ssl_mode}") # Output: False (used default) # --- Getting Config String --- # print(app_config.get_config()) would regenerate the structure
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- get_as_str() str[source]¶
Returns the string representation of the current dataclass value.
- Return type:
- load_proto(proto: ConfigProto) None[source]¶
Deserialize dataclass from
proto.options[self.name].as_string.- Parameters:
proto (ConfigProto) –
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize dataclass into
proto.options[self.name].as_string.- Parameters:
proto (ConfigProto) –
- Return type:
None
- set_as_str(value: str) None[source]¶
Creates and sets the dataclass instance from its string representation.
Parses the
valuestring expectingfield_name: value_as_stritems, separated according to theseparatorlogic. Usesstrconvto convert eachvalue_as_strto the required field type. Finally, instantiates the dataclass using the parsed field values.- Parameters:
value (str) – String containing the dataclass representation.
- Raises:
ValueError – If the string format is invalid, a field name is unknown, a value cannot be converted by
strconv, or the resulting dictionary of values cannot instantiate the dataclass (e.g., missing required fields without defaults).TypeError – If
strconvconversion fails with a type error.
- Return type:
None
- separator: str | None¶
String that separates dataclass field values when options value is read from
ConfigParser. Default separator is None. It’s possible to use a line break as separator. If separator isNoneand the value contains line breaks, it uses the line break as separator, otherwise it uses comma as separator.
- class firebird.base.config.PathOption(name: str, description: str, *, required: bool = False, default: Path | None = None)[source]¶
-
Configuration option with
pathlib.Pathvalue.- Parameters:
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.PyExprOption(name: str, description: str, *, required: bool = False, default: PyExpr | None = None)[source]¶
-
String configuration option with Python expression value.
- Parameters:
- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.PyCodeOption(name: str, description: str, *, required: bool = False, default: PyCode | None = None)[source]¶
-
String configuration option with Python code value.
- Parameters:
Important
Python code must be properly indented, but ConfigParser multiline string values have leading whitespace removed. To circumvent this, the
PyCodeOptionsupports assignment of text values where lines start with|character. This character is removed, along with any number of subsequent whitespace characters that are between|and first non-whitespace character on first line starting with|.- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- class firebird.base.config.PyCallableOption(name: str, description: str, signature: Signature | Callable | str, *, required: bool = False, default: PyCallable | None = None)[source]¶
Bases:
Option[PyCallable]String configuration option with Python callable value.
- Parameters:
name (str) – Option name.
description (str) – Option description. Can span multiple lines.
signature (Signature | Callable | str) – Callable signature, callable or string with callable signature (function header).
required (bool) – True if option must have a value.
default (T) – Default option value.
Important
Python code must be properly indented, but
ConfigParsermultiline string values have leading whitespace removed. To circumvent this, thePyCallableOptionsupports assignment of text values where lines start with|character. This character is removed, along with any number of subsequent whitespace characters that are between|and first non-whitespace character on first line starting with|.- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
- Parameters:
to_default (bool) – If True, sets the option value to default value, else to None.
- Return type:
None
- get_value() PyCallable | None[source]¶
Returns current option value.
- Return type:
PyCallable | None
- load_proto(proto: ConfigProto) None[source]¶
Deserialize value from
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message that may contains options value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the argument is not a valid option value.
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize value into
ConfigProtomessage.- Parameters:
proto (ConfigProto) – Protobuf message where option value should be stored.
- Return type:
None
- set_as_str(value: str) None[source]¶
Set new option value from string.
- Parameters:
value (str) – New option value.
- Raises:
ValueError – When the argument is not a valid option value.
- Return type:
None
- set_value(value: PyCallable | None) None[source]¶
Set new option value.
- Parameters:
value (PyCallable | None) – New option value.
- Raises:
TypeError – When the new value is of the wrong type.
ValueError – When the callable has wrong signature.
- Return type:
None
- property value: PyCallable | None¶
Current option value
- class firebird.base.config.ConfigOption(name: str, config: Config, description: str, *, required: bool = False, default: str | None = None)[source]¶
-
Option whose ‘value’ is a Config instance, but stores/parses its section name.
This allows having nested configuration sections where the section name itself is configurable. The actual
Configobject must be passed during initialization. Thevalueproperty returns thisConfigobject, while methods likeset_as_str,get_as_str,get_formatted,load_proto,save_protooperate on theConfigobject’s name (the section name).Loading/saving the contents of the referenced
Configobject is handled by the parentConfig’sload_config/save_protomethods.- Parameters:
name (str) – Option name.
description (str) – Option description. Can span multiple lines.
config (Config) – Option’s value.
required (bool) – True if option must have a value.
default (T) – Default
Config.namevalue.
Important
Assigning directly to the
valueproperty is not supported like other options; useset_as_stror assign to theConfigobject’snameattribute indirectly if needed (though typically done viaload_config).Note
The “empty” value for this option is not
None(because theConfiginstance always exists), but an empty string forConfig.nameattribute.- clear(*, to_default: bool = True) None[source]¶
Clears the option value.
Note
This method calls
clear(to_default).- Parameters:
to_default (bool) – If True, sets the
Config.nameto default value, else to empty string.- Return type:
None
- get_as_str() str[source]¶
Returns the current section name of the associated
Configinstance.- Return type:
- get_formatted() str[source]¶
Return value formatted for use in config file.
The string contains section name that will be used to store the
Configvalues.- Return type:
- load_proto(proto: ConfigProto) None[source]¶
Deserialize section name from
proto.options[self.name].as_string.- Parameters:
proto (ConfigProto) –
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize section name into
proto.options[self.name].as_string.- Parameters:
proto (ConfigProto) –
- Return type:
None
- set_as_str(value: str) None[source]¶
Sets the section name for the associated
Configinstance.- Parameters:
value (str) – The new section name (string).
- Return type:
None
- set_value(value: str | None) None[source]¶
Sets the section name (indirectly). Does not accept a Config object.
This method primarily handles setting the default section name during init. Setting the name post-init is typically done via
load_configorset_as_str. PassingNonesets the name to empty string (if not required).- Parameters:
value (str | None) – The new section name (string) or None.
- Raises:
ValueError – If
valueis None or empty string and the option is required.- Return type:
None
- class firebird.base.config.ConfigListOption(name: str, item_type: type[Config], description: str, *, required: bool = False, separator: str | None = None)[source]¶
-
Option holding a list of Config instances, parsing/storing their section names.
This option manages a list of
Configobjects, all of the same specifieditem_type. However, in configuration files (ConfigParser) and Protobuf messages, it stores and parses a list of strings, where each string is the section name corresponding to one of theConfiginstances in the list.Loading/saving the contents (options) of each referenced
Configsection is handled by the parentConfig’sload_config/save_protomethods when they iterate through the main configuration structure. This option itself only deals with the list of names that identify which sections belong here.When
set_as_strorload_configprocesses the string list of names, it creates new instances ofitem_type(the specifiedConfigsubclass) for each name found.Important
When read from
ConfigParser, empty values in the list of names are ignored.- Parameters:
name (str) – Option name identifying where the list of section names is stored.
item_type (type[Config]) – The specific
Configsubclass for items in the list. All items will be instances of this type.description (str) – Option description. Can span multiple lines.
required (bool) – If True, the list of section names cannot be empty.
separator (str | None) – String separating section names in the config file value. Handles line breaks automatically if
None. See class docs.
Example:
from firebird.base.config import Config, StrOption, ConfigListOption from configparser import ConfigParser import io class WorkerConfig(Config): '''Configuration for a worker process.''' def __init__(self, name: str): super().__init__(name) self.task_type = StrOption('task_type', 'Type of task', default='generic') class MainAppConfig(Config): '''Main application configuration.''' def __init__(self): super().__init__('main_app') self.workers = ConfigListOption('workers', WorkerConfig, 'List of worker configurations (section names)') # --- Configuration File Content --- config_data = ''' [main_app] workers = worker_alpha, worker_beta ; List of section names [worker_alpha] task_type = processing [worker_beta] task_type = reporting ''' # --- Loading --- app_config = MainAppConfig() parser = ConfigParser() parser.read_string(config_data) app_config.load_config(parser) # Loads 'workers' list and worker sections # --- Accessing --- print(f"Worker section names: {app_config.workers.get_as_str()}") # Output: Worker section names: worker_alpha, worker_beta worker_list = app_config.workers.value print(f"Number of workers: {len(worker_list)}") # Output: 2 print(f"First worker name: {worker_list[0].name}") # Output: worker_alpha print(f"First worker task: {worker_list[0].task_type.value}") # Output: processing print(f"Second worker task: {worker_list[1].task_type.value}") # Output: reporting # --- Getting Config String --- # print(app_config.get_config()) would regenerate the structure
- clear(*, to_default: bool = True) None[source]¶
Clears the list of
Configinstances.- Parameters:
to_default (bool) – This parameter is ignored as there’s no default list content. The list is simply emptied.
- Return type:
None
- get_as_str() str[source]¶
Returns the list of contained section names as a separator-joined string.
- Return type:
- get_formatted() str[source]¶
Returns the list of section names formatted for use in a config file.
- Return type:
- load_proto(proto: ConfigProto) None[source]¶
Deserialize list of section names from
proto.options[self.name].as_string.- Parameters:
proto (ConfigProto) –
- Return type:
None
- save_proto(proto: ConfigProto) None[source]¶
Serialize list of section names into
proto.options[self.name].as_string.- Parameters:
proto (ConfigProto) –
- Return type:
None
- set_as_str(value: str) None[source]¶
Populates the list with new
Configinstances based on section names in string.Parses the input string
value(using the definedseparatorlogic) to get a list of section names. For each non-empty name, creates a new instance ofself.item_typewith that name and adds it to the internal list, replacing any previous list content.- Parameters:
value (str) – String containing separator-defined list of section names.
- Raises:
ValueError – If the string parsing encounters issues (though typically just results in fewer items if format is odd).
- Return type:
None
- set_value(value: list | None) None[source]¶
Sets the list of
Configinstances.Replaces the current list with the provided one. Ensures all items in the new list are of the correct
item_type. PassingNoneclears the list.
- validate() None[source]¶
Validates the option state.
Checks if the list is non-empty if required. Calls
validate()on eachConfiginstance currently in the list.
- separator: str | None¶
String that separates values when options value is read from
ConfigParser. Default separator is None. It’s possible to use a line break as separator. If separator isNoneand the value contains line breaks, it uses the line break as separator, otherwise it uses comma as separator.