CheckedDict

class configdict.configdict.CheckedDict(default=None, validator=None, docs=None, callback=None, precallback=None)[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

  • 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 None to prevent the modification

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

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

copy()

Create a copy of this CheckedDict

diff()

Get a dict containing keys:values which differ from default

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 the value corresponding to this key, if it was specified.

getType(key)

Returns the expected type for key, as a type which can be passed to isinstance

getTypestr(key)

The same as .getType but returns a string representation of the type/types possible for the value of this key

getValidateFunc(key)

Returns a function to validate a value for key, if there is one.

items()

keys()

override(key, value[, default])

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

pop(k[,d])

If key is not found, d is returned if given, otherwise KeyError is raised

popitem()

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

reset()

Resets the config to its default (inplace), and saves it.

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 after the operation

values()

Methods Documentation

addKey(key, value, type=None, choices=None, range=None, validatefunc=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 .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, 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 – a seq of possible values

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

  • validatefunc (Optional[Callable[[dict, Any], bool]]) – a function (config, value) -> bool, which 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

Returns errormsg. If value is of correct type, errormsg is None

Example

error = config.checkType(key, value)
if error:
    print(error)
Return type

Optional[str]

clear()None.  Remove all items from D.
copy()[source]

Create a copy of this CheckedDict

Return type

CheckedDict

diff()[source]

Get a dict containing keys:values which differ from default

Return type

dict

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 the value corresponding to this key, if it was specified.

Return type

Optional[tuple]

getType(key)[source]

Returns the expected type for key, as a type which can be passed to isinstance

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

Return type

Union[type, Tuple[type, …]]

getTypestr(key)[source]

The same as .getType but returns a string representation of the type/types possible for the value of this key

Return type

str

getValidateFunc(key)[source]

Returns a function to validate a value for key, if there is one. 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, 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
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 key is not found, d is returned if given, otherwise KeyError is raised

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), and saves it.

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 after the operation

Return type

~T

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