[Tutor] loading modules only when needed and PEP 008

Eric Walstad eric at ericwalstad.com
Thu Mar 20 00:06:50 CET 2008

Hi Tim,
Tim Michelsen wrote:
> Hello fellow Pythonistas,
> I have a question concerning import statements.
> it takes a lot 
> of time for a TKinter-GUI to start up. And this start-up time is even 
> longer when matplotlib is imported
> a optimized version would be:
> import sys
> plot_data = 'yes' # option: yes/no
> if plot_data == 'yes':
> 	import matplotlib
> else:
> 	pass
> How would you handle such a case?
> What is recommended in such a case?
> Does anyone have experience with this?
Beware that code later in your module that calls matplotlib.foo() may 
fail if plot_data is not 'yes'.  When I do this sort of thing I like to 
move my imports into my functions/methods.  The 'main' code then 
conditionally calls the function/method.  All the code in the function 
safely assumes that the import has been done but code in the calling 
function assumes the import hasn't been done.

if plot_data:

def show_plot_data(data):
     "load matplotlib and show the user the data"
     import matplotlib
     ...do stuff with matplotlib...

And as we are talking about style, note that your
isn't really necessary but it does make it explicitly clear that you are 
choosing not to do anything if the plot_data isn't 'yes'.  Are those 
tabs you're using?  Four spaces are preferred, according to the style guide.

More information about the Tutor mailing list