caput.config

Configure class attributes using values from a dictionary.

This module to defines strictly typed attributes of a class, that can be loaded from an input dictionary. This is particularly useful for loading a class from a YAML document.

Examples

In this example we set up a class to store information about a person.

>>> class Person(Reader):
...
...     name = Property(default='Bill', proptype=str)
...     age = Property(default=26, proptype=float, key='ageinyears')

We then extend it to store information about a person with a pet. The configuration will be successfully inherited.

>>> class PersonWithPet(Person):
...
...     petname = Property(default='Molly', proptype=str)

Let’s create a couple of objects from these classes.

>>> person1 = Person()
>>> person2 = PersonWithPet()

And a dictionary of replacement parameters.

>>> testdict = { 'name' : 'Richard', 'ageinyears' : 40, 'petname' : 'Sooty'}

First let’s check what the default parameters are:

>>> print(person1.name, person1.age)
Bill 26.0
>>> print(person2.name, person2.age, person2.petname)
Bill 26.0 Molly

Now let’s load the configuration from a dictionary:

>>> person1.read_config(testdict)
>>> person2.read_config(testdict)

Then we’ll print the output to see the updated configuration:

>>> print(person1.name, person1.age)
Richard 40.0
>>> print(person2.name, person2.age, person2.petname)
Richard 40.0 Sooty
exception caput.config.CaputConfigError(message, file_=None, location=None)[source]

Bases: Exception

There was an error in the configuration.

Parameters
  • message (str) – Message / description of error

  • file (str) – Configuration file name (optional)

  • location (dict) – If using SafeLineLoader is used, a dict created by that can be passed in here to report the line number where the error occurred.

class caput.config.Property(default=None, proptype=None, key=None)[source]

Bases: object

Custom property descriptor that can load values from a given dict.

Make a new property type.

Parameters
  • default (object) – The initial value for the property.

  • proptype (function) – The type of the property. In reality this is just a function which gets called whenever we update the value: val = proptype(newval), so it can be used for conversion and validation

  • key (string) – The name of the dictionary key that we can fetch this value from. If None (default), attempt to use the attribute name from the class.

class caput.config.Reader[source]

Bases: object

A class that allows the values of Properties to be assigned from a dictionary.

classmethod from_config(config, *args, **kwargs)[source]

Create a new instance with values loaded from config.

Parameters

config (dict) – Dictionary of configuration values.

read_config(config, compare_keys=False, use_defaults=True)[source]

Set all properties in this class from the supplied config.

Parameters
  • config (dict) – Dictionary of configuration values.

  • compare_keys (bool or list[str]) – If True, a CaputConfigError is raised if there are unused keys in the config dictionary. If a list of strings is given, any unused keys except the ones in the list lead to a CaputConfigError.

  • use_defaults (bool) – If False, a CaputConfigError is raised if a property is not defined by the config dictionary

Raises

CaputConfigError – If there was an error in the config dict.

class caput.config.SafeLineLoader(stream)[source]

Bases: yaml.loader.SafeLoader

YAML loader that tracks line numbers.

Adds the line number information to every YAML block. This is useful for debugging and to describe linting errors.

Initialize the scanner.

caput.config.enum(options, default=None)[source]

A property type that accepts only a set of possible values.

Parameters
  • options (list) – List of allowed options.

  • default (optional) – The optional default value.

Returns

prop – A property instance setup to validate an enum type.

Return type

Property

Raises

ValueError – If the default value is not part of the options.

Examples

Should be used like:

class Project:

    mode = enum(['forward', 'backward'], default='forward')
caput.config.file_format(default=None)[source]

A property type that accepts only “zarr”, or “hdf5”.

Returns the selected caput.fileformat.FileFormat subclass or caput.fileformats.HDF5 if value == default.

Parameters

default (optional) – The optional default value.

Returns

prop – A property instance setup to validate a file format.

Return type

Property

Raises

ValueError – If the default value is not “hdf5” or “zarr”.

Examples

Should be used like:

class Project:

    mode = file_format(default='zarr')
caput.config.float_in_range(start, end, default=None)[source]

A property type that tests if its input is within the given range.

Parameters
  • start (float) – Range to test.

  • end (float) – Range to test.

  • default (float, optional) – The optional default time.

Returns

prop – A property instance setup to validate an input float type.

Return type

Property

Examples

Should be used like:

class Position:

    longitude = config.float_in_range(0.0, 360.0, default=90.0)
caput.config.list_type(type_=None, length=None, maxlength=None, default=None)[source]

A property type that validates lists against required properties.

Parameters
  • type (type, optional) – Type to apply. If None does not attempt to validate elements against type.

  • length (int, optional) – Exact length of the list we expect. If None (default) accept any length.

  • maxlength (int, optional) – Maximum length of the list. If None (default) there is no maximum length.

  • default (optional) – The optional default value.

Returns

prop – A property instance setup to validate the type.

Return type

Property

Raises

ValueError – If the default value fails validation.

Examples

Should be used like:

class Project:

    mode = list_type(int, length=2, default=[3, 4])
caput.config.logging_config(default=None)[source]

A Property type that validates the caput logging config.

Allows the type to be either a string (for backward compatibility) or a dict setting log levels per module.

Parameters

default (optional) – The optional default value.

Returns

prop – A property instance setup to validate the type.

Return type

Property

Examples

Should be used like:

class Project:

    loglevels = logging_config({"root": "INFO", "annoying.module": "WARNING"})
caput.config.utc_time(default=None)[source]

A property for representing UTC as UNIX time.

Parameters
  • time (float, string or datetime) – These are all easy to produce from a YAML file.

  • default (float, string or datetime, optional) – The optional default time.

Returns

prop – A property instance setup to parse UTC time.

Return type

Property