Default management of the psyplot package

This module defines the necessary classes, data and functions for the default configuration of the module. The structure is motivated and to larger parts taken from the matplotlib package.

Classes:

RcParams(*args, **kwargs)

A dictionary object including validation

SubDict(base, base_str[, pattern, ...])

Class that keeps week reference to the base dictionary

Data:

defaultParams

dict with default values and validation functions

rcParams

RcParams instance that stores default formatoptions and configuration settings.

Functions:

get_configdir([name, env_key])

Return the string representing the configuration directory.

psyplot_fname([env_key, fname, if_exists])

Get the location of the config file.

safe_list(iterable)

Function to create a list

validate_bool(b)

Convert b to a boolean or raise

validate_bool_maybe_none(b)

Convert b to a boolean or raise

validate_dict(d)

Validate a dictionary

validate_files_exist(files)

Validate if all pathnames in a given list exists

validate_path_exists(s)

If s is a path, return s, else False

validate_str(s)

Validate a string

validate_stringlist(s)

Validate a list of strings

validate_stringset(*args, **kwargs)

Validate a set of strings

class psyplot.config.rcsetup.RcParams(*args, **kwargs)[source]

Bases: dict

A dictionary object including validation

validating functions are defined and associated with rc parameters in defaultParams

This class is essentially the same as in maplotlibs RcParams but has the additional find_and_replace() method.

Parameters:
  • defaultParams (dict) – The defaultParams to use (see the defaultParams attribute). By default, the psyplot.config.rcsetup.defaultParams dictionary is used

  • *args – Any key-value pair for the initialization of the dictionary

  • **kwargs – Any key-value pair for the initialization of the dictionary

Attributes:

HEADER

defaultParams

descriptions

The description of each keyword in the rcParams dictionary

msg_depr

msg_depr_ignore

validate

Dictionary with validation methods as values

Methods:

catch()

Context manager to reset the rcParams afterwards

connect(key, func)

Connect a function to the given formatoption

copy()

Make sure, the right class is retained

disconnect([key, func])

Disconnect the connections to the an rcParams key

dump([fname, overwrite, include_keys, ...])

Dump this instance to a yaml file

find_all(pattern)

Return the subset of this RcParams dictionary whose keys match, using re.search(), the given pattern.

find_and_replace(*args, **kwargs)

Like find_all() but the given strings are replaced

keys()

Return sorted list of keys.

load_from_file([fname])

Update rcParams from user-defined settings

load_plugins([raise_error])

Load the plotters and defaultParams from the plugins

remove(key, func)

update([E, ]**F)

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

update_from_defaultParams([defaultParams, ...])

Update from the a dictionary like the defaultParams

values()

Return values in order of sorted keys.

HEADER = 'Configuration parameters of the psyplot module\n\nYou can copy this file (or parts of it) to another path and save it as\npsyplotrc.yml. The directory should then be stored in the PSYPLOTCONFIGDIR\nenvironment variable.'
catch()[source]

Context manager to reset the rcParams afterwards

Usage:

rcParams['some_key'] = 0
with rcParams.catch():
    rcParams['some_key'] = 1
    assert rcParams['some_key'] == 1
assert rcParams['some_key'] == 0
connect(key, func)[source]

Connect a function to the given formatoption

Parameters:
  • key (str) – The rcParams key

  • func (function) – The function that shall be called when the rcParams key changes. It must accept a single value that is the new value of the key.

copy()[source]

Make sure, the right class is retained

property defaultParams
property descriptions

The description of each keyword in the rcParams dictionary

disconnect(key=None, func=None)[source]

Disconnect the connections to the an rcParams key

Parameters:
  • key (str) – The rcParams key. If None, all keys are used

  • func (function) – The function that is connected. If None, all functions are connected

dump(fname=None, overwrite=True, include_keys=None, exclude_keys=['project.plotters'], include_descriptions=True, **kwargs)[source]

Dump this instance to a yaml file

