PEP 8 and deferred import
Question: I am working on a large Python program which makes use of a multitude of
modules depending on command-line options, in particular, `numpy`. We have
recently found a need to run this on a small embedded module which precludes
the use of numpy. From our perspective, this is easy enough (just don't use
the problematic command line options.)

However, following [PEP 8](https://www.python.org/dev/peps/pep-0008/), our
`import numpy` is at the beginning of each module that might need it, and the
program will crash due to `numpy` not being installed. The straightforward
solution is to move `import numpy` from the top of the file to the functions
that need it. The question is, "How bad is this"?

(An alternative solution is to wrap `import numpy` in a `try .. except`. Is
this better?)


Answer: Here is a best practice pattern to check if a module is installed and make
code branch depending on it.

    
    
    # GOOD
    import pkg_resources
    
    try:
        pkg_resources.get_distribution('numpy')
    except pkg_resources.DistributionNotFound:
        HAS_NUMPY = False
    else:
        HAS_NUMPY = True
        # You can also import numpy here unless you want to import it inside the function
    

Do this in every module imports having soft dependency to numpy. [More
information in Plone CMS coding
conventions](http://docs.plone.org/develop/plone.api/docs/contribute/conventions.html).

