ConfigDict

class configdict.configdict.ConfigDict(name, default=None, validator=None, docs=None, precallback=None, persistent=True, load=True, fmt='yaml', sortKeys=False)[source]

Bases: configdict.configdict.CheckedDict

This is a (optionally) persistent, unique dictionary used for configuration of a module / app. It is saved under the config folder determined by the OS (and is thus OS dependent) and no two instances of the same config can coexist.

Parameters
  • name (str) – a str of the form prefix.name or prefix/name (these are the same) or simply name if this is an isolated configuration (not part of a bigger project). The data will be saved at $USERCONFIGDIR/{prefix}/{name}.{fmt} if prefix is given, or $USERCONFIGDIR/{name}.{fmt}. For instance, in Linux a config with a name “myproj.myconfig” and a yaml format will be saved to “~/.config/mydir/myconfig.yaml”

  • default (Optional[Dict[str, Any]]) – a dict with all default values. A config can accept only keys which are already present in the default. This value can be left as None if the config is built successively. See example below

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

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

    {
      'keyA::choices': ['foo', 'bar'],
      'keyB::type': float,
      'keyB::range': (10, 30)
    }
    

    Choices can be defined lazyly by giving a lambda

  • docs (Optional[Dict[str, str]]) – a dict containing documentation for each key

  • persistent – if True, any change to the dict will be saved.

  • load – if True, the saved version will be loaded after creation. This is disabled if no default dict is given. .load should be called manually in this case (see example)

  • precallback (Optional[Callable[[ConfigDict, str, Any, Any], Any]]) – function (dict, key, oldvalue, newvalue) -> None|newvalue, If given, it is called before the modification is done. This function should return None to allow modification, any value to modify the value, or raise ValueError to stop the transaction

  • sortKeys – if True, keys are sorted whenever the dict is saved/edited.

Example

config = ConfigDict("myproj.subproj")
config.addKey("keyA", 10, doc="documentaion of keyA")
config.addKey("keyB", 0.5, range=(0, 1))
config.addKey("keyC", "blue", choices=("blue", "red"),
              doc="documentation of keyC")
config.load()

# The same effect can be achieved by passing the default/validator/doc

default = {
    "keyA": 10,
    "keyB": 0.5,
    "keyC": "blue
}

validator = {
    "keyB::range": (0, 1),
    "keyC::choices": ("blue", "red")
}

docs = {
    "keyA": "documentation of keyA"
    "keyC": "documentation of keyC"
}

cfg = ConfigDict("myproj.subproj",
                 default=default,
                 validator=validator,
                 docs=docs)
# no need to call .load in this case

Attributes Summary

name

The name of this ConfigDict.

persistent

Is this a persistent ConfigDict?

Methods Summary

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

Add a key: value pair to the default settings.

asCsv()

Returns this dict as a csv str, with columns: key, value, spec, doc

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([name, persistent, cloneCallbacks])

Create a clone of this dict

copy()

Create a copy if this ConfigDict.

diff()

Get a dict containing keys:values which differ from default

dump()

Dump this config to stdout

edit([waitOnModified])

Edit this config by opening it in an external application.

fromkeys([value])

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

generateRstDocumentation()

rtype

str

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)

getPath()

Return the path this dict will be saved to

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

load([configpath])

Read the saved config, update self.

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.

registerCallback(func[, pattern])

Register a callback to be fired when a key matching the given pattern is changed.

reset()

Reset this dict to its default

save([path])

Normally a config doesn’t need to be saved by the user, it is saved whenever it is modified.

setdefault(key[, default])

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

update([d])

Update this dict with the values in d.

updated([d])

The same as update(), but returns self after the operation

values()

Attributes Documentation

name

The name of this ConfigDict. The name determines where it is saved (if persist==True)

Return type

Optional[str]

persistent

Is this a persistent ConfigDict?

Return type

bool

Methods Documentation

addKey(key, value, type=None, choices=None, range=None, validatefunc=None, doc=None)

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

asCsv()[source]

Returns this dict as a csv str, with columns: key, value, spec, doc

Return type

str

asYaml(sortKeys=False)

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

Return type

str

checkDict(d)

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)

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.
clone(name='', persistent=None, cloneCallbacks=False)[source]

Create a clone of this dict

Parameters
  • name (str) – the name of the clone. If a name is not given, the clone cannot be made persistent

  • persistent (Optional[bool]) – given that this clone has a distinct name, should the clone be made persitent?

  • cloneCallbacks – should the registered callbacks of the original (if any) be also cloned?

Return type

ConfigDict

Returns

the cloned dict

copy()[source]

Create a copy if this ConfigDict. The resulting copy will be unnamed and thus not persistent.

Return type

ConfigDict

Returns

the copy of this dict

diff()

Get a dict containing keys:values which differ from default

Return type

dict

dump()[source]

Dump this config to stdout

edit(waitOnModified=False)[source]

Edit this config by opening it in an external application. The format used is yaml, because it allows to embed comments. This is independent of the format used for persistence. The application used is the user’s default application for the .yaml format and can be configured at the os level. In macos we use open, in linux xdg-open and in windows start, which all respond to the user’s own configuration regarding default applications.

Note

A temporary file is created for editing. The persisted file is only modified if the editing is accepted.

Parameters

waitOnModified – if True, the transaction is accepted whenever the file being edited is saved. Otherwise a message box is created which needs to be clicked in order to confirm the transaction. Just exiting the application will not cancel the edit job since many applications which have a server mode or unique instance mode might in fact exit right away from the perspective of the subprocess which launched them

Return type

None

fromkeys(value=None, /)

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

generateRstDocumentation()[source]
Return type

str

get(key, default=None, /)

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

getChoices(key)

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

Return type

Optional[list]

getDoc(key)

Get documentation for key (if present)

Return type

Optional[str]

getPath()[source]

Return the path this dict will be saved to

Return type

str

getRange(key)

Returns the valid range for the value corresponding to this key, if it was specified.

Return type

Optional[tuple]

getType(key)

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)

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)

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
load(configpath=None)[source]

Read the saved config, update self.

Return type

None

override(key, value, default=None)

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.

registerCallback(func, pattern=None)[source]

Register a callback to be fired when a key matching the given pattern is changed. If no pattern is given, the function will be called for every key.

Parameters
  • func (Callable[[ConfigDict, str, Any], None]) – a function of the form (dict, key, value) -> None, where dict is this ConfigDict itself, key is the key which was just changed and value is the new value.

  • pattern (Optional[str]) – call func when pattern matches key.

Return type

None

reset()[source]

Reset this dict to its default

Return type

None

save(path=None)[source]

Normally a config doesn’t need to be saved by the user, it is saved whenever it is modified.

Parameters
  • path (str) – the path to save the config. If None and this is a named config, it is saved to the path returned by getPath()

  • sortKeys – if True, the keys are sorted when saving

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 this dict with the values in d.

Parameters
  • d (Optional[dict]) – values in this dictionary will overwrite values in self. Keys not present in self will raise an exception

  • **kws – any key:value here will also be used to update self

Return type

None

updated(d=None, **kws)

The same as update(), but returns self after the operation

Return type

~T

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