When exactly does Python import?

Question

If I have instructions import

nested within a block if/else

, do I increase efficiency? I know some languages ​​do "one pass" over the code for import

and syntax problems. I just don't know how deeply Python is in this.

My hypothesis

Because Python is interpreted and not compiled, the nested statements import

in the else block, these libraries will not be imported until that line is reached, thus conserving system resources unless otherwise required.

Scenario

I wrote a script that will be used by both the more literate computer and the less. My department is very comfortable with running scripts from the command line with arguments, so I set it up to use the arguments for what it needs, and if it doesn't find the arguments it was expecting, it launches the GUI with titles, buttons, and more verbose instructions. However, this means I am importing libraries that are only used if no arguments were provided.

Additional Information

  • The GUI is very, very simple (half a dozen text fields and maybe fewer buttons), so I'm not interested in just creating and creating a custom GUI class into which the required libraries will be imported. If it gets more complicated I will consider it in the future or even click to go to the web interface.
  • My script completely works as I expected. The only question is with regard to resource consumption.
+3


source to share


1 answer


Operators

import

are executed as they would in normal execution, so if the condition prevents that line from being executed, no import occurs and you avoid unnecessary work.

However, if the module will be imported in some other way (say, of course, imported module B depends on A, and you import A conditionally), the savings are trivial; after the first import of a module, subsequent imports simply get a new link to the same cached module; the import technique has to do some tricky things to handle import hooks and the like, but in general it's still pretty cheap (sub-microsecond when importing an already cached module).



The only way to save you from anything is if this module is not imported in any way, in which case you will avoid the work of loading it and the memory used by the loaded module.

+5


source







All Articles