I am not yet at the level where I have tools (or know how to develop or use them) for testing and profiling seemingly simple things like my questions so I turn to you.
I have a function that checks a condition and based on that condition picks the best mathematical tool to work with (different modules) but this function is applied on windows of an array and so is looped. Different imports may occur from window to window but this leads me to wonder if the imports are actually being looped and if this is a performance issue at all.
Here is an example from the matplotlib source
def pause(interval):
"""
Pause for *interval* seconds.
If there is an active figure it will be updated and displayed,
and the GUI event loop will run during the pause.
If there is no active figure, or if a non-interactive backend
is in use, this executes time.sleep(interval).
This can be used for crude animation. For more complex
animation, see :mod:`matplotlib.animation`.
This function is experimental; its behavior may be changed
or extended in a future release.
"""
backend = rcParams['backend']
if backend in _interactive_bk:
figManager = _pylab_helpers.Gcf.get_active()
if figManager is not None:
canvas = figManager.canvas
canvas.draw()
show(block=False)
canvas.start_event_loop(interval)
return
# No on-screen figure is active, so sleep() is all we need.
import time
time.sleep(interval)
If I in a loop alternate opening and closing figures will time be imported every other iteration? Or just imported the first time the import is called on and subsequent imports ignored?
Thanks
After an
importcompletes successfully, the imported module is cached insys.modulesand subsequentimportstatements will find the module insys.modulesso the module will not be reimported. You can force a module reimport with thereloadbuiltin function.From the documentation:
PEP 8 (the Python style guide) recommends that imports should be at the top of the file, not within methods. Valid reasons to break this rule (giving a “late import”) are if a module import is expensive and used only rarely in your program (and not at all in a typical execution), or to resolve a circular import dependency (though in that case you should try to resolve the circularity by splitting module functionality better). For a module like
time, that is built in to Python, there’s very little reason to use a late import.