Using context as an overview construct in Mathematica

Reflecting on the solution of the previous previous question about switching between numerical and analytical โ€œmodesโ€ in a large Mathematica project, I thought about the idea of โ€‹โ€‹using Context as a table of contents.

The basic idea is to do all the assignments of numerical values โ€‹โ€‹in their own context, for example

 Begin["Global`Numerical`"] par1 = 1; par2 = 2; ... End[] 

and have all the complex analytic functions, matrices, etc. in a global context.

Ideally, I could work in a global context and switch to all numeric with a simple Begin[Global'Numeric'] and switch using End[] .

Unfortunately, this doen does not work, because, for example, f[par1_,par2_,...] := foo , defined in the global context, will not use par1 , par2 , etc., which were defined in the Global subcontext .

Is there a way to make subcontexts inherit definitions from their parent context? Is there any other way to use contexts to create a simple switchable area?

+4
source share
1 answer

Well, here's one way to get around (what I think) is your problem by properly adjusting $ContextPath :

 SetOptions[EvaluationNotebook[], CellContext -> "GlobalTestCtxt`"]; Remove[f, GlobalTestCtxt`Numerical`f, par1, par2]; f[par1_, par2_] := {par1, par2}; savedContextPath = $ContextPath; Begin["GlobalTestCtxt`Numerical`"]; Print[{$ContextPath, $Context}]; $ContextPath = DeleteCases[$ContextPath, "GlobalTestCtxt`"]; par1 = 1; par2 = 2; End[]; $ContextPath = savedContextPath; 

Now this will be analytically analyzed:

 f[par1, par2] 

And this is numerical:

 savedContextPath = $ContextPath; Begin["GlobalTestCtxt`Numerical`"]; $ContextPath = Prepend[$ContextPath, $Context]; f[par1, par2] End[]; $ContextPath = savedContextPath; 

The reason I say it is fragile is because if you are not careful, it is easy to get a character in the wrong context. For example, suppose you forgot to evaluate f in a global context before evaluating a "numerical" block. Well, now your numeric block will not work simply because it will turn into the (absolutely correct) GlobalTestCtxt`Numerical`f character that you accidentally entered into the character table when you first evaluated the numeric block. Due to possible errors like this, I personally do not use this approach.

Edit: Bug fixed (when making assignments in a numeric context, you must hide the "global" context)

+5
source

Source: https://habr.com/ru/post/1348164/


All Articles