Getting started

This package focuses on the declaration part of the configuration and it relies on pyhocon for the specification part. It interconnects these two aspects and relieves you, as the developer, from that task. All you have to do is to declare your configuration.

Suppose you're developing a tool for managing your list of all time favorite movies. You start by introducing a separate class representing each of the movies:

from pyhocon import ConfigTree

class Movie:
    def __init__(self, config: ConfigTree):
        self.title = config['title']
        self.year = config['year']
        
star_wars = Movie(ConfigTree(title='Star Wars', year=1977))

The relevant work for loading the parameters is performed in Movie.__init__. While the amount of work is manageable here, we're not very explicit about what kind of information we expect and also the user, given they have only access to our Movie class, have no information about the required parameters.

Now let's use hanna for declaring the parameters:

from hanna import Configurable, Integer, String

class Movie(Configurable):
    title = String()
    year = Integer()
        
star_wars = Movie(ConfigTree(title='Star Wars', year=1977))
print(star_wars.title)  # Prints "Star Wars".
print(star_wars.year)   # Prints "1977".

What we did here is making our Movie class inherit from Configurable and then specify the required parameters as fields on the class. This has already the following advantages:

  • No need to duplicate the name of the parameter as field name and configuration path (the parameter name matches the field name).

  • Being explicit about the parameter types.

  • Users can inspect the Movie class and obtain information about required parameters.

We also have the option to manually specify names for the parameters such as:

class Movie(Configurable):
    title = String('release_title')
    year = String('release_year')
    
star_wars = Movie(ConfigTree(release_title='Star Wars', release_year=1977))
print(star_wars.title)  # Prints "Star Wars".
print(star_wars.year)   # Prints "1977".

This allows users to customize classes to match their configuration sources without modifying the actually functionality of that class:

Movie.title.name = 'the_title'

star_wars = Movie(ConfigTree(the_title='Star Wars', release_year=1977))

Last updated