Skip to content

Commit

Permalink
Detect _param_names from __init__ signature (#867)
Browse files Browse the repository at this point in the history
* Detect _param_names from __init__ signature

Signed-off-by: Fabrice Normandin <fabrice.normandin@gmail.com>

* Remove big NOTE block

Signed-off-by: Fabrice Normandin <fabrice.normandin@gmail.com>
  • Loading branch information
lebrice committed Mar 31, 2022
1 parent 7fbd124 commit 7e49dc3
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/orion/algo/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"""
import copy
import hashlib
import inspect
import logging
from abc import ABCMeta, abstractmethod

Expand Down Expand Up @@ -109,7 +110,16 @@ def __init__(self, space, **kwargs):
kwargs,
)
self._space = space
self._param_names = list(kwargs.keys())
if kwargs:
param_names = list(kwargs)
else:
init_signature = inspect.signature(type(self))
param_names = [
name
for name, param in init_signature.parameters.items()
if name != "space" and param.kind != param.VAR_KEYWORD
]
self._param_names = param_names
# Instantiate tunable parameters of an algorithm
for varname, param in kwargs.items():
setattr(self, varname, param)
Expand Down
35 changes: 35 additions & 0 deletions tests/unittests/algo/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
# -*- coding: utf-8 -*-
"""Example usage and tests for :mod:`orion.algo.base`."""

import pytest

from orion.algo.base import BaseAlgorithm
from orion.algo.space import Integer, Real, Space
from orion.core.utils import backward, format_trials

Expand Down Expand Up @@ -108,3 +111,35 @@ def test_is_done_max_trials(monkeypatch, dumbalgo):

dumbalgo.max_trials = 4
assert algo.is_done


@pytest.mark.parametrize("pass_to_super", [True, False])
def test_arg_names(pass_to_super: bool):
"""Test that the `_arg_names` can be determined programmatically when the args aren't passed to
`super().__init__(space, **kwargs)`.
Also checks that the auto-generated configuration dict acts the same way.
"""

class SomeAlgo(BaseAlgorithm):
def __init__(self, space, foo: int = 123, bar: str = "heyo"):
if pass_to_super:
super().__init__(space, foo=foo, bar=bar)
else:
super().__init__(space)
self.foo = foo
self.bar = bar
# Param names should be correct, either way.
assert self._param_names == ["foo", "bar"]
# Attributes should be set correctly either way:
assert self.foo == foo
assert self.bar == bar

space = Space(x=Real("yolo1", "uniform", 1, 4))
algo = SomeAlgo(space, foo=111, bar="barry")
assert algo.configuration == {
"somealgo": {
"bar": "barry",
"foo": 111,
}
}

0 comments on commit 7e49dc3

Please sign in to comment.