Skip to content

Commit

Permalink
Rename params to parameters (#104)
Browse files Browse the repository at this point in the history
The initial suggestion was to use `params` for the parameter dict and
`parameters` for the parameter panel widget. I found however the usage
of `parameters` for the panel confusing so I would not go with this
suggestion. The abbreviation is therefore not needed anymore.
  • Loading branch information
agoscinski authored Dec 19, 2024
1 parent 76ce8c6 commit 441311a
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 52 deletions.
22 changes: 11 additions & 11 deletions src/scwidgets/code/_widget_parameter_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,18 @@ def dummy_function(**kwargs):
parameters.keys(), self._interactive_widget.kwargs_widgets
)
}
super().__init__(self.panel_params_widget)
super().__init__(self.panel_parameters_widget)

@property
def param_to_widget_map(self) -> dict[str, Widget]:
return self._param_to_widget_map

@property
def panel_params_trait(self) -> List[str]:
return ["value"] * len(self.panel_params)
def panel_parameters_trait(self) -> List[str]:
return ["value"] * len(self.panel_parameters)

@property
def panel_params_widget(self) -> List[Widget]:
def panel_parameters_widget(self) -> List[Widget]:
"""
:return: Only parameters that are tunable in the parameter panel are returned.
Fixed parameters are ignored.
Expand All @@ -71,15 +71,15 @@ def panel_params_widget(self) -> List[Widget]:
]

@property
def params(self) -> Dict[str, Any]:
def parameters(self) -> Dict[str, Any]:
"""
:return: All parameters that were given on initialization are returned,
also including also fixed parameters.
"""
return {key: widget.value for key, widget in self._param_to_widget_map.items()}

@property
def panel_params(self) -> Dict[str, Any]:
def panel_parameters(self) -> Dict[str, Any]:
"""
:return: Only parameters that are tunable in the parameter panel are returned.
Fixed parameters are ignored.
Expand All @@ -90,8 +90,8 @@ def panel_params(self) -> Dict[str, Any]:
if not (isinstance(widget, fixed))
}

def update_params(self, new_params: Dict[str, Any]):
for key, value in new_params.items():
def update_parameters(self, new_parameters: Dict[str, Any]):
for key, value in new_parameters.items():
self.param_to_widget_map[key].value = value

