TransWikia.com

stop notebook evaluation when Assert fails

Mathematica Asked on January 22, 2021

I would like a notebook evaluation to entirely stop when an Assert fails, without quitting the kernel. Is this possible (e.g., by setting $AssertFunction to … something)?

Edit:

For example, if I create a notebook containing a cell with the following lines, I would like the value of test to still be 0, and for no subsequent cells to be exectuted.

test = 0;
Assert[False];
test = 1;

EDIT:

Note that setting $AssertFunction=Abort[]& does not work, because it only aborts the current computation, but afterwards evaluation continues to proceed through the notebook.

A related question: why must we execute On[Assert] before we can set $AssertFunction? Naturally I understand why we must turn assertions on and off; that is not my question. My question is why On[Assert] apparently resets $AssertFunction:

On[Assert] 
$AssertFunction = Abort[] &;
Assert[False]  (* aborts *)
Off[Assert]
On[Assert]
Assert[False]  (* does not abort *)

3 Answers

It sounds like you want to inspect the stack when an assertion fails. Will Dialog do what you want? As in

$AssertFunction:=Dialog[]

As already mentioned however, cells queued for evaluation, and even subsequent lines in the current cell, will still execute when you Return or ExitDialog. You can ExitDialog[Unevaluated[Abort[]]] to abort a statement, but

test=0;
Assert[False];
test=1;

is three statements.

Answered by Ian on January 22, 2021

On[Assert]
$AssertFunction := (
    (*1*)
   SelectionMove[EvaluationNotebook[], All, Notebook, AutoScroll -> False];
   FrontEndExecute @ FrontEndToken @ "RemoveFromEvaluationQueue";
   SelectionMove[EvaluationCell[], After, Cell, AutoScroll -> False];
    (*2*)
   RunScheduledTask[$Pre =., {1}];
       $Pre = Abort[] &; Abort[];
);
  1. First procedure removes all queued cells from the evaluation queue. And puts a selection after a current evaluating cell.

  2. Since no Token or Abort works, let's improvise to abort pending evaluation in current evaluation cell. Each line(not really a line) is a separate CompoundExpression which needs to be aborted separately so we can $Pre the Abort[] operation. But it would be nice to get rid of that later, that's where ScheduledTask comes in. 1 second is arbitrary but I think enough to abort everything and not to interrupt user actions in future.

enter image description here

Everything from main cell after Assert is aborted and the cell with 4 is skipped from evaluation even though it was selected too.

Answered by Kuba on January 22, 2021

As of Version 11.2 RunScheduledTask has been superseded by SessionSubmit. @Kuba 's cool function stopped working on 11.2 but does work when RunScheduledTask is replaced.

Answered by George Wolfe on January 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP