Question

I'm writing a .py file which will be regularly imported at the start of some of my IPython sessions in the first cells but will also be imported from other non-interactive sessions, since it contains functions that can be run in batch in non-interactive mode.

It is basically a module containing many classes and functions that are very common.

Since I'm using IPython with the --pylab=inline option, numpy as well as matplotlib functions are already imported, but when run in batch with a simple python mymodule.py the numpy functions have to be imported specifically.

At the end I'd come up with double imports during the IPython session, a thing I don't like very much.

What is the best practice in this case? Isn't importing modules twice a bad practice?

Was it helpful?

Solution

Repeated imports aren't a problem. No matter how many times a module is imported in a program, Python will only run its code once and only make one copy of the module. All imports after the first will merely refer to the already-loaded module object. If you're coming from a C++ background, you can imagine the modules all having implicit include guards.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top