In this chapter, we will look at a number of more advanced techniques for working with modules and packages. In particular, we will:
import
statement can be used, including optional imports, local imports, and how to tweak the way importing works by changing sys.path
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 = False
You 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 the numpy
library was installed, and if so, use numpy.zeros()
to create a two-dimensional array. Otherwise, we use a list of lists instead. This allows your program to take advantage of the speed of the NumPy library if it was installed, while still working (albeit more slowly) if this library isn't available.
Using optional imports like this is a great way of having your module or package take advantage of other libraries, while still working if they aren't installed. Of course, you should always mention these optional imports in the documentation for your package so that your users will know what will happen if these optional modules or packages are installed.
3.144.9.124