2

Consider the following code:

x = 1;

nb = NotebookPut@Notebook[
    {
     Cell[
      BoxData@ToBoxes@Defer@{$Context, x = 2},
      "Input",
      CellContext -> Notebook
      ]
     }
    ];

NotebookEvaluate[nb, InsertResults -> True];

This code first creates Global`x, then it creates a notebook with a cell with CellContext->Notebook. Evaluating the notebook using NotebookEvaluate creates the symbol Notebook$$…`x, everything works as expected.

But now, let's replace the last line with the following:

Block[{$ContextPath = $ContextPath},
 NotebookEvaluate[nb, InsertResults -> True];
 ]

Rerunning the code (including the creation of the notebook), now issues a shadowing warning for x.

Why is this happening? This seems to be a rather strange effect of Block...

Lukas Lang
  • 33,963
  • 1
  • 51
  • 97
  • 1
    Block with $ContextPath causes all sorts of weird shadowing messages where they shouldn't be. I've reported a few cases of this as bugs but my guess is WRI doesn't care about such a minor/cosmetic one when they've got so many other bugs to quash. – b3m2a1 Feb 13 '19 at 22:22
  • NotebookEvaluate does not cope well with CellContext->Notebook: 135025 – Kuba Feb 13 '19 at 22:28
  • Also the interpretation of docs "The cells of the notebook are evaluated in a dialog subsession." can imply that it is strange it didn't happen with the first one. Don't know where a 'dialog subsession' is defined though. – Kuba Feb 13 '19 at 22:30
  • @b3m2a1 Thanks, good to know I'm not going crazy. Are you aware of any other symbols that cause similar problems when used with block? – Lukas Lang Feb 13 '19 at 22:31
  • @LukasLang none that are unexpected. I think Mathematica just has a botched implementation of its $ContextPath stack creation mechanism or like the way it reads that stack or something. – b3m2a1 Feb 13 '19 at 22:32
  • @Kuba Thanks, I'm aware of those problems - but I thought I "fixed" most of them by now (i.e. employed ugly workarounds), until I encountered this one. Unfortunately, I really need NotebookEvalute so I'll have to live with all its quirks...Regarding the dialog subsession: why would you expect the first example to also produce a warning? In terms of documentation, there is a least some information in the doc page of Dialog and the "Dialogs" tutorial, but nothing too specific. – Lukas Lang Feb 13 '19 at 22:48
  • 1
    @LukasLang is CellContext->Notebook in context of NotebookEvaluate working like Begin or BeginPackage? My point was that there are many not really precisely defined actions so who knows what really should happen. But yes, it is clearly unexpected. – Kuba Feb 13 '19 at 22:53

0 Answers0