[Tutor] loading modules only when needed and PEP 008

Tim Michelsen timmichelsen at gmx-topmail.de
Wed Mar 19 23:15:41 CET 2008


Hello fellow Pythonistas,
I have a question concerning import statements.

My code uses matplotlib to plot the results of my calculations.

Since I want to make this plotting functionality a optional feature I 
would like to import matplotlib only when needed because 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.

I am still in doubt because PEP 008 [1] states that all imports should 
come right at the beginning of the code.

My current code goes something like:

import sys

import matplotlib

## ....
## do some calcs
## ...
matplotlib.plot(mydata)

a optimized version would be:
import sys

plot_data = 'yes' # option: yes/no

if plot_data == 'yes':
	import matplotlib
else:
	pass

## ....
## do some calcs
## ...
if plot_data == 'yes':
	matplotlib.plot(mydata)
else:
	pass

How would you handle such a case?
What is recommended in such a case?
Does anyone have experience with this?

Thanks for your suggestions in advance!

Kind regards,
Tim



[1] PEP 8 -- Style Guide for Python Code - 
http://www.python.org/dev/peps/pep-0008/



More information about the Tutor mailing list