9
$\begingroup$

Is it possible to import the contents of another (existing) notebook into the current namespace in the same way that I can with a package?

I know that it would be best to use a .m or .wl file, and I know that they can be created from .nb, but I would like to avoid the hassle of having people doing these and I would like th ability to load directly a .nb.

For example, consider this scenario:

data.nb / data.wl

test = "This is a test";
x = f[2,4];

master.nb

f[a_, b_] := a^b;
Get[NotebookDirectory[]<>"data.nb"];
Print[test];
Print[x];

As that stand, evaluating master.nb results in:

test

x

On the other hand, if I Get the data.wl file instead, I get the desired output:

This is a test

16

There is a solution that uses NotebookEvaluate instead of Get (see this answer) but it requires the context of each notebook to be global and thus will fail for anyone who has set each notebooks' context to be independent of each other.

So how can I load a .nb file in such a way that it behaves like a package file?

$\endgroup$
  • $\begingroup$ You can temporarily change CellContext of the notebook. $\endgroup$ – Kuba Apr 4 '16 at 9:55
  • $\begingroup$ @Kuba Do you mean, open data.nb and modify the CellContext property manually? Or is there a way that this can be done programmatically? $\endgroup$ – JP-Ellis Apr 4 '16 at 10:27
  • $\begingroup$ You can use SetOptions or CurrentValue. $\endgroup$ – Kuba Apr 4 '16 at 10:29
  • $\begingroup$ @Kuba So using Get, I get a Notebook object, but I'm not sure how I can manipulate it and use SetOptions :/ Mathematica's documentation on this is rather limited too. $\endgroup$ – JP-Ellis Apr 4 '16 at 10:36
9
$\begingroup$

You can temporarily change CellContext of the notebook with SetOptions or CurrentValue but if the notebook isn't opened yet, this is faster:

Module[{path, nb}
   ,
   path = (*path*);

   nb = NotebookOpen[ path, CellContext -> "Global`", Visible -> False];

   NotebookEvaluate[nb, InsertResults -> False];

   NotebookClose[nb]
] 

You can use $Context instead of "Global`" for general case.

$\endgroup$
  • $\begingroup$ Awesome, that works perfectly with $Context :) $\endgroup$ – JP-Ellis Apr 4 '16 at 11:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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