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.
Python has separate concepts of importing and loading a module:
module
object.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 import
s.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With