Parameters:
  • fname (str or None) – file name to write to. If None, the string that would be written to a file is returned

  • overwrite (bool) – If True and fname already exists, it will be overwritten

  • include_keys (None or list of str) – Keys in the dictionary to be included. If None, all keys are included

  • exclude_keys (list of str) – Keys from the RcParams instance to be excluded

  • **kwargs – Any other parameter for the yaml.dump() function

Returns:

if fname is None, the string is returned. Otherwise, None is returned

Return type:

str or None

Raises:

IOError – If fname already exists and overwrite is False

See also

load_from_file

find_all(pattern)[source]

Return the subset of this RcParams dictionary whose keys match, using re.search(), the given pattern.

Parameters:

pattern (str) – pattern as suitable for re.compile

Returns:

RcParams instance with entries that match the given pattern

Return type:

RcParams

Notes

Changes to the returned dictionary are (different from find_and_replace() are not propagated to the parent RcParams dictionary.

See also

find_and_replace

find_and_replace(*args, **kwargs)[source]

Like find_all() but the given strings are replaced

This method returns a dictionary-like object that keeps weak reference to this rcParams instance. The resulting SubDict instance takes the keys from this rcParams instance but leaves away what is found in base_str.

*args and **kwargs are determined by the SubDict class, where the base dictionary is this one.

Parameters:
  • base_str (str or list of str) – Strings that are used as to look for keys to get and set keys in the base dictionary. If a string does not contain '%(key)s', it will be appended at the end. '%(key)s' will be replaced by the specific key for getting and setting an item.

  • pattern (str) – Default: '.+'. This is the pattern that is inserted for %(key)s in a base string to look for matches (using the re module) in the base dictionary. The default pattern matches everything without white spaces.

  • pattern_base (str or list or str) – If None, the whatever is given in the base_str is used. Those strings will be used for generating the final search patterns. You can specify this parameter by yourself to avoid the misinterpretation of patterns. For example for a base_str like 'my.str' it is recommended to additionally provide the pattern_base keyword with 'my\.str'. Like for base_str, the %(key)s is appended if not already in the string.

  • trace (bool) – Default: False. If True, changes in the SubDict are traced back to the base dictionary. You can change this behaviour also afterwards by changing the trace attribute

  • replace (bool) – Default: True. If True, everything but the ‘%(key)s’ part in a base string is replaced (see examples below)

Returns:

SubDict with this rcParams instance as reference.

Return type:

SubDict

Examples

The syntax is the same as for the initialization of the SubDict class:

>>> from psyplot import rcParams
>>> d = rcParams.find_and_replace(['plotter.baseplotter.',
...                                'plotter.vector.'])
>>> print(d['title'])
None

>>> print(d['arrowsize'])
1.0

See also

find_all, SubDict

keys()[source]

Return sorted list of keys.

load_from_file(fname=None)[source]

Update rcParams from user-defined settings

This function updates the instance with what is found in fname

Parameters:

fname (str) – Path to the yaml configuration file. Possible keys of the dictionary are defined by config.rcsetup.defaultParams. If None, the config.rcsetup.psyplot_fname() function is used.

See also

dump_to_file, psyplot_fname

load_plugins(raise_error=False)[source]

Load the plotters and defaultParams from the plugins

This method loads the plotters attribute and defaultParams attribute from the plugins that use the entry point specified by group. Entry points must be objects (or modules) that have a defaultParams and a plotters attribute.

Parameters:

raise_error (bool) – If True, an error is raised when multiple plugins define the same plotter or rcParams key. Otherwise only a warning is raised

msg_depr = '%s is deprecated and replaced with %s; please use the latter.'
msg_depr_ignore = '%s is deprecated and ignored. Use %s'
remove(key, func)[source]
update([E, ]**F) None.  Update D from dict/iterable E and F.[source]

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

update_from_defaultParams(defaultParams=None, plotters=True)[source]

Update from the a dictionary like the defaultParams

Parameters:
  • defaultParams (dict) – The defaultParams like dictionary. If None, the defaultParams attribute will be updated

  • plotters (bool) – If True, 'project.plotters' will be updated too

property validate

Dictionary with validation methods as values

values()[source]

Return values in order of sorted keys.

class psyplot.config.rcsetup.SubDict(base, base_str, pattern='.+', pattern_base=None, trace=False, replace=True)[source]

Bases: UserDict, dict

Class that keeps week reference to the base dictionary

This class is used by the RcParams.find_and_replace() method to provide an easy handable instance that keeps reference to the base rcParams dictionary.

Parameters:
  • base (dict) – base dictionary

  • base_str (str or list of str) – Strings that are used as to look for keys to get and set keys in the base dictionary. If a string does not contain '%(key)s', it will be appended at the end. '%(key)s' will be replaced by the specific key for getting and setting an item.

  • pattern (str) – Default: '.+'. This is the pattern that is inserted for %(key)s in a base string to look for matches (using the re module) in the base dictionary. The default pattern matches everything without white spaces.

  • pattern_base (str or list or str) – If None, the whatever is given in the base_str is used. Those strings will be used for generating the final search patterns. You can specify this parameter by yourself to avoid the misinterpretation of patterns. For example for a base_str like 'my.str' it is recommended to additionally provide the pattern_base keyword with 'my\.str'. Like for base_str, the %(key)s is appended if not already in the string.

  • trace (bool) – Default: False. If True, changes in the SubDict are traced back to the base dictionary. You can change this behaviour also afterwards by changing the trace attribute

  • replace (bool) – Default: True. If True, everything but the ‘%(key)s’ part in a base string is replaced (see examples below)

Notes

  • If a key of matches multiple strings in base_str, the first matching one is used.

  • the SubDict class is (of course) not that efficient as the base dictionary, since we loop multiple times through it’s keys

Examples

Initialization example:

>>> from psyplot import rcParams
>>> d = rcParams.find_and_replace(['plotter.baseplotter.',
...                                'plotter.vector.'])
>>> print d['title']

>>> print d['arrowsize']
1.0

To convert it to a usual dictionary, simply use the data attribute:

>>> d.data
{'title': None, 'arrowsize': 1.0, ...}

Note that changing one keyword of your SubDict will not change the base dictionary, unless you set the trace attribute to True:

>>> d['title'] = 'my title'
>>> print(d['title'])
my title

>>> print(rcParams['plotter.baseplotter.title'])

>>> d.trace = True
>>> d['title'] = 'my second title'
>>> print(d['title'])
my second title
>>> print(rcParams['plotter.baseplotter.title'])
my second title

Furthermore, changing the replace attribute will change how you can access the keys:

>>> d.replace = False

# now setting d['title'] = 'anything' would raise an error (since
# d.trace is set to True and 'title' is not a key in the rcParams
# dictionary. Instead we need
>>> d['plotter.baseplotter.title'] = 'anything'

Methods:

add_base_str(base_str[, pattern, ...])

Add further base string to this instance

iteritems()

Unsorted iterator over items

iterkeys()

Unsorted iterator over keys

itervalues()

Unsorted iterator over values

update(*args, **kwargs)

Update the dictionary

Attributes:

base

dict.

base_str

list of strings.

data

Dictionary representing this SubDict instance

patterns

list of compiled patterns from the base_str attribute, that are used to look for the matching keys in base

replace

bool.

trace

bool.

add_base_str(base_str, pattern='.+', pattern_base=None, append=True)[source]

Add further base string to this instance

Parameters:
  • base_str (str or list of str) – Strings that are used as to look for keys to get and set keys in the base dictionary. If a string does not contain '%(key)s', it will be appended at the end. '%(key)s' will be replaced by the specific key for getting and setting an item.

  • pattern (str) – Default: '.+'. This is the pattern that is inserted for %(key)s in a base string to look for matches (using the re module) in the base dictionary. The default pattern matches everything without white spaces.

  • pattern_base (str or list or str) – If None, the whatever is given in the base_str is used. Those strings will be used for generating the final search patterns. You can specify this parameter by yourself to avoid the misinterpretation of patterns. For example for a base_str like 'my.str' it is recommended to additionally provide the pattern_base keyword with 'my\.str'. Like for base_str, the %(key)s is appended if not already in the string.

  • append (bool) – If True, the given base_str are appended (i.e. it is first looked for them in the base dictionary), otherwise they are put at the beginning

base = {}

dict. Reference dictionary

base_str = []

list of strings. The strings that are used to set and get a specific key from the base dictionary

property data

Dictionary representing this SubDict instance

See also

iteritems

iteritems()[source]

Unsorted iterator over items

iterkeys()[source]

Unsorted iterator over keys

itervalues()[source]

Unsorted iterator over values

patterns = []

list of compiled patterns from the base_str attribute, that are used to look for the matching keys in base

property replace

bool. If True, matching strings in the base_str attribute are replaced with an empty string.

trace = False

bool. If True, changes are traced back to the base dict

update(*args, **kwargs)[source]

Update the dictionary

psyplot.config.rcsetup.defaultParams

dict with default values and validation functions

psyplot.config.rcsetup.get_configdir(name='psyplot', env_key='PSYPLOTCONFIGDIR')[source]

Return the string representing the configuration directory.

The directory is chosen as follows:

  1. If the env_key environment variable is supplied, choose that.

2a. On Linux and osx, choose '$HOME/.config/' + name.

2b. On other platforms, choose '$HOME/.' + name.

  1. If the chosen directory exists, use that as the configuration directory.

  2. A directory: return None.

Parameters:
  • name (str) – The name of the program

  • env_key (str) – The environment variable that can be used for the configuration directory

Notes

This function is motivated by the matplotlib.matplotlib_fname() function

psyplot.config.rcsetup.psyplot_fname(env_key='PSYPLOTRC', fname='psyplotrc.yml', if_exists=True)[source]

Get the location of the config file.

The file location is determined in the following order

  • $PWD/psyplotrc.yml

  • environment variable PSYPLOTRC (pointing to the file location or a directory containing the file psyplotrc.yml)

  • $PSYPLOTCONFIGDIR/psyplot

  • On Linux and osx,

    • $HOME/.config/psyplot/psyplotrc.yml

  • On other platforms,

    • $HOME/.psyplot/psyplotrc.yml if $HOME is defined.

  • Lastly, it looks in $PSYPLOTDATA/psyplotrc.yml for a system-defined copy.

Parameters:
  • env_key (str) – The environment variable that can be used for the configuration directory

  • fname (str) – The name of the configuration file

  • if_exists (bool) – If True, the path is only returned if the file exists

Returns:

None, if no file could be found and if_exists is True, else the path to the psyplot configuration file

Return type:

None or str

Notes

This function is motivated by the matplotlib.matplotlib_fname() function

psyplot.config.rcsetup.rcParams

RcParams instance that stores default formatoptions and configuration settings.

psyplot.config.rcsetup.safe_list(iterable)[source]

Function to create a list

Parameters:

iterable (iterable or anything else) –

Parameter that shall be converted to a list.

  • If string or any non-iterable, it will be put into a list

  • if iterable, it will be converted to a list

Returns:

l put (or converted) into a list

Return type:

list

psyplot.config.rcsetup.validate_bool(b)[source]

Convert b to a boolean or raise

psyplot.config.rcsetup.validate_bool_maybe_none(b)[source]

Convert b to a boolean or raise

psyplot.config.rcsetup.validate_dict(d)[source]

Validate a dictionary

Parameters:

d (dict or str) – If str, it must be a path to a yaml file

Return type:

dict

Raises:

ValueError

psyplot.config.rcsetup.validate_files_exist(files)[source]

Validate if all pathnames in a given list exists

psyplot.config.rcsetup.validate_path_exists(s)[source]

If s is a path, return s, else False

psyplot.config.rcsetup.validate_str(s)[source]

Validate a string

Parameters:

s (str) –

Return type:

str

Raises:

ValueError

psyplot.config.rcsetup.validate_stringlist(s)[source]

Validate a list of strings

Parameters:

val (iterable of strings) –

Returns:

list of str

Return type:

list

Raises:

ValueError

psyplot.config.rcsetup.validate_stringset(*args, **kwargs)[source]

Validate a set of strings

Parameters:

val (iterable of strings) –

Returns:

set of str

Return type:

set

Raises:

ValueError