More Features

Overriding the callable

In addition to overriding the arguments of a callable (function or class), the configuaration file may also replace the callable itself using the class key. In a YAML file, the value needs to be specified using the !!python/name tag (see the PyYAML documentation for more information):

ham:
  class: !!python/name:spam.Spam

Note that this is potentially unsafe, as it allows the configuration file to execute arbitrary code. To load YAML files safely (which will disable this feature), pass loader=yaml.SafeLoader to from_yaml() or from_yaml_file().

Accessing raw values

The raw content of a configuration object can be obtained by calling its get() method. To access the value of a given key, use _cfg.get('key') (equivalent to _cfg['key'].get()).

Configuration lists

Sometimes we might want to create a list of objects of the same type, with arguments for each item supplied in the configuration file. This can be useful for example when creating a deep neural network with layers of different sizes. In this situation, we can use the configure_list() method, like so:

_cfg['dense_layers'].configure_list(tf.keras.layers.Dense, activation='relu')

The configuration file might then look like this:

dense_layers:
  - units: 100
  - units: 150
  - units: 2
    activation: None

Argument binding

It is sometimes useful to pre-configure a callable without actually calling it, for example if we intend to call it multiple times or want to supply additional arguments later. This can be achieved using the bind() method, e.g.:

Dense = _cfg['dense_layer'].bind(tf.keras.layers.Dense, activation='relu')
dense1 = Dense()  # parameters supplied by configuration
dense2 = Dense(use_bias=False, activation=None)  # overrides configuration

Maybe configure

We have seen that we can omit parts of the configuration file as long as defaults for all the required parameters are defined in the code. However, we might sometimes want to skip creating an object if the corresponding key is omitted from the configuration. This functionality is provided by the maybe_configure() method, which returns None if the configuration value is missing.

There is also maybe_bind(), which works analogously (see Argument binding above).

Required parameters

Instead of providing a default value, it is possbile to explicitly mark a parameter as required:

_cfg['dense_layer'].configure(tf.keras.layers.Dense, activation=_cfg.REQUIRED)

Not providing a value for this parameter in the configuration will result in an exception.