I have a piece of code that I'd like to turn into a function. I'm aware of modules and saw this post. The problem is that my code is quite long, containing all kinds of functions of the form fun[x_]:=..., numerical integrations, eigensystems and so on, and it seems Module doesn't handle that very well (or perhaps I'm just not using it correctly).

I've also looked here, where it is described how to call a notebook from another notebook. This should work, but I was wondering if there is a way to really treat the notebook as a function with inputs I can pass to, similarly to most all other programming languages.

  • 1
    $\begingroup$ You might see if you could use a technique like this f[x_]:=Module[{}, a[y_]:=Sin[y]; b[z_]:=z^2; b[a[x]] ]; f[2] which wraps Module around all the functions in your notebook and then calls the Module. $\endgroup$
    – Bill
    Commented Aug 4, 2019 at 23:32
  • $\begingroup$ Smth similar is discussed here: community.wolfram.com/groups/-/m/t/1752195, especially see the last post in that thread by Alan Calvitti, but see disadvantages also. $\endgroup$
    – Alx
    Commented Aug 5, 2019 at 1:58

1 Answer 1


You could quite literally do the following, but it is not nice because of all sorts of scoping problems,

myNotebookFunction[var1_, var2_] := Module[{},    (* add this as the first line of your notebook *)
                                                  (* adjust number of vars *)

(* notebook as is goes here *)

result ]  (* add this as last line to close Module. Result is what you want returned *) 

myNotebookFunction[ var1, var2 ] will then be available after doing Get["notebookfile.nb"].

However, its horrible. What you should be doing is turning your notebook into a simple package. To find out how to do that, type the following into a Text cell in any notebook, highlight it with the mouse, then press F1 to get the documentation:


  • 1
    $\begingroup$ You don't even need Module as a wrapper. Just putting all code between parentheses (....) is enough. Be sure though to separate all individual blocks of code with semicolons ;, otherwise you'll accidentally multiply things together. $\endgroup$ Commented Aug 5, 2019 at 7:16

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.