# Import another Notebook as if it were a Package

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?

• You can temporarily change CellContext of the notebook. – Kuba Apr 4 '16 at 9:55
• @Kuba Do you mean, open data.nb and modify the CellContext property manually? Or is there a way that this can be done programmatically? – JP-Ellis Apr 4 '16 at 10:27
• You can use SetOptions or CurrentValue. – Kuba Apr 4 '16 at 10:29
• @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. – JP-Ellis Apr 4 '16 at 10:36

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. • Awesome, that works perfectly with $Context :) – JP-Ellis Apr 4 '16 at 11:13