From 3f582f6496859312104963cb7f1e6827c97e8c94 Mon Sep 17 00:00:00 2001 From: Alexander Goscinski Date: Fri, 29 Nov 2024 15:04:09 +0100 Subject: [PATCH] Make figure directly accesable through `CodeExercise` If one output is only given that is translated to a `CueFigure` then it can be accessed with `code_exercise.figure` instead of `code_exercise.output.figure` --- src/scwidgets/exercise/_widget_code_exercise.py | 9 +++++++++ tests/test_code.py | 10 ++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/scwidgets/exercise/_widget_code_exercise.py b/src/scwidgets/exercise/_widget_code_exercise.py index 71205d3..6ad918a 100644 --- a/src/scwidgets/exercise/_widget_code_exercise.py +++ b/src/scwidgets/exercise/_widget_code_exercise.py @@ -687,6 +687,15 @@ def output(self) -> CueOutput | None: def outputs(self) -> List[CueOutput]: return self._cue_outputs + @property + def figure(self) -> Figure | None: + return ( + self._cue_outputs[0].figure + if len(self._cue_outputs) > 0 + and isinstance(self._cue_outputs[0], CueFigure) + else None + ) + def _on_click_update_action(self) -> bool: self._output.clear_output(wait=True) raised_error = False diff --git a/tests/test_code.py b/tests/test_code.py index 9be0762..6eedf1a 100644 --- a/tests/test_code.py +++ b/tests/test_code.py @@ -1,9 +1,11 @@ import os from typing import Callable, List, Literal, Union +import matplotlib.pyplot as plt import numpy as np import pytest from ipywidgets import fixed +from matplotlib.figure import Figure from widget_code_input.utils import CodeValidationError from scwidgets.check import Check, CheckRegistry, CheckResult @@ -345,3 +347,11 @@ def failing_update(a, b): code=TestCodeInput.mock_function_0, update_func=failing_update, ) + + def test_figure(self): + """Test figure""" + + code_ex = CodeExercise(outputs=plt.figure()) + assert isinstance(code_ex.figure, Figure) + assert code_ex.output.figure is code_ex.figure + assert code_ex.outputs[0] is code_ex.output