Skip to content

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() ​

python
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]) – if True, 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's display).
  • exclude (Union[None, list, tuple, set]) – ignored (compatibility with IPython's display).
  • metadata (Optional[dict]) – ignored (compatibility with IPython's display).
  • transient (Optional[dict]) – ignored (compatibility with IPython's display).
  • display_id (Union[None, str, bool]) – ignored (compatibility with IPython's display).
  • clear (Optional[bool]) – ignored (compatibility with IPython's display).
  • **kwargs – ignored (compatibility with IPython's display).

download() ​

python
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:

python
>>> download("path/to/file")
>>> download("filename", data)

Parameters:

  • filename (str) – the path of the file to download if data is None, otherwise the name of the downloaded file.
  • data (Optional[Union[str, bytes]]) – the data to download (text is encoded in UTF-8), or None to download the file filename.

clear_output() ​

python
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 – if True, the output is cleared only when new output is displayed, which avoids flickering.

The basthon.autoeval submodule ​

validationclass() ​

python
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 ​

python
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() ​

python
ignore_breakpoint(value: bool = True)

Enable or disable going to the next breakpoint cell of a sequenced notebook after a success.

Parameters:

  • value (bool) – if True, the breakpoint is ignored.

trial_count() ​

python
trial_count() -> int

Number of validation attempts i.e. number of call to __call__().

__call__() ​

python
__call__() -> bool

The default implementation calls succeeded without any check.

equality() ​

python
equality(a: T, b: T, rel_tol: float = 1e-09, abs_tol: float = 0.0) -> bool

Test 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, see math.isclose().
  • abs_tol (float) – used only for float comparison, see math.isclose().

ValidateSequences class ​

python
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 using compute_result()
  • targets (Iterable[T]) – the corresponding target results
  • **kwargs – passed to parent constructor.

equality() ​

python
equality(a: T, b: T, rel_tol: float = 1e-09, abs_tol: float = 0.0) -> bool

Test 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, see math.isclose().
  • abs_tol (float) – used only for float comparison, see math.isclose().

handle_failure() ​

python
handle_failure(value: V, target: T, result: T) -> bool

This 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 error
  • target (T) – the corresponding target
  • result (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() ​

python
handle_exception(exc: Exception, value: V, target: T) -> bool

This 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 exception
  • value (V) – the value that caused the error
  • target (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() ​

python
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() ​

python
handle_success(value: V, target: T, result: T) -> None

This 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 result
  • target (T) – the corresponding target
  • result (T) – the computed result

handle_full_success() ​

python
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() ​

python
precompute() -> Any

Precompute 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() ​

python
handle_precompute_exception(exc: Exception) -> None

Handle an exception occurring during the precompute process.

Parameters:

  • exc (Exception) – the exception raise by the call to precompute.

compute_result() ​

python
compute_result(value: V, precomputed_data: Any) -> T

Computes the result corresponding to value.

Parameters:

  • value (V) – the value used to compute the desired result
  • precomputed_data (Any) – data returned by precompute()

Returns: The result corresponding to value.

__call__() ​

python
__call__() -> bool

Starts the validation process by testing results computed from values against targets.

ValidateVariables class ​

python
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 ​

python
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 tuple
  • target_values (Optional[Iterable[T]]) – the corresponding target values ; they are computed from valid_function if target_values is omitted.
  • valid_function (Optional[Callable[..., T]]) – a function to compute target values if target_values is None.
  • argcount (Optional[int]) – the number of arguments given to the function ; if None, it is guessed from the test values
  • check_signature (Union[bool, inspect.Signature]) – indicate if we have to check the signature in the validation process ; the signature is taken from valid_function or directly passed through check_signature
  • ignore_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 ​

python
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 tuple
  • target_values (Optional[Iterable[T]]) – the corresponding target values ; they are computed from valid_function if target_values is omitted.
  • valid_function (Optional[Callable[..., T]]) – a function to compute target values if target_values is None.
  • argcount (Optional[int]) – the number of arguments given to the function ; if None, it is guessed from the test values
  • check_signature (Union[bool, inspect.Signature]) – indicate if we have to check the signature in the validation process ; the signature is taken from valid_function or directly passed through check_signature
  • ignore_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 ​

python
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 to ValidateBatch (validators, keep_going).
  • **kwargs – passed to ValidateBatch (validators, keep_going, label...).

ValidateAny class ​

python
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 to ValidateBatch (validators, keep_going).
  • **kwargs – passed to ValidateBatch (validators, keep_going, label...).