CheckedDict

class configdict.configdict.CheckedDict(default=None, validator=None, docs=None, callback=None, adaptor=None, precallback=None, autoload=True, strict=True, readonly=False, useDefaultTypes=True, hiddenPrefix='.')[source]

Bases: dict

A dictionary which checks that the keys and values are valid according to a default dict and a validator. In a CheckedDict, only keys are allowed which are already present in the default given.

Parameters:
  • default (Optional[dict[str, Any]]) – a dict will all default values. A config can accept only keys which are already present in the default

  • validator (Optional[dict[str, Any]]) –

    a dict containing choices and types for the keys in the default. Given a default like: {'keyA': 'foo', 'keyB': 20, 'keyC': 0.5}, a validator could be:

    {'keyA::choices': ['foo', 'bar'],
     'keyB::type': float,
     'keyB': lambda d, value: value > d['keyC'] * 10
     'keyC::range': (0, 1)
    }
    

    choices can be defined lazyly by giving a lambda which returns a list of possible choices

  • adaptor (Optional[dict[str, Callable[[Any], Any]]]) – a dict mapping keys to functions to convert the value before being set. An adaptor callback has the form (value: Any) -> Any. The value returned will be the value set for the given key

  • docs (Optional[dict[str, str]]) – a dict containing help lines for keys defined in default

  • callback (Optional[Callable[[str, Any], None]]) – function (key, value) -> None. This function is called after the modification has been done.

  • precallback – function (key, value) -> newvalue. If given, a precallback intercepts any change and can modify the value or return INVALID to prevent the modification

  • strict – if False keys are case and punktuation insensitive, meaning that a key like ‘foo.barBaz’ will also be matched by ‘foo_bar_baz’ or ‘foo_barbaz’

  • useDefaultTypes – if True, the type of the default value for a given key is enforced, with the exception of keys with a None value.

Example

from configdict import *
default = {
    'color': '#FF0000',
    'size': 10,
    'name': ''
}

validator = {
    'size::range': (6, 30),
    'color': lambda d, value: iscolor(value)
}

checked = CheckedDict(default, validator=validator)

Methods Summary

__call__(key, value[, type, choices, range, ...])

Call self as a function.

addAlias(key, alias)

Add an alias for key

addKey(key, value[, type, choices, range, ...])

Add a key: value pair to the default settings.

asYaml([sortKeys])

Returns this dict as yaml str, with comments, defaults, etc.

checkDict(d)

Check if dict d can be used to update self

checkValue(key, value)

Check if value is valid for key

clear()

clone([updates])

Clone self with modifications

copy()

Create a copy of this dict

diff([other])

Get a dict containing keys:values which differ from the default or from another dict

fromkeys([value])

Create a new dictionary with keys from iterable and values set to value.

get(key[, default])

Return the value for key if key is in the dictionary, else default.

getChoices(key)

Return a seq.

getDoc(key)

Get documentation for key (if present)

getRange(key)

Returns the valid range for this key's value, if specified.

getType(key)

Returns the expected type for key's value

getTypeHint(key)

Returns either the type (as str) or the typehint as set in the validator

getTypestr(key)

The same as .getType but returns a string representation of the type

getValidateFunc(key)

Returns a function to validate a value for key

items()

keys()

load()

Update any undefined key in self with the default value

makeDefault()

Create a version of this class with all values set to the default

normalizeKey(key)

Normalize this key.

override(key, value[, default])

The same as value if value is not None else config.get(key, default)

pop(k[,d])

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()

Remove and return a (key, value) pair as a 2-tuple.

reset()

Resets the config to its default (inplace)

setdefault(key[, default])

Insert key with a value of default if key is not in the dictionary.

update([d])

Update ths dict with d or any key:value pair passed as keyword

updated([d])

The same as update(), but returns self

validatorTypes(key)

Return the validator types for a given key

values()

Methods Documentation

__call__(key, value, type=None, choices=None, range=None, doc='', validatefunc=None)[source]

Call self as a function.

Return type:

None

addAlias(key, alias)[source]

Add an alias for key

This allows multiple keys for the same value

Return type:

None

addKey(key, value, type=None, choices=None, range=None, validatefunc=None, adaptor=None, typehint='', doc='')[source]

Add a key: value pair to the default settings.

This is used when building the default config item by item (see example). After adding all new keys it is necessary to call ConfigDict.load()

Example

cfg = ConfigDict("foo", load=False)
# We define a default step by step
cfg.addKey("width", 100, range=(50, 150))
cfg.addKey("color", "red", choices=("read", "blue", "green"))
cfg.addKey("height",
           doc="Height should be higher than width",
           validatefunc=lambda cfg, key, height: height > cfg['width'])
