Python: Optimizing imports

import, python

Solution

This indicates it may make a difference:

"import statements can be executed just about anywhere. It's often useful to place them inside functions to restrict their visibility and/or reduce initial startup time. Although Python's interpreter is optimized to not import the same module multiple times, repeatedly executing an import statement can seriously affect performance in some circumstances."

These two OS questions, local import statements? and import always at top of module? discuss this at length.

Finally, if you are curious about your specific case you could profile/benchmark your two alternatives in your environment.

I prefer to put all of my import statements at the top of the source file, following stylistic conventions and for consistency (also it would make changes easier later w/o having to hunt through the source file looking for import statements scattered throughout)

Problem

Does it matter where modules are loaded in a code? Or should they all be declared at the top, since during load time the external modules will have to be loaded regardless of where they are declared in the code...? Example: ``` from os import popen try: popen('echo hi') doSomethingIllegal; except: import logging #Module called only when needed? logging.exception("Record to logger) ``` or is this optimized by the compiler the same way as: ``` from os import popen import logging #Module will always loaded regardless try: popen('echo hi') doSomethingIllegal; except: logging.exception("Record to logger) ```

Original source

Related problems