Python basthon module API
This page describes the functions and classes of the basthon Python module, available in Basthon's Python kernel (import basthon): displays and downloads, and notebooks' self-assessment (basthon.autoeval). It is generated from the source code.
Info
This page is in English, as the technical documentation. Other kernels have their own Basthon: OCaml's Basthon module and JavaScript's basthon object are described on the page Autres langages (in French).
The basthon module
display()
display(
*objs: Any,
include: Union[None, list, tuple, set] = None,
exclude: Union[None, list, tuple, set] = None,
metadata: Optional[dict] = None,
transient: Optional[dict] = None,
display_id: Union[None, str, bool] = None,
raw: Optional[bool] = False,
clear: Optional[bool] = False,
**kwargs,
)Display Python objects in the console's graphical output or under the notebook's cell, with their richest representation (HTML, SVG, PNG, LaTeX or Markdown, see the _repr_*_ methods of IPython).
Parameters:
*objs(Any) – the objects to display.raw(Optional[bool]) – ifTrue, the objects are already MIME bundles (dicts mapping MIME types to the content), displayed as they are.include(Union[None, list, tuple, set]) – ignored (compatibility with IPython'sdisplay).exclude(Union[None, list, tuple, set]) – ignored (compatibility with IPython'sdisplay).metadata(Optional[dict]) – ignored (compatibility with IPython'sdisplay).transient(Optional[dict]) – ignored (compatibility with IPython'sdisplay).display_id(Union[None, str, bool]) – ignored (compatibility with IPython'sdisplay).clear(Optional[bool]) – ignored (compatibility with IPython'sdisplay).**kwargs– ignored (compatibility with IPython'sdisplay).
download()
download(filename: str, data: Optional[Union[str, bytes]] = None)Download a file of the virtual filesystem, or data, to the user's computer (the browser saves it as a downloaded file).
Usage:
>>> download("path/to/file")
>>> download("filename", data)Parameters:
filename(str) – the path of the file to download ifdataisNone, otherwise the name of the downloaded file.data(Optional[Union[str, bytes]]) – the data to download (text is encoded in UTF-8), orNoneto download the filefilename.
clear_output()
clear_output(wait=True)Clear the output of the running notebook cell, as IPython's clear_output (useful for animations). The console ignores it.
Parameters:
wait– ifTrue, the output is cleared only when new output is displayed, which avoids flickering.
The basthon.autoeval submodule
validationclass()
validationclass(the_class) -> Type[Validate]Use this decorator on all your validation classes.
It makes it work in the context of a sequenced notebook, implements the trial counter, makes the class derive from Validate if needed, and logs each validation called from the user's code (see basthon.logValidation).
Parameters:
the_class– the validation class.
Returns: the decorated class.
Validate class
class Validate(ignore_breakpoint: bool = False, label: Optional[str] = None)The base class for auto-evaluation.
You should use the @validationclass() decorator to implement your own validation process. It automatically makes your class derives from Validate. Otherwise, you could directly use a dedicated class like ValidateFunction or ValidateVariables.
In the context of a sequenced notebooks, it implements the breakpoint cell validation process in the __call__() method. This method should return True in order to validate a cell and display all the cells until the next breakpoint cell.
It is important to create a new Validate object for each breakpoint code cell. Two breakpoint code cells can't share the same Validate object. Only the objects created (and whose class is defined) in a module file, like the teacher's validation module, unlock the next cells: not those created in the notebook.
The default implementation of __call__() returns True. This is useful for automatic breakpoint validation.
Parameters:
ignore_breakpoint(bool) – if set to True in the context of a sequenced notebook, we do not go to the next breakpoint after a success. Useful to have several tests in the same cell.label(Optional[str]) – an (optional) id to identify the validation.
ignore_breakpoint()
ignore_breakpoint(value: bool = True)Enable or disable going to the next breakpoint cell of a sequenced notebook after a success.
Parameters:
value(bool) – ifTrue, the breakpoint is ignored.
trial_count()
trial_count() -> intNumber of validation attempts i.e. number of call to __call__().
__call__()
__call__() -> boolThe default implementation calls succeeded without any check.
equality()
equality(a: T, b: T, rel_tol: float = 1e-09, abs_tol: float = 0.0) -> boolTest the equality between a and b by carefully looking at the type. Float equality is done by math.isclose() using rel_tol and abs_tol.
Parameters:
a(T) – first value to compare.b(T) – second value to compare.rel_tol(float) – used only for float comparison, seemath.isclose().abs_tol(float) – used only for float comparison, seemath.isclose().
ValidateSequences class
class ValidateSequences(values: Iterable[V], targets: Iterable[T], **kwargs)Bases: Generic[V, T], Validate
Validate the equality between targets and results associated with values. This is the base class for ValidateFunction and ValidateVariables. It is not intended to be used directly but to be derived.
The testing process is launched by calling the object.
Initialise inputs and desired outputs. Raise ValueError if values and targets differ in length.
Parameters:
values(Iterable[V]) – input values used to compute results usingcompute_result()targets(Iterable[T]) – the corresponding target results**kwargs– passed to parent constructor.
equality()
equality(a: T, b: T, rel_tol: float = 1e-09, abs_tol: float = 0.0) -> boolTest the equality by carefully looking at the type. Default implementation uses equality().
Parameters:
a(T) – first value to compare.b(T) – second value to compare.rel_tol(float) – used only for float comparison, seemath.isclose().abs_tol(float) – used only for float comparison, seemath.isclose().
handle_failure()
handle_failure(value: V, target: T, result: T) -> boolThis method is called when the result computed by compute_result() using value is different from the target. It is intended to be overridden.
Parameters:
value(V) – the value that caused the errortarget(T) – the corresponding targetresult(T) – the computed result
Returns: Indicate whether we continue the testing process or not. If the return value is True, the testing process continue, otherwise, it stops.
handle_exception()
handle_exception(exc: Exception, value: V, target: T) -> boolThis method is called when the call of compute_result() on value raises an exception. It is intended to be overridden.
Parameters:
exc(Exception) – the raised exceptionvalue(V) – the value that caused the errortarget(T) – the corresponding target
Returns: Indicate whether we continue the testing process or not. If the return value is True, the testing process continue, otherwise, it stops.
handle_partial_success()
handle_partial_success()This method is called at the end of the testing process, when at least one error occurred (different target and result or exception raised). It is intended to be overridden.
handle_success()
handle_success(value: V, target: T, result: T) -> NoneThis method is called when the result computed by compute_result() using value is equal to the target (wrt. equality()). It is intended to be overridden.
Parameters:
value(V) – the value used to compute the resulttarget(T) – the corresponding targetresult(T) – the computed result
handle_full_success()
handle_full_success()This method is called at the end of the testing process, when all tests succeeded. It is intended to be overridden.
precompute()
precompute() -> AnyPrecompute data before a test session. It is intended to be overridden.
Returns: Any precomputed data that should be passed to compute_result().
handle_precompute_exception()
handle_precompute_exception(exc: Exception) -> NoneHandle an exception occurring during the precompute process.
Parameters:
exc(Exception) – the exception raise by the call toprecompute.
compute_result()
compute_result(value: V, precomputed_data: Any) -> TComputes the result corresponding to value.
Parameters:
value(V) – the value used to compute the desired resultprecomputed_data(Any) – data returned byprecompute()
Returns: The result corresponding to value.
__call__()
__call__() -> boolStarts the validation process by testing results computed from values against targets.
ValidateVariables class
class ValidateVariables(names_and_values: dict[str, Any], **kwargs)Bases: ValidateSequences[str, Any]
A class to validate user defined variables.
To customize this class, have a look at ValidateSequences.
Parameters:
names_and_values(dict[str, Any]) – a dict with variable names as key and desired values as values to test against variables defined in the user namespace (top-level).**kwargs– passed to parent constructor.
ValidateFunction class
class ValidateFunction(
func_name: str,
test_values: Iterable[V],
target_values: Optional[Iterable[T]] = None,
valid_function: Optional[Callable[..., T]] = None,
argcount: Optional[int] = None,
check_signature: Union[bool, inspect.Signature] = False,
ignore_names_in_signature: bool = False,
**kwargs,
)Bases: ValidateSequences[V, T]
A class to validate a function. The tested function may have any number of parameters. To customize this class, have a look at ValidateSequences.
Parameters:
func_name(str) – the name of the function to test in the user namespace (top-level)test_values(Iterable[V]) – values to test the function on ; for function with several parameters, use list or tupletarget_values(Optional[Iterable[T]]) – the corresponding target values ; they are computed fromvalid_functioniftarget_valuesis omitted.valid_function(Optional[Callable[..., T]]) – a function to compute target values iftarget_valuesisNone.argcount(Optional[int]) – the number of arguments given to the function ; ifNone, it is guessed from the test valuescheck_signature(Union[bool, inspect.Signature]) – indicate if we have to check the signature in the validation process ; the signature is taken fromvalid_functionor directly passed throughcheck_signatureignore_names_in_signature(bool) – indicate if we have to worry about wrong parameter name in the function's signature**kwargs– passed to parent constructor.
ValidateFunctionPretty class
class ValidateFunctionPretty(
func_name: str,
test_values: Iterable[V],
target_values: Optional[Iterable[T]] = None,
valid_function: Optional[Callable[..., T]] = None,
argcount: Optional[int] = None,
check_signature: Union[bool, inspect.Signature] = False,
ignore_names_in_signature: bool = False,
**kwargs,
)Bases: ValidateFunction[V, T]
Similar to ValidateFunction but with all test results summarized in a pretty html table.
To customize this class, have a look at ValidateSequences.
Parameters:
func_name(str) – the name of the function to test in the user namespace (top-level)test_values(Iterable[V]) – values to test the function on ; for function with several parameters, use list or tupletarget_values(Optional[Iterable[T]]) – the corresponding target values ; they are computed fromvalid_functioniftarget_valuesis omitted.valid_function(Optional[Callable[..., T]]) – a function to compute target values iftarget_valuesisNone.argcount(Optional[int]) – the number of arguments given to the function ; ifNone, it is guessed from the test valuescheck_signature(Union[bool, inspect.Signature]) – indicate if we have to check the signature in the validation process ; the signature is taken fromvalid_functionor directly passed throughcheck_signatureignore_names_in_signature(bool) – indicate if we have to worry about wrong parameter name in the function's signature**kwargs– passed to parent constructor.
ValidateAll class
class ValidateAll(*args, **kwargs)Bases: ValidateBatch
Validate a list of objects, instances of the Validate class. The global validation succeeds when all validations in the list succeed.
Parameters:
*args– passed toValidateBatch(validators,keep_going).**kwargs– passed toValidateBatch(validators,keep_going,label...).
ValidateAny class
class ValidateAny(*args, **kwargs)Bases: ValidateBatch
Validate a list of objects, instances of the Validate class. The validation succeeded when one validation succeeded.
Parameters:
*args– passed toValidateBatch(validators,keep_going).**kwargs– passed toValidateBatch(validators,keep_going,label...).