At the moment, I am producing various complicated interactive plots. They all share a common "code base", with modifications on top of it.

I would like to refactor my code so that the various files call the common "code base". However, the code must be portable - only relative to the current directory.

What is the simplest way to achieve this? Packages seem complicated, and .nb files are preferable to .m files in my current setup. Therefore I have looked into a setup with library.nb followed by Import["library.nb"] in the other files. I couldn't get this to work for some reason, and would appreciate some guidance.

  • 1
    $\begingroup$ The simplest way is to put all your definitions in one one notebook, and use Get on it. Get can read .nb files. But best solution is to make a package of all your common functions. $\endgroup$
    – Nasser
    Jan 30, 2015 at 5:27
  • $\begingroup$ Is there an easy way to use Get with relative pathnames? The code has to be portable. $\endgroup$
    – pre-kidney
    Jan 30, 2015 at 6:02
  • $\begingroup$ NotebookDirectory, ParentDirectory etc. should help. Sounds also like you should consider writing a package. $\endgroup$
    – Yves Klett
    Jan 30, 2015 at 6:30
  • $\begingroup$ What are the benefits of using a package? It seems to increase the complexity of what I want to do. Can I write the package locally, or does it have to go in a location on the $Path? $\endgroup$
    – pre-kidney
    Jan 30, 2015 at 6:36
  • $\begingroup$ package can be anywhere. I have my package in some folder on my D drive. I simply use Get["G:\\blabla\\......\\mypakge.m"] to read it when I want to use some functions in it. $\endgroup$
    – Nasser
    Jan 30, 2015 at 7:13

1 Answer 1


You don't have to write a package if you don't like to. You can just put all your code-base in a *.m file. If your "code-base.m" is then in the same directory as your working notebooks, you can simply call

Get[FileNameJoin[{Directory[], "code-base.m"}]]

inside them.

Some points that are maybe of interest:

You don't need to put your code into a package, because what Get does is it

reads in a file, evaluating each expression in it and returning the last one

This means, it is basically the same than when you go through your notebook and evaluate each cell. Be aware that Get only returns the last expression. While you will have output for each cell in a notebook, you won't have this for your "code-base.m".

Finally, putting everything in a package should still be the goal for stuff you use for a long time or stuff you give to others. With a proper package, you can hide implementation details and only publish functions to the global name-space that should be used.


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.