def observe_parameters(
Expand All @@ -101,7 +101,7 @@ def observe_parameters(
notification_type: Union[None, str, Sentinel] = "change",
):
""" """
for widget in self.panel_params_widget:
for widget in self.panel_parameters_widget:
widget.observe(handler, trait_name, notification_type)

def unobserve_parameters(
Expand All @@ -110,10 +110,10 @@ def unobserve_parameters(
trait_name: Union[str, Sentinel, List[str]],
notification_type: Union[None, str, Sentinel] = "change",
):
for widget in self.panel_params_widget:
for widget in self.panel_parameters_widget:
widget.unobserve(handler, trait_name, notification_type)

def set_parameters_widget_attr(self, name: str, value):
for widget in self.panel_params_widget:
for widget in self.panel_parameters_widget:
if hasattr(widget, name):
setattr(widget, name, value)
62 changes: 33 additions & 29 deletions src/scwidgets/exercise/_widget_code_exercise.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class CodeExercise(VBox, CheckableWidget, ExerciseWidget):
:param check_registry:
a check registry that is used to register checks
:param params:
:param parameters:
Input parameters for the :py:class:`ParameterPanel` class or an initialized
:py:class:`ParameterPanel` object. Specifies the arguments in the parameter
panel.
Expand All @@ -66,7 +66,7 @@ def __init__(
check_registry: Optional[CheckRegistry] = None,
exercise_registry: Optional[ExerciseRegistry] = None,
exercise_key: Optional[str] = None,
params: Optional[
parameters: Optional[
Union[Dict[str, Union[Check.FunInParamT, Widget]], ParameterPanel]
] = None,
update_mode: str = "manual",
Expand Down Expand Up @@ -139,15 +139,15 @@ def __init__(
self._exercise_title_html.add_class("exercise-title")

# verify if input argument `parameter` is valid
if params is not None:
if parameters is not None:
allowed_parameter_types = [dict, ParameterPanel]
parameter_type_allowed = False
for allowed_parameter_type in allowed_parameter_types:
if isinstance(params, allowed_parameter_type):
if isinstance(parameters, allowed_parameter_type):
parameter_type_allowed = True
if not (parameter_type_allowed):
raise TypeError(
f"Got parameter {type(params)!r} but only "
f"Got parameter {type(parameters)!r} but only "
f"{allowed_parameter_types} are allowed."
)

Expand All @@ -160,20 +160,20 @@ def __init__(
f"WidgetCodeInput but got {type(code)!r}"
)

# check compability between code and params, can only be checked if
# check compability between code and parameters, can only be checked if
# update_func is not used because we cannot know how the code input is used
if update is None and code is not None and params is not None:
if isinstance(params, dict):
if update is None and code is not None and parameters is not None:
if isinstance(parameters, dict):
compatibility_result = code.compatible_with_signature(
list(params.keys())
list(parameters.keys())
)
elif isinstance(params, ParameterPanel):
elif isinstance(parameters, ParameterPanel):
compatibility_result = code.compatible_with_signature(
list(params.params.keys())
list(parameters.parameters.keys())
)
if compatibility_result != "":
raise ValueError(
"code and params do no match: " + compatibility_result
"code and parameters do no match: " + compatibility_result
)

name = kwargs.get("name", exercise_key)
Expand Down Expand Up @@ -205,10 +205,10 @@ def __init__(
self._cue_outputs.append(CueObject(output))

self._parameter_panel: Union[ParameterPanel, None]
if isinstance(params, dict):
self._parameter_panel = ParameterPanel(**params)
elif isinstance(params, ParameterPanel):
self._parameter_panel = params
if isinstance(parameters, dict):
self._parameter_panel = ParameterPanel(**parameters)
elif isinstance(parameters, ParameterPanel):
self._parameter_panel = parameters
else:
self._parameter_panel = None

Expand Down Expand Up @@ -301,8 +301,8 @@ def __init__(
update_button_disable_during_action = True

self._cue_parameter_panel = UpdateCueBox(
self._parameter_panel.panel_params_widget,
self._parameter_panel.panel_params_trait, # type: ignore
self._parameter_panel.panel_parameters_widget,
self._parameter_panel.panel_parameters_trait, # type: ignore
self._parameter_panel,
)

Expand All @@ -311,25 +311,25 @@ def __init__(
# TODO this has to be made public
cue_output._widgets_to_observe = [
self._code
] + self._parameter_panel.panel_params_widget
] + self._parameter_panel.panel_parameters_widget
# fmt: off
cue_output._traits_to_observe = (

[ # type: ignore[assignment]
"function_body"
]
+ self._parameter_panel.panel_params_trait
+ self._parameter_panel.panel_parameters_trait
)
# fmt: on

cue_output.observe_widgets()
else:
# TODO this has to be made public
cue_output._widgets_to_observe = (
self._parameter_panel.panel_params_widget
self._parameter_panel.panel_parameters_widget
)
cue_output._traits_to_observe = (
self._parameter_panel.panel_params_trait # type: ignore[assignment] # noqa: E501
self._parameter_panel.panel_parameters_trait # type: ignore[assignment] # noqa: E501
)
cue_output.observe_widgets()
elif self._code is not None:
Expand Down Expand Up @@ -397,9 +397,11 @@ def __init__(

if self._parameter_panel is not None:
save_widgets_to_observe.extend(
self._parameter_panel.panel_params_widget
self._parameter_panel.panel_parameters_widget
)
save_traits_to_observe.extend(
self._parameter_panel.panel_parameters_trait
)
save_traits_to_observe.extend(self._parameter_panel.panel_params_trait)

if self._cue_code is not None:
self._cue_code = SaveCueBox(
Expand Down Expand Up @@ -521,7 +523,9 @@ def answer(self) -> dict:
return {
"code": None if self._code is None else self._code.function_body,
"parameter_panel": (
None if self._parameter_panel is None else self._parameter_panel.params
None
if self._parameter_panel is None
else self._parameter_panel.parameters
),
}

Expand All @@ -537,7 +541,7 @@ def answer(self, answer: dict):
if answer["code"] is not None and self._code is not None:
self._code.function_body = answer["code"]
if answer["parameter_panel"] is not None and self._parameter_panel is not None:
self._parameter_panel.update_params(answer["parameter_panel"])
self._parameter_panel.update_parameters(answer["parameter_panel"])

if self._save_cue_box is not None:
self._save_cue_box.observe_widgets()
Expand All @@ -559,12 +563,12 @@ def panel_parameters(self) -> Dict[str, Check.FunInParamT]:
)

@property
def params(self) -> Dict[str, Check.FunInParamT]:
def parameters(self) -> Dict[str, Check.FunInParamT]:
"""
:return: All parameters that were given on initialization are returned,
also including also fixed parameters.
"""
return {} if self._parameter_panel is None else self._parameter_panel.params
return {} if self._parameter_panel is None else self._parameter_panel.parameters

@property
def exercise_title(self) -> Union[str, None]:
Expand Down Expand Up @@ -721,7 +725,7 @@ def _on_click_update_action(self) -> bool:
else:
self._update_func(self) # type: ignore[call-arg]
elif self._code is not None:
self.run_code(**self.params)
self.run_code(**self.parameters)

for cue_output in self.outputs:
if hasattr(cue_output, "draw_display"):
Expand Down
2 changes: 1 addition & 1 deletion tests/notebooks/widget_answers.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def foo(x):

code_ex = CodeExercise(
foo,
params={"x": (0, 2, 1)},
parameters={"x": (0, 2, 1)},
update_mode="manual",
exercise_registry=exercise_registry,
exercise_key="exercise_2",
Expand Down
22 changes: 11 additions & 11 deletions tests/test_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@

class TestParameterPanel:

def test_params(self):
def test_parameters(self):
from ipywidgets import fixed

panel = ParameterPanel(**{"x": (0, 1, 0.5), "y": (2, 3, 1), "z": fixed(5)})
assert panel.params == {"x": 0.0, "y": 2, "z": 5}
assert panel.panel_params == {"x": 0.0, "y": 2}
assert panel.parameters == {"x": 0.0, "y": 2, "z": 5}
assert panel.panel_parameters == {"x": 0.0, "y": 2}


class TestCodeInput:
Expand Down Expand Up @@ -196,24 +196,24 @@ def get_code_exercise(

def update_print():
if code_input is None:
output = code_ex.params
output = code_ex.parameters
else:
output = code_ex.run_code(**code_ex.params)
output = code_ex.run_code(**code_ex.parameters)
code_ex.output.object = f"Output:\n{output}"

else:

def update_print(code_ex: CodeExercise):
if code_input is None:
output = code_ex.params
output = code_ex.parameters
else:
output = code_ex.run_code(**code_ex.params)
output = code_ex.run_code(**code_ex.parameters)
code_ex.output.object = f"Output:\n{output}"

code_ex = CodeExercise(
code=code_input,
check_registry=CheckRegistry() if include_checks is True else None,
params=parameters if include_params is True else None,
parameters=parameters if include_params is True else None,
outputs=[CueObject("Not initialized")],
update=update_print,
update_mode=update_mode,
Expand Down Expand Up @@ -308,7 +308,7 @@ def test_compute_and_set_references(self, code_ex):
],
)
def test_run_code(self, code_ex):
output = code_ex.run_code(**code_ex.params)
output = code_ex.run_code(**code_ex.parameters)
assert np.allclose((output,), code_ex.checks[0].outputs_references[0])

@pytest.mark.parametrize(
Expand All @@ -324,7 +324,7 @@ def test_erroneous_run_code(self, code_ex):
CodeValidationError,
match="name 'bug' is not defined.*",
):
code_ex.run_code(**code_ex.params)
code_ex.run_code(**code_ex.parameters)

@pytest.mark.parametrize(
"function",
Expand All @@ -346,7 +346,7 @@ def print_success(code_ex: CodeExercise | None):

code_ex = CodeExercise(
code=function,
params={"parameter": fixed(5)},
parameters={"parameter": fixed(5)},
exercise_registry=exercise_registry,
exercise_key="test_save_registry_ex",
outputs=[cue_output],
Expand Down

0 comments on commit 441311a

Please sign in to comment.