CoreConfig¶
- class maelzel.core.config.CoreConfig(updates=None, source='root', active=False, **kws)[source]¶
Bases:
ConfigDict
A CoreConfig is a
dict
like 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 therootConfig
, which is an instance ofCoreConfig
.Notice 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 (
str
|ConfigDict
|None
) – 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?
root
(key, value[, type, choices, range, ...])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: 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 selfcheckValue
(key, value)Check if value is valid for key
clear
()clone
([updates])Create a clone of this dict
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
.getType
but returns a string representation of the typegetValidateFunc
(key)Returns a function to validate a value for
key
isCongruentWith
(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)- 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.
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
save
([path])Save this config.
saveKey
(key)- rtype:
None
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?
- root(key, value, type=None, choices=None, range=None, doc='', validatefunc=None): CoreConfig | None = {'.enharmonic.debug': False, '.enharmonic.threeQuarterMicrotonePenalty': 20, '.quant.debug': False, '.quant.debugShowNumRows': 50, '.quant.divisionErrorWeight': None, '.quant.gridErrorExp': None, '.quant.gridErrorWeight': None, '.quant.rhythmComplexityWeight': None, '.rec.compressionBitrate': 224, '.reprShowFractionsAsFloat': True, '.show.autoClefChangesWindow': 1, '.show.centsAnnotationPlusSign': True, '.show.keepClefBiasFactor': 2.0, '.soundfilePlotWidth': 24, 'A4': 442, 'chordAdjustGain': True, 'dynamicCurveDynamics': 'ppp pp p mp mf f ff fff', 'dynamicCurveMaxdb': 0, 'dynamicCurveMindb': -60, 'dynamicCurveShape': 'expon(0.3)', 'enharmonic.horizontalWeight': 1, 'enharmonic.verticalWeight': 0.5, 'fixStringNotenames': False, 'htmlTheme': 'light', 'jupyterHtmlRepr': True, 'lilypondpath': '', 'musescorepath': '', 'openImagesInExternalApp': False, 'play.backend': 'default', 'play.defaultAmplitude': 1.0, 'play.defaultDynamic': 'f', 'play.engineName': 'maelzel.core', 'play.fade': 0.02, 'play.fadeShape': 'cos', 'play.gain': 1.0, 'play.generalMidiSoundfont': '', 'play.gracenoteDuration': '1/14', 'play.instr': 'sin', 'play.numChannels': 2, 'play.pitchInterpolation': 'linear', 'play.schedLatency': 0.05, 'play.soundfontAmpDiv': 16384, 'play.soundfontInterpolation': 'linear', 'play.unschedFadeout': 0.05, 'play.useDynamics': True, 'play.verbose': False, 'play.waitAfterStart': 0.5, 'quant.breakSyncopationsLevel': 'weak', 'quant.complexity': 'high', 'quant.nestedTuplets': None, 'quant.nestedTupletsInMusicxml': False, 'quant.syncopationMaxAsymmetry': 2, 'quant.syncopationMinBeatFraction': 0.3333333333333333, 'rec.blocking': True, 'rec.extratime': 0.0, 'rec.ksmps': 64, 'rec.numChannels': 2, 'rec.path': '', 'rec.sr': 44100, 'rec.verbose': False, 'reprShowFreq': False, 'semitoneDivisions': 4, 'show.arpeggiateChord': 'auto', 'show.arpeggioDuration': 0.5, 'show.asoluteOffsetForDetachedObjects': False, 'show.autoClefChanges': True, 'show.backend': 'lilypond', 'show.cacheImages': True, 'show.centSep': ',', 'show.centsAnnotationSnap': 2, 'show.centsAnnotationStyle': 'fontsize=6; placement=below', 'show.centsDeviationAsTextAnnotation': True, 'show.clipNoteheadShape': 'square', 'show.fillDynamicFromAmplitude': False, 'show.flagStyle': 'straight', 'show.format': 'png', 'show.glissEndStemless': False, 'show.glissHideTiedNotes': True, 'show.glissLineThickness': 2, 'show.glissLineType': 'solid', 'show.hideRedundantDynamics': True, 'show.horizontalSpacing': 'medium', 'show.jupyterMaxImageWidth': 1000, 'show.labelStyle': 'fontsize=9; placement=above', 'show.lilypondGlissandoMinimumLength': 5, 'show.lilypondPngStaffsizeScale': 1.5, 'show.measureAnnotationStyle': 'box=rectangle; fontsize=12', 'show.musicxmlFontScaling': 1.0, 'show.pageMarginMillimeters': 4, 'show.pageOrientation': 'portrait', 'show.pageSize': 'a4', 'show.pngResolution': 200, 'show.proportionalNotationDuration': '1/24', 'show.proportionalSpacing': False, 'show.proportionalSpacingKind': 'strict', 'show.referenceStaffsize': 12.0, 'show.rehearsalMarkStyle': 'box=rectangle; fontsize=13; bold', 'show.respellPitches': True, 'show.scaleFactor': 0.75, 'show.scaleFactorMusicxml': 0.8, 'show.staffSize': 10.0, 'show.voiceMaxStaves': 2, 'soundfilePlotHeight': 3, 'splitAcceptableDeviation': 4}¶
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: 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 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 returnTrue
if value is valid forkey
or 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
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 invalidkey
orvalue
, “” 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:
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]¶
Create a clone of this dict
- Parameters:
name – the name of the clone. If not given, the name of this dict is used.
persistent – Should the clone be made persitent?
cloneCallbacks – should the registered callbacks of the original (if any) be cloned?
updates (
Optional
[dict
]) – a dict with updates**kws – same as updates but only for keys which are valid keywords
- Return type:
- Returns:
the cloned dict
- 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-open
and 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
k
orNone
- Return type:
Optional
[list
]
- getDoc(key)¶
Get documentation for key (if present)
- Return type:
Optional
[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:
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:
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
.getType
but 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
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
- 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
]) – an 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
When
- 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:
scoring.enharmonics.EnharmonicOptions
- Returns:
a
maelzel.scoring.enharmonics.EnharmonicOptions
- makeQuantizationProfile()[source]¶
Create a QuantizationProfile from this config
This quantization profile can be passed to
Returns:
- Return type:
- makeRenderOptions()[source]¶
Create RenderOptions based on this config
- Return type:
- 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='')[source]¶
Save this config.
If no path is given, this config is saved as the default config and loaded in the next session. If a path is given, the config is saved to the given location and can be recreated via
CoreConfig.read()
- Parameters:
path – the path where to save this config
- 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 ¶