CoreConfig¶
- class maelzel.core.config.CoreConfig(updates=None, source='root', active=False, **kws)[source]¶
Bases:
ConfigDictA CoreConfig is a
dictlike object which controls many aspects of maelzel.coreA CoreConfig reads its settings from a persistent copy. This persistent version is generated whenever the user calls the method
CoreConfig.save(). When maelzel.core is imported it reads this configuration and creates the root, which is an instance ofCoreConfigand can be accessed via the class variable :attr:CoreConfig.rootNotice that a configuration, in order to modify the behaviour of the environment, needs to be either actively used (passed as an argument to any function accepting a configuration object) or set as active via
setConfig()or by calling itsCoreConfig.activate()method.- Parameters:
updates (
Optional[dict[str,Any]]) – if given, a dict which will be used to update the newly created instancesource (
ConfigDict|str) – either a ConfigDict to use as prototype; ‘root’, to use the root config (the last saved config); ‘load’ to reload the last saved config This ConfigDict will be a copy of that prototypeactive – if True, set this CoreConfig as active (modifying the current Workspace)
kws – any keywords will be used to update the config and must be valid keys for a CoreConfig
See Also
Configuration Keys for documentation on the keys and their possible values
See also
maelzel.core.workspace.makeConfig()Attributes Summary
The name of this ConfigDict.
Is this a persistent ConfigDict?
Methods Summary
__call__(key, value[, type, choices, range, ...])Call self as a function.
activate()Make this config the active config
addKey(key, value[, type, choices, range, ...])Add a
key: valuepair 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
dcan be used to update selfcheckValue(key, value)Check if value is valid for key
clear()clone([updates])Create a new CoreConfig from this config with modified values
copy()Create a copy of this config
diff([other])Get a dict containing keys:values which differ from the default or from another dict
dump()Dump this config to stdout
edit([waitOnModified, sortKeys])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([maxWidth, ...])Generate ReST documentation for this dictionary
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 this key's value, if specified.
getType(key)Returns the expected type for key's value
getTypestr(key)The same as
.getTypebut returns a string representation of the typegetValidateFunc(key)Returns a function to validate a value for
keyisCongruentWith(other)Returns True if self and other share same default
items()keys()load([configpath])Read the saved config, update self.
Create a version of this class with all values set to the default
Create EnharmonicOptions from this config
Create a QuantizationProfile from this config
Create RenderOptions based on this config
normalizeKey(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.
read(path)Create a new CoreConfig from the saved config
registerCallback(func[, pattern])Register a callback to be fired when a key matching the given pattern is changed.
Remove the saved default config
reset([removesaved])Reset this config to its defaults
resetKey(key)Reset the given key to its default value
root()save([path, header])Save this to its persistent path (or a custom path)
saveKey(key)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 selfvalidatorTypes(key)Return the validator types for a given key
values()Attributes Documentation
- name¶
The name of this ConfigDict. The name determines where it is saved
- persistent¶
Is this a persistent ConfigDict?
Methods Documentation
- __call__(key, value, type=None, choices=None, range=None, doc='', validatefunc=None)¶
Call self as a function.
- Return type:
None
- activate()[source]¶
Make this config the active config
This is just a shortcut for
setConfig(self)- Return type:
None
- addKey(key, value, type=None, choices=None, range=None, validatefunc=None, adaptor=None, doc=None)¶
Add a
key: valuepair 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 keyvalue (
Any) – a default valuetype (
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 valuesrange (
Optional[tuple[Any,Any]]) – a (min, max) tuple defining an allowed range for this valuevalidatefunc (
Optional[Callable[[dict,str,Any],bool]]) – a function(config: dict, key:str, value) -> bool, should returnTrueif value is valid forkeyor False otherwisedoc (
Optional[str]) – documentation for this key
- Return type:
None
- asCsv()¶
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
dcan be used to update self- Parameters:
d (dict) – a dict which might update self
- Return type:
str- Returns:
An error message if
dhas any invalidkeyorvalue, “” if everything is ok
- checkValue(key, value)¶
Check if value is valid for key
This is only possible if a validator was set
- Parameters:
key (
str) – the key to checkvalue – 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]¶
Create a new CoreConfig from this config with modified values
Keywords which are not valid symbols (keys containing periods, like ‘quant.nestedTuples’) can be used by removing any invalid characters. Also, config keys are not case sensitive. In the case above,
quantNestedTuplescould be usedNote
A
CoreConfigcan be used as a context manager to activate it temporarily. Used together with this method it can be used to modify any rendering or playback condition for the code within that block.- Parameters:
updates (
Optional[dict]) – a dictionary of updates to apply to the new config**kws – keyword arguments to pass to the new config.
- Return type:
- Returns:
the new CoreConfig
Example
Render an object with modified quantization
>>> from maelzel.core import * >>> cfg = getConfig() >>> with cfg.clone(quantNestedTuples=False): ... Chain(...).show()
- diff(other=None)¶
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- Returns:
value pairs where self differs from other
- Return type:
a dict containing key
- dump()¶
Dump this config to stdout
- edit(waitOnModified=True, sortKeys=False)¶
Edit this config by opening it in an external application.
The format used is yaml. 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 linuxxdg-openand in windowsstart, 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
sortKeys – if True, keys appear in sorted order
- Return type:
None
- fromkeys(value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
- generateRstDocumentation(maxWidth=80, withName=True, withDescription=True, withLink=True, linkPrefix='')¶
Generate ReST documentation for this dictionary
The generated string can then be dumped to a file and included in documentation
- Parameters:
maxWidth – the max. width of a line
withName – if True, add the name of the config (if it has a name)
withDescription – if True, add this dict’s description (if it has any)
withLink – if True, for each key:value pair generate a RST link using the given linkPrefix For example, for a key ‘foo’ and a linkPrefix=’config’ the generated link will be
.. _configfoo. This link can be used within the documentation to link to this keylinkPrefix – a prefix to use for all links
- Return type:
str- Returns:
the generated rst documentation, as 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
korNone- Return type:
list|None
- getDoc(key)¶
Get documentation for key (if present)
- Return type:
str
- getPath()¶
Return the path this dict will be saved to
If the dict has no name, an empty string is returned
- Return type:
str
- getRange(key)¶
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()
- getTypestr(key)¶
The same as
.getTypebut returns a string representation of the type- Parameters:
key (
str) – the key to query- Return type:
str
- getValidateFunc(key)¶
Returns a function to validate a value for
keyA 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
- isCongruentWith(other)¶
Returns True if self and other share same default
- Return type:
bool
- 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)¶
Read the saved config, update self.
If there is no saved version or the dict has no name, then the dict is set to the default defined at construction.
When defining the default iteratively (via addKey), calling load marks the end of the definition: after calling load no other keys can be added to this dict.
- Parameters:
configpath (
Optional[str]) – a custom path to load a saved version from. Otherwise it is loaded fromConfigDict.getPath()(this is only possible if the dict has a name, since the resolved path is determined from the name)- Return type:
None
Example
from configdict import ConfigDict conf = ConfigDict('foo.bar') conf.addKey('key1', 'value1', ...) conf.addKey('key2', 'value2', ...) ... # When finished defining keys, call .load conf.load() # Now the dict can be used
- makeDefault()¶
Create a version of this class with all values set to the default
- Return type:
TypeVar(_CheckedDictT, bound= CheckedDict)
- makeEnharmonicOptions()[source]¶
Create EnharmonicOptions from this config
The returned object is used within maelzel.scoring.enharmonics to determine the best to
- Return type:
enharmonics.EnharmonicOptions
- Returns:
a
maelzel.scoring.enharmonics.EnharmonicOptions
- makeQuantizationProfile()[source]¶
Create a QuantizationProfile from this config
- Return type:
QuantizationProfile
- makeRenderOptions()[source]¶
Create RenderOptions based on this config
- Return type:
RenderOptions
- Returns:
a RenderOptions instance
- static normalizeKey(key)¶
- Return type:
str
- 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 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.
- classmethod read(path)[source]¶
Create a new CoreConfig from the saved config
The path points to a .yaml config saved via
CoreConfig.save()- Parameters:
path (
str) – the path to a config- Returns:
the new CoreConfig
- registerCallback(func, pattern='.*')¶
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 – a regex pattern. The function will be called if the pattern matches the key being modified.
- Return type:
None
- reset(removesaved=False)[source]¶
Reset this config to its defaults
- Parameters:
removesaved – if True, remove any saved config
- Return type:
None
- resetKey(key)¶
Reset the given key to its default value
- Return type:
None
- save(path='', header='')¶
Save this to its persistent path (or a custom path)
If this config was created with the
persistentflag on, it does not need to be saved manually, it is saved whenever it is modified. However if it was created withpersistent=Falsethen this method can be used to write this dict so it will be loaded in a future session- Parameters:
path – the path to save the config. If None and this is a named config, it is saved to the path returned by
getPath()header – if given, this string is written prior to the dict, as a comment. This is only supported when saving to yaml
- 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)¶
Update this dict with the values in d.
Note
keywords have priority over d (similar to builtin dict)
- 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- Return type:
TypeVar(_CheckedDictT, bound= CheckedDict)
- validatorTypes(key)¶
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¶