larq/zookeeper

Let HParams support optional and non-optional parameters

jneeven opened this issue · 1 comments

Problem statement & motivation

Let's say I have a class of parameters for which I want to define the structure, but not the values. For example:

class TestParams(HParams):
    value_1: float
    value_2: Optional[float]

In this case, each instance of TestParams should have some property value_1, and potentially a value_2.

HParams currently don't support this:

p = TestParams(value_2=0.5) # This will not throw any errors
print(p.value_1) # Will throw an AttributeNotFoundError

Suggested solution

We could add decorators that indicate which attributes are required, for example something along the following lines:

class required_attribute():
    def __init__(self, value):
         self.value = value

class TestParams(HParams):
    @required_attribute
    value_1: float
    value_2: Optional[float]

    def __init__(self, **kwargs):
          """TODO: loop over all attributes of this class, and check whether they 
         are of the type RequiredAttribute. If so, check if we received a value and 
         if not, throw an error."""
         pass

    def __iter__(self):
        return (item.value for item in self.__dir__() if self._is_hparam(item))
         

This is no longer valid; zookeeper v1 will actively check that a value was provided for all mandatory component attributes