Question

The memory cost obviously depends on exactly how large a module is, but I'm only looking for a general answer: Is it generally expensive or cheap to import a module in Python? If I have a few tens of small scripts that potentially stay in memory for the whole duration of the application, how much will that hog the memory?

Was it helpful?

Solution

It sounds like you aren't worried about time cost (good; that would be silly, since modules are only imported once) but memory cost. I put it to you: if you need all the functionality in these modules, then how exactly do you plan to avoid having them all in memory? Might as well just import things in the most logical way.

That said, in Python import is a statement and not some kind of preprocessor directive (or similar), and so you can delay the import of a module until you actually need its contents, by simply arranging for the statement to run at the appropriate time. This can be a meaningful optimization in some particularly large or complex projects, or at least make tricky things possible. Remember, the Python compiler doesn't try to check if there is a foo when you refer to foo.bar; every name is looked up at run-time. Duck-typing comes into play here; the foo.bar code doesn't care whether foo is the name of a module, class or object. (That's basically because modules and classes are objects, but I digress...)

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