4

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?

linello
  • 8,451
  • 18
  • 63
  • 109
  • "Isn't importing modules twice a bad practice?" - why do you say that? – user2357112 Mar 03 '14 at 10:54
  • 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 Mar 03 '14 at 10:56
  • 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 Mar 03 '14 at 10:58

1 Answers1

5

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • When writing packages, what is the behaviour of imports when explicitly importing from the base folder `__init.py`? Aren't the other '.py` files sharing the imports in `__init__`? – linello Mar 03 '14 at 11:32
  • 1
    @linello: No. An import loads the module for the whole interpreter, but it only makes the name available for a single file. For example, if `foo.py` does `import bar`, this only assigns the `bar` module to the `bar` variable within module `foo`. Every file that needs to use a module needs to import it separately. – user2357112 Mar 03 '14 at 11:37
  • Thanks for this precious information, it solved some of my perplexities :) – linello Mar 03 '14 at 11:39