configs

class cincoconfig.Schema(key=None, name=None, dynamic=False, env=None, schema=None)

A config schema containing all available configuration options. A schema’s fields and hierarchy are built dynamically.

schema = Schema()
schema.mode = ApplicationModeField(default='production', required=True)
schema.http.port = PortField(default=8080)
# the previous line implicitly performs "schema.http = Schema(key='http')"
schema.http.host = IPv4Address(default='127.0.0.1')

Accessing a field that does not exist, such as schema.http in the above code, dynamically creates and adds a new Schema.

Once a schema is completely defined, a Config is created by calling the schema. The config is populate with the default values specified for each field and can then load the configuration from a file.

Parameters
  • key (Optional[str]) – schema field key

  • dynamic (bool) – configurations created from this schema are dynamic and can add fields not originally in the schema _key

  • env (Union[bool, str, None]) – the environment variable prefix for this schema and all children schemas, for information, see Field Environment Variables

_add_field(name, field)

Add a field to the schema. This method will call field.__setkey__(self, key).

Return type

BaseField

Returns

the added field (field)

_get_field(key)
Return type

Optional[BaseField]

Returns

a field from the schema

__setattr__(name, value)
Parameters
  • name (str) – attribute name

  • value (Any) – field or schema to add to the schema

Return type

Any

__getattr__(name)

Retrieve a field by key or create a new Schema if the field doesn’t exist.

Parameters

name (str) – field or schema key

Return type

BaseField

__setitem__(name, value)
Return type

BaseField

Returns

field, equivalent to setattr(schema, key), however his method handles setting nested values. For example:

>>> schema = Schema()
>>> schema.x = Schema()
>>> schema['x.y'] = IntField(default=10)
>>> print(schema.x.y)
IntField(key='y', ...)

__getitem__(key)
Return type

BaseField

Returns

field, equivalent to getattr(schema, key), however his method handles retrieving nested values. For example:

>>> schema = Schema()
>>> schema.x.y = IntField(default=10)
>>> print(schema['x.y'])
IntField(key='y', ...)

__iter__()

Iterate over schema fields, produces as a list of tuples (key, field).

Return type

Iterator[Tuple[str, BaseField]]

__call__(parent=None, **data)

Compile the schema into an initial config with default values set.

_ref_path

Get the full reference path to the schema field. For example:

>>> schema = Schema()
>>> schema.x.y.z = Field()
>>> schema.x.y.z._ref_path
'x.y.z'
generate_argparse_parser(**parser_kwargs)

(Deprecated, will be removed in v1.0.0) generate an ArgumentParser for the schema. Use generate_argparse_parser().

Return type

ArgumentParser

Returns

an ArgumentParser containing arguments that match the schema’s fields

get_all_fields()

(Deprecated, will be removed in v1.0.0) get all the fields in the configuration. Use get_all_fields().

Return type

List[Tuple[str, Schema, BaseField]]

Returns

a list of tuples with (key, schema, field)

instance_method(key)

(Deprecated, will be removed in v1.0.0) decorator to register an instance method with the schema. Use instance_method().

Return type

Callable[[Config], None]

make_type(name, module=None, key_filename=None)

(Deprecated, will be removed in v1.0.0) create a new type from the schema. Use make_type().

Return type

Type[ConfigType]

validator(func)

(Deprecated, will be removed in v1.0.0) decorator to register a validator method with the schema. Use validator().

Return type

Callable[[Config], None]

class cincoconfig.Config(schema, parent=None, key_filename=None, **data)

A configuration.

Parsing and serializing the configuration is done via an intermediary object, a tree (dict) containing only basic (serializable) values (see Field to_basic()).

When saving, the config will convert the current config values to a tree and then pass the tree to the specified format. When loading, the file content’s will be passed to the formatter, which will return a basic tree that the config will validate and convert to actual config values.

The initial config will be populated with default values, specified in each Field’s default value. If the configuration needs to be initialized programmatically, prior to loading from a file, the load_tree() method can be used to load a basic tree.

schema = Schema()
schema.port = PortField()
schema.host = HostnameField()

config = schema()
# We didn't specify any default values, load from a dict

config.load_tree({
    'port': 8080,
    'host': '127.0.0.1'
})

# Loading an initial tree above is essentially equivalent to:
#
# schema = Schema()
# schema.port = PortField(default=8080)
# schema.host = HostnameField(default='127.0.0.1')
# config = schema()

Each config object can have an associated cincoconfig.KeyFile, passed in the constructor as key_filename. If the configuration file doesn’t have a key file path set, the config object will use the parent config’s key file. Requesting a key file will bubble up to the first config object that has the key filename set and, if no config has a keyfile, the default path will be used, DEFAULT_CINCOKEY_FILEPATH.

