Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it problematic to repeat the same import in multiple modules?

I am writing modules right now and several of these import numpy. For example, the simplest kind of module just creates a namespace:

import numpy as np
pi=np.pi

Here, I have to import numpy – but I also have to import numpy for my main program and other modules to actually use numpy directly. Is this problematic, for example does it occupy additional memory?

My assumption is that no space is left occupied, because even though I import numpy in my main program, it complains if I don't do so in the module. So I guess the import of numpy is "unloaded" (not sure if correct vocabulary) as soon as my main program has finished importing my own module.

like image 206
Leviathan Avatar asked Oct 19 '25 07:10

Leviathan


2 Answers

Python has separate concepts of importing and loading a module:

  • loading actually creates an in-memory representation of the module. This may run arbitrary code, create arbitrary objects, and produces a module object.
  • importing only binds a module in the current namespace. The module is fetched from an interpreter-global storage, which may load the module if it is not present.

Practically speaking, this means that Python will load numpy only the first time import numpy executes. Afterwards, numpy is fetched from an internal storage.1 The memory is not duplicated for repeated imports.

The binding done by import is like a regular name-binding, i.e. import numpy as np behaves like np = __magic_import_function__("numpy"). When done at the top-level of a module, the name will persist for as long as the module lives – usually as long as the program. Repeated imports consume no more memory than simple name bindings.


1 It is possible to access and modify this internal storage as well as the import machinery. This makes it technically possible that modules are re-loaded on import. This is highly unusual and can be ignored for practical purposes unless a module explicitly uses this mechanism.

like image 198
MisterMiyagi Avatar answered Oct 21 '25 22:10

MisterMiyagi


When you import a module in Python, first it checks if there are more equal import statements on the code. If so, it doesn't reimport all the module content again, because it could take a lot of memory and time, it just gets a reference to the already created object with all the constants, functions, and objects of the module, in this case numpy.

Also, if you want more details about how Python imports modules, you can take a look at the official documentation.

like image 26
Cardstdani Avatar answered Oct 21 '25 23:10

Cardstdani