Chapter 7. Advanced Module Techniques

In this chapter, we will look at a number of more advanced techniques for working with modules and packages. In particular, we will:

  • Examine the more unusual ways in which the import statement can be used, including optional imports, local imports, and how to tweak the way importing works by changing sys.path
  • Briefly examine a number of "gotchas" relating to importing modules and packages
  • Take a look at how you can use the Python interactive interpreter to help develop your modules and packages more quickly
  • Learn how to work with global variables within a module or package
  • See how to configure a package
  • Discover how to include data files as part of your Python package.

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 = 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.

Note

Note that this example is just made up; you probably wouldn't be able to use a list of lists directly instead of a NumPy array and have the rest of your program work without any change. But the concept of doing one thing if a module is present, and something else if it is not, remains the same.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.9.124