Parameters
  • schema (Schema) – backing schema, stored as _schema

  • parent (Optional[Config]) – parent config instance, only set when this config is a field of another config, stored as _parent

  • key_filename (Optional[str]) – path to key file

  • data – configuration values

_get_field(key)
Return type

Optional[BaseField]

Returns

a field from the schema or the dynamically added field if the schema is dynamic.

_set_value(key, value)

Set a configuration value. This method passes the value through the field validation chain and then calls the target field’s __setval__() to actually set the value.

Any exception that is raised by the field validation will be wrapped in an ValidationError and raised again.

Parameters
  • name – field key

  • value (Any) – value to validate and set

Raises

ValidationError – setting the value failed

Return type

Any

_set_default_value(key, value)

Set a default value without performing any validation. The value is set and the field is marked as having the initial default value.

Parameters
  • key (str) – field key

  • value (Any) – field default value

Return type

None

_get_value(key)
Return type

Any

__setattr__(name, value)

Validate a configuration value and set it.

Parameters
  • name (str) – field key

  • value (Any) – value

Return type

Any

__getattr__(name)

Retrieve a config value.

Parameters

name (str) – field key

Return type

Any

__setitem__(key, value)

Set a field value, equivalent to setattr(config, key), however this method handles setting nested values. For example:

>>> schema = Schema()
>>> schema.x.y = IntField(default=10)
>>> config = schema()
>>> config['x.y'] = 20
>>> print(config.x.y)
20
Return type

Any

__getitem__(key)
Return type

Any

Returns

field value, equivalent to getattr(config, key), however his method handles retrieving nested values. For example:

>>> schema = Schema()
>>> schema.x.y = IntField(default=10)
>>> config = schema()
>>> print(config['x.y'])
10

__iter__()
Return type

Iterator[Tuple[str, Any]]

__contains__(key)

Check if key is in the configuration. This method handles checking nested values. For example:

>>> schema = Schema()
>>> schema.x.y = IntField(default=10)
>>> config = schema()
>>> 'x.y' in config
True
Return type

bool

_ref_path
Returns

the full reference path to the configuration

_keyfile
Returns

the config’s encryption key file (if not set, get the parent config’s key file)

_key_filename
Returns

the path to the cinco encryption key file (if not set, get the parent config’s key filename)

cmdline_args_override(args, ignore=None)

(Deprecated, will be removed in v1.0.0) override configuration values from the command line arguments. Use cmdline_args_override().

Parameters
Return type

None

dumps(format, virtual=False, sensitive_mask=None, **kwargs)

Serialize the configuration to a string with the specified format.

Parameters
  • format (str) – output format

  • virtual (bool) – include virtual fields in the output

  • sensitive_mask (Optional[str]) – replace secure values, see to_tree()

  • kwargs – additional keyword arguments to pass to the formatter’s __init__()

Return type

bytes

Returns

serialized configuration file content

property full_path: str

(Deprecated, will be removed in v1.0.0) get the full path to the configuration :returns: the full path to this configuration

load(filename, format)

Load the configuration from a file.

Parameters
  • filename (str) – source filename

  • format (str) – source format

load_tree(tree, validate=True)

Load a tree and then validate the values.

Parameters

tree (dict) – a basic value tree

Return type

None

loads(content, format, **kwargs)

Load a configuration from a str or bytes and process any IncludeField.

Parameters
  • content (Union[str, bytes]) – configuration content

  • format (str) – content format

  • kwargs – additional keyword arguments to pass to the formatter’s __init__()

save(filename, format, **kwargs)

Save the configuration to a file. Additional keyword arguments are passed to dumps().

Parameters
  • filename (str) – destination file path

  • format (str) – output format

Param

additional keyword arguments for dumps()

to_tree(virtual=False, sensitive_mask=None)

Convert the configuration values to a tree.

The sensitive_mask parameter is an optional string that will replace sensitive values in the tree.

  • None (default) - include the value as-is in the tree

  • len(sensitive_mask) == 1 (single character) - replace every character with the sensitive_mask character. value = sensitive_mask * len(value)

  • len(sensitive_mask) != 1 (empty or multi character string) - replace the entire value with the sensitive_mask.

Parameters
  • virtual (bool) – include virtual field values in the tree

  • sensitive_mask (Optional[str]) – mask secure values with a string

Return type

dict

Returns

the basic tree containing all set values

validate(collect_errors=False)

Perform validation on the entire config.

Return type

List[ValidationError]

class cincoconfig.ConfigType(parent=None, **kwargs)

A base class for configuration types. A subclass of ConfigType is returned by the make_type() function.

Parameters

parent (Optional[Config]) – parent configuration