spine.utils.factory

Contains functions needed to instantiate a class from a dictionary.

This allows to generically convert a YAML block into an instatiated class with all the appropriate checks that the class exists and is provided with appropriate arguments.

Functions

instantiate(module_dict, cfg[, alt_name])

Instantiates a class based on a configuration dictionary and a list of possible classes to chose from.

module_dict(module[, class_name, pattern])

Converts module into a dictionary which maps class names onto classes.

spine.utils.factory.module_dict(module, class_name=None, pattern=None)[source]

Converts module into a dictionary which maps class names onto classes.

Parameters:
  • module (module) – Module from which to fetch the classes

  • class_name (str, optional) – If specified, only allow aliases that match it

  • pattern (str, optional) – If specified, looks for a specific pattern in the class name

Returns:

Dictionary which maps acceptable class names to classes themselves

Return type:

dict

spine.utils.factory.instantiate(module_dict, cfg, alt_name=None, **kwargs)[source]

Instantiates a class based on a configuration dictionary and a list of possible classes to chose from.

This function supports two YAML configuration structures (parsed as a dictionary):

function:
  name: function_name
  kwarg_1: value_1
  kwarg_2: value_2
  ...

or

function:
  name: function_name
  args:
    value_1
    value_2
    ...
  kwargs:
    kwarg_1: value_1
    kwarg_2: value_2
    ...

The name field can have a different name, as long as it is specified.

Parameters:
  • module_dict (dict) – Dictionary which maps a class name onto an object class.

  • cfg (dict) – Configuration dictionary

  • alt_name (str, optional) – Key under which the class name can be specfied, beside ‘name’ itself

  • **kwargs (dict, optional) – Additional parameters to pass to the function

Returns:

Instantiated object

Return type:

object