Optional imports
Try opening the Python interactive interpreter and entering the following command:
import nonexistent_module
The interpreter will return the following error message:
ImportError: No module named 'nonexistent_module'
This shouldn't be a surprise to you; you may have even seen this error in your own programs if you made a typo within an import statement.
The interesting thing about this error is that it doesn't just apply where you've made a typo. You can also use this to test if a module or package is available on this particular computer, for example:
try:
import numpy
has_numpy = True
except ImportError:
has_numpy = FalseYou can then use this to have your program take advantage of the module if it is present, or do something else if the module or package isn't available, like this:
if has_numpy:
array = numpy.zeros((num_rows, num_cols), dtype=numpy.int32)
else:
array = []
for row in num_rows:
array.append([])In this example, we check to see if...