4
votes

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?

1
"Isn't importing modules twice a bad practice?" - why do you say that? - user2357112 supports Monica
Isn't it a memory waste? I come from C++ where importing headers twice leads to nasty compiler errors, so the #pragma's and #ifndef's - linello
No. You can import a module 200 times in a loop or have A import B which imports A, and Python will still only execute each module's code once. (The circular import example can cause some other problems, though.) - user2357112 supports Monica

1 Answers

5
votes

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.