Transformations

It is possible to transform specifications before they are received by the corresponding parameter(s) by declaring transformations on them. A transformation is a function that takes the (possibly already transformed) specification as an input and outputs whatever you like. Transformations can be chained. But let the code speak:

from hanna import Configurable, Integer, String
from pyhocon import ConfigTree

class Movie(Configurable):
    n_words_title = String('title').transform(str.split, len)
    
movie = Movie(ConfigTree(title='Star Wars'))
movie.n_words_title  # 2

movie = Movie(ConfigTree(title='Star Wars: A New Hope'))
movie.n_words_title  # 5

Here we chained two transformations by passing multiple arguments to transform. They are applied in the order of declaration, that is first str.split on the specified value and then len on the previous result.

Syntactic sugar

Here is some syntactic sugar for declaring transformations:

class Movie(Configurable):
    n_words_title = String('title') >> str.split >> len
    n_words_title = String('title') >> (str.split, len)

As we can see from the above example, single calls to transform (or the equivalent >> operator) can be chained since they return the parameter itself.

Last updated