diff --git a/src/scwidgets/code/_widget_code_input.py b/src/scwidgets/code/_widget_code_input.py index 6528be8..aec3b89 100644 --- a/src/scwidgets/code/_widget_code_input.py +++ b/src/scwidgets/code/_widget_code_input.py @@ -5,7 +5,7 @@ import types import warnings from functools import wraps -from typing import Any, List, Optional +from typing import List, Optional from widget_code_input import WidgetCodeInput from widget_code_input.utils import ( @@ -68,12 +68,21 @@ def __init__( @property def function(self) -> types.FunctionType: """ - Returns the unwrapped function object + Return the compiled function object. + + This can be assigned to a variable and then called, for instance:: + + func = widget.wrapped_function # This can raise a SyntaxError + retval = func(parameters) + + :raise SyntaxError: if the function code has syntax errors (or if + the function name is not a valid identifier) """ - return inspect.unwrap(self.get_function_object()) + return inspect.unwrap(self.wrapped_function) - def __call__(self, *args, **kwargs) -> Any: - return self.function(*args, **kwargs) + def __call__(self, *args, **kwargs) -> Check.FunOutParamsT: + """Calls the wrapped function""" + return self.wrapped_function(*args, **kwargs) def compatible_with_signature(self, parameters: List[str]) -> str: """ @@ -95,9 +104,6 @@ def compatible_with_signature(self, parameters: List[str]) -> str: def function_parameters_name(self) -> List[str]: return self.function_parameters.replace(",", "").split(" ") - def run(self, *args, **kwargs) -> Check.FunOutParamsT: - return self.get_function_object()(*args, **kwargs) - @staticmethod def get_code(func: types.FunctionType) -> str: source_lines, _ = inspect.getsourcelines(func) @@ -140,13 +146,15 @@ def get_code(func: types.FunctionType) -> str: return source - def get_function_object(self): + @property + def wrapped_function(self) -> types.FunctionType: """ - Return the compiled function object. + Return the compiled function object wrapped by an try-catch block + raising a `CodeValidationError`. This can be assigned to a variable and then called, for instance:: - func = widget.get_function_object() # This can raise a SyntaxError + func = widget.wrapped_function # This can raise a SyntaxError retval = func(parameters) :raise SyntaxError: if the function code has syntax errors (or if diff --git a/src/scwidgets/exercise/_widget_code_exercise.py b/src/scwidgets/exercise/_widget_code_exercise.py index e1d794d..7d42ea9 100644 --- a/src/scwidgets/exercise/_widget_code_exercise.py +++ b/src/scwidgets/exercise/_widget_code_exercise.py @@ -756,7 +756,7 @@ def run_code(self, *args, **kwargs) -> Check.FunOutParamsT: raise ValueError( "run_code was invoked, but no code was given on initializaion" ) - return self._code.run(*args, **kwargs) + return self._code(*args, **kwargs) except CodeValidationError as e: raise e except Exception as e: