Patterns

Some parameter types allow us to specify patterns which will be matched against their specified values. Only values which match the pattern are valid and a ValueError error will be raised for invalid specifications.

The most prominent example is using the String parameter:

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

class Movie(Configurable):
    # Restrict to titles with two words, containing only letters.
    title = String(pattern='([A-Z][a-z]+\s?){2}')
    
movie = Movie(ConfigTree(title='Star Wars'))  # Fine.

# raises ValueError: "title" does not match pattern '^([A-Z][a-z]+\s?){2}$' ('Star Wars: A New Hope')
movie = Movie(ConfigTree(title='Star Wars: A New Hope'))

But also the parameter types Bool, Integer, Number, PhysicalQuantites support patterns. You can access the default pattern of a parameter type via Number.pattern.

class Movie(Configurable):
    year = Integer(pattern='^20[0-1][0-9]$')  # Range in [2000, 2019].

Illegal patterns

Parameters also support illegal patterns, i.e. patterns that must not be matched, and you can also add your own. They can be accessed via Parameter.illegal_patterns for example. Up to now each parameter instance of a specific type shares all illegal patterns with all other instances. For example the Integer type has an illegal pattern that forbids using true divisionarrow-up-right in formulas in order to prevent ambiguities. If you want to extend a specific instance only with its own illegal patterns you need to copy them over manually:

title = String()
title.illegal_patterns = String.illegal_patterns + ['^Star Wars']  # Too much Star Wars.

Turning off pattern matching

We can also disable pattern matching for parameters by setting Integer(pattern=False).

Last updated