# Now update the dict with the newly defined default and any
# saved version
cfg.load()
Parameters:
  • key (str) – a string key

  • value (Any) – a default value

  • type (type | tuple[type, …] | None) – the type accepted, as passed to isinstance (can be a tuple)

  • choices (set | tuple | None) – a set/tuple of possible values

  • range (tuple[Any, Any] | None) – a (min, max) tuple defining an allowed range for this value

  • validatefunc (validatefunc_t | None) – a function (config: dict, key:str, value) -> bool, should return True if value is valid for key or False otherwise

  • doc – documentation for this key

Return type:

None

asYaml(sortKeys=False)[source]

Returns this dict as yaml str, with comments, defaults, etc.

Return type:

str

checkDict(d)[source]

Check if dict d can be used to update self

Parameters:

d (dict) – a dict which might update self

Return type:

str

Returns:

An error message if d has any invalid key or value, “” if everything is ok

checkValue(key, value)[source]

Check if value is valid for key

This is only possible if a validator was set

Parameters:
  • key (str) – the key to check

  • value – the value to check according to the contraints defined for the key (range, type, etc)

Return type:

str | None

Returns:

None if the value is acceptable for the key, an error message otherwise

Example

error = config.checkType(key, value)
if error:
    print(error)
clear() None.  Remove all items from D.
clone(updates=None, **kws)[source]

Clone self with modifications

Parameters:
  • updates (dict | None) – a dict with updated values for the clone dict

  • kws – any keyworg arg will be used to update the resulting dict

Return type:

Self

Returns:

the cloned dict

Examples

>>> import configdict
>>> d = configdict.CheckedDict(default={'A': 10, 'B': 20, 'C':30})
>>> d2 = d.clone({'B':21}, C=31)
>>> d2
{'A': 10, 'B': 21, 'C': 31)
copy()[source]

Create a copy of this dict

Return type:

Self

diff(other=None)[source]

Get a dict containing keys:values which differ from the default or from another dict

Parameters:

other (Optional[dict]) – if given, another dict which this is compared against. Otherwise the diff is calculated to the default dict

Return type:

dict

Returns:

a dict containing key – value pairs where self differs from other

fromkeys(value=None, /)

Create a new dictionary with keys from iterable and values set to value.

get(key, default=None, /)

Return the value for key if key is in the dictionary, else default.

getChoices(key)[source]

Return a seq. of possible values for key k or None

Return type:

list | None

getDoc(key)[source]

Get documentation for key (if present)

Return type:

str

getRange(key)[source]

Returns the valid range for this key’s value, if specified.

Parameters:

key (str) – the key to get the range from.

Return type:

tuple | None

Returns:

the range of values allowed for this key, or None if there is no range defined for this key.

Raises KeyError if the key is not present

getType(key)[source]

Returns the expected type for key’s value

Parameters:

key (str) – the key to query

Return type:

type | tuple[type, ...]

Note

All numbers are reduced to type float, all strings are of type str, otherwise the type of the default value, which can be a collection like a list or a dict

See Also: checkValue()

getTypeHint(key)[source]

Returns either the type (as str) or the typehint as set in the validator

Typehints are useful when the validator is set via a lambda (not via ::type). In this case the user can make clear what is actually expected by writing a typehint for a given key as <key>::typehint:<typehint>

Return type:

str

getTypestr(key)[source]

The same as .getType but returns a string representation of the type

Parameters:

key (str) – the key to query

Return type:

str

getValidateFunc(key)[source]

Returns a function to validate a value for key

A validate function has the form (config, value) -> bool

Parameters:

key (str) – the key to query for a validate function

Return type:

validatefunc_t | None

Returns:

The validate function, or None

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
load()[source]

Update any undefined key in self with the default value

Return type:

None

Example

::

from configdict import * config = CheckedConfig() config.addKey(…) config.addKey(…) … config.load() # Now config is fully defined

makeDefault()[source]

Create a version of this class with all values set to the default

Return type:

Self

normalizeKey(key)[source]

Normalize this key. Does not check if the resulting key is valid

Return type:

str

override(key, value, default=None)[source]

The same as value if value is not None else config.get(key, default)

Return type:

None

pop(k[, d]) v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

reset()[source]

Resets the config to its default (inplace)

Return type:

None

setdefault(key, default=None, /)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update(d=None, **kws)[source]

Update ths dict with d or any key:value pair passed as keyword

Return type:

None

updated(d=None, **kws)[source]

The same as update(), but returns self

Return type:

Self

validatorTypes(key)[source]

Return the validator types for a given key

A validator type for a given key can be a choices validator, where a set of possible values is given for a given key; it can be a range, where the value must be within a given range; a type, where a value must be of a certain type; or a function, which must return True if the value is valid, or False or an error message as string if the value is invalid

Parameters:

key (str) – the key to query

Return type:

list[str]

Returns:

a list of validator types, where each item is one of ‘choices’, ‘range’, ‘type’, ‘func’

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