CheckedDict

class configdict.configdict.CheckedDict(default=None, validator=None, docs=None, callback=None, adaptor=None, precallback=None, autoload=True, strict=True, readonly=False, advancedPrefix='.')[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[[str, Any, Any], Any]]]) – a dict mapping keys to functions to convert the value before being set. An adaptor callback has the form (key: str, newvalue: Any, oldvalue: 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’

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.

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

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)

rtype:

str

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

addKey(key, value, type=None, choices=None, range=None, validatefunc=None, adaptor=None, doc=None)[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 (Union[type, tuple[type, ...], None]) – the type accepted, as passed to isinstance (can be a tuple)

  • choices (Union[Set, tuple, None]) – a set/tuple of possible values

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

  • validatefunc (Optional[Callable[[dict, str, Any], bool]]) – a function (config: dict, key:str, value) -> bool, should return True if value is valid for key or False otherwise

  • doc (Optional[str]) – 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:

Optional[str]

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 (Optional[dict]) – a dict with updated values for the clone dict

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

Return type:

TypeVar(_CheckedDictT, bound= CheckedDict)

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:

TypeVar(_CheckedDictT, bound= CheckedDict)

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:

Optional[list]

getDoc(key)[source]

Get documentation for key (if present)

Return type:

Optional[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:

Optional[tuple]

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:

Union[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()

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:

Optional[Callable[[dict, str, Any], bool]]

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:

TypeVar(_CheckedDictT, bound= CheckedDict)

static normalizeKey(key)[source]
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:

TypeVar(_CheckedDictT, bound= CheckedDict)

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