32
$\begingroup$

Is there a way to have Mathematica at the notebook level (SetOptions[EvaluationNotebook[], CellContext -> Notebook]) only uses a set of declared variables in the notebook context. Any variables that are not declared would throw a warning on use. A front-end indication (font format) and/or a run-time warning.

For example, Visual Basic as the OPTION EXPLICIT command which throws a warning if any variables are used that have not been explicitly declared. When this command is not set you can create variables on the fly as you can in Mathematica.

I am developing a UI for a process that as many user driven event updates. I have a quite a few variables that are holding state of this process and these are all floating about in the notebook context. It is easy to typo one of the variable names and then it is a nightmare to locate it.

Short of wrapping the entire code of the notebook in one giant module where misspelled names would show blue, how do I get some front-end indication or run-time warning that a variable is undeclared?


Update

Using @rcollyer answer below that pointed me to $NewSymbol I have constructed the following two functions, declareContext and removeDeclareContext, that enable an OPTION EXPLICIT type environment when the Global setting for CellContext is Notebook (this can be done in the Option Inspector).

ClearAll[declareContext];
declareContext[context_String] :=
 Module[{},
  $NewSymbol::undeclared = "`1``2` was not previously declared.";

  If[ValueQ[$NewSymbol::declarativeContexts] == False,
   $NewSymbol::declarativeContexts = ""
   ];

  $NewSymbol::declarativeContexts = 
   StringJoin[$NewSymbol::declarativeContexts, "|", context];

  $NewSymbol :=
   If[ContainsAny[StringSplit[$NewSymbol::declarativeContexts, "|"], {#2}] &&
      ContainsNone[Names[#2 <> "*"], {#1}],
     Message[$NewSymbol::undeclared, #2, #1]] &;
  ]

declareContext sets up

  • a new message to display for undeclared variables,
  • a repository of contexts that are participating in the option explicit setting by using a new message, $NewSymbol::declarativeContexts,
  • the $NewSymbol to a function that makes use of both its parameters (variable and context) to check the context repository and existing variables in the context.

ClearAll[removeDeclareContext];
removeDeclareContext[context_String] :=
 $NewSymbol::declarativeContexts = 
  StringDelete[$NewSymbol::declarativeContexts, "|" <> context]

removeDeclareContext simply removes the context from the repository.

Both of the above can be call on multiple notebooks and notebooks that have not called them will continue to operate with just-in-time variables. These can be placed in a .wl package file to make them easier to use across multiple notebooks.

To use

At the start of your notebook declare your variables by evaluating them in a list. Then call declareContext with the Context; this should be the notebook context with either the notebook or global preference CellContext -> Notebook.

{x, y, z};
declareContext@Context[]

You may now assign values to the declared variables but new variables will error.

In:= x = 4
Out= 4

but

w = 1
$NewSymbol::undeclared: Notebook$$15$56114`w was not previously declared. >>

Turn off declarative variables by calling removeDeclareContext@Context[].

Issues

The functions above prevent declaring scoped variables as in Module and DynamicModule. Therefore they are too restrictive.

Module[{w},
 w = 1
]
$NewSymbol::undeclared: Notebook$$15$56114`w was not previously declared. >>

You can work around this by using a sub-context for scoped variables.

Module[{m`w},
 m`w = 1
]
1

Any ideas to loosen up the functions so that you do not need a sub-context for scoped variables are very welcome

$\endgroup$
2
  • $\begingroup$ For the context repository, I'd give you another +1, if I could. Clever workaround. $\endgroup$
    – rcollyer
    Commented Feb 2, 2017 at 21:11
  • 1
    $\begingroup$ For debugging I'd use a palette with dynamically updated table of symbols which have values. $\endgroup$
    – Kuba
    Commented Feb 2, 2017 at 21:44

2 Answers 2

14
$\begingroup$

Edit: method extended for multiple contexts and unlocking mehtod added.


Let's protect whatever is a new symbol.

In old answer I've manually excluded symbols matching name$digits but that wasn't necessary as according to $NewSymbol details:

$NewSymbol is not applied to symbols automatically created by scoping constructs such as Module.

enter image description here

 BeginPackage["Lock`"];

    contextLock; contextUnlock;

 Begin["`Private`"];

   SetAttributes[{contextLock, contextUnlock}, HoldFirst];

   $LockedContexts = <||>;

   contextLock[context_: $Context] := Which[
     $LockedContexts === <||>
     , setLocking[]; $LockedContexts[context] = {}
     , Not@KeyExistsQ[$LockedContexts, context]
     , $LockedContexts[context] = {};
   ];



   contextUnlock[context_: $Context] /; KeyExistsQ[$LockedContexts, context] := (
       ToExpression[#, StandardForm, Unprotect] & /@ $LockedContexts[context]
     ; ToExpression[#, StandardForm, Remove] & /@ $LockedContexts[context]
     ; KeyDropFrom[$LockedContexts, context]
     ; If[$LockedContexts === <||>, $NewSymbol =.];
   )

   setLocking[] := $NewSymbol := If[
     MemberQ[Keys[$LockedContexts], #2]
     , AppendTo[$LockedContexts[#2], #2 <> #1]
     ; ToExpression[#2 <> #1, StandardForm, Protect]
   ] &;

End[];

EndPackage[];
$\endgroup$
13
  • $\begingroup$ Okay. The big drawback of your answer is that only once notebook context can be locked at a time. If I call Lock`contextLock[] on notebook A it removes the lock on notebook B. Will have to update my question update to use the repository. $\endgroup$
    – Edmund
    Commented Feb 3, 2017 at 14:02
  • 1
    $\begingroup$ @Kuba to get around the single context, you could use an Association as a set as the keys are guaranteed to be unique, so you can use MemberQ[Keys@assoc, #2] to test if it is a protected context. $\endgroup$
    – rcollyer
    Commented Feb 4, 2017 at 2:43
  • $\begingroup$ @Edmund updated $\endgroup$
    – Kuba
    Commented Feb 5, 2017 at 19:47
  • $\begingroup$ @rcollyer updated, don't have time to add examples but will do that soon. it is quite selfexplanatory though. $\endgroup$
    – Kuba
    Commented Feb 5, 2017 at 19:48
  • 1
    $\begingroup$ My thoughts are that I would unlock the context to explicitly declare additional variables. If there are unused variable names that are locked then this excludes them from being used. It also seems cleaner not to have the failed symbols lurking around the context once it is unlocked as all symbols should be available when in the unlocked state. $\endgroup$
    – Edmund
    Commented Feb 8, 2017 at 13:56
26
$\begingroup$

You are looking for $NewSymbol which is run every time a new symbol is created. For example, let say you only want x, y, and z as symbols, then declare them initially

In[63]:= {x, y, z}
(*Out[1]= {x, y, z}*)

Then, set $NewSymbol to issue a message when it is used, e.g.

In[2]:= $NewSymbol::undeclared = "`1` was not previously declared.";
In[3]:= $NewSymbol := Message[$NewSymbol::undeclared , #1] &

In[4]:= q
(*
During evaluation of In[4]:= $NewSymbol::undeclared: q was not previously declared.
Out[4]= q*)

But, no message is issued with x.

In[5]:= x = 5
(*Out[5]= 5*)

Additionally, you can create your own cell style that will treat variable declarations as expected using a custom CellEvaluationFunction

CellEvaluationFunction -> (Block[{$NewSymbol}, ToExpression[#]]&)

For instance, you can add it to the "Code" cell, e.g.

Cell[StyleData["Code"], 
 CellEvaluationFunction -> (Block[{$NewSymbol}, ToExpression[#]]&)
]
$\endgroup$
5
  • 3
    $\begingroup$ Very good answer. (+1) Going to let this sit for a bit just in case. $\endgroup$
    – Edmund
    Commented Feb 2, 2017 at 19:09
  • $\begingroup$ @Edmund never a problem. I like seeing what others come up with, too. $\endgroup$
    – rcollyer
    Commented Feb 2, 2017 at 19:10
  • $\begingroup$ Does $NewSymbol affect all context or just the context it is set in? Since I use the Notebook context I can't have $NewSymbol from notebook A affect $NewSymbol from notebook B. $\endgroup$
    – Edmund
    Commented Feb 2, 2017 at 19:11
  • 1
    $\begingroup$ Good point. It takes two arguments, the second being the context. A filter can be added to that to make it more robust ... how to make it understand what notebook B's context is automatically would take some digging, but if declared in the notebook, a simple comparison with Context[] should be sufficient. $\endgroup$
    – rcollyer
    Commented Feb 2, 2017 at 19:14
  • $\begingroup$ @Edmund thanks for the gold badge. :) $\endgroup$
    – rcollyer
    Commented Feb 9, 2017 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.