PEP 8 exegetics: conditional imports?

kj at
Fri Aug 7 18:50:12 CEST 2009

Conditional imports make sense to me, as in the following example:

def foobar(filename):
    if os.path.splitext(filename)[1] == '.gz':
        import gzip
        f =
        f = file(filename)
    # etc.

And yet, quoth PEP 8:

    - Imports are always put at the top of the file, just after any module
      comments and docstrings, and before module globals and constants.

...which seems to condemn conditional imports unequivocally. 

Then again, the PEP 8 scriptures do not explicitly mention conditional
imports at all, as far as I can tell, which leaves open the
possibility that they are still righteous. 

In fact, venerable passages in the Python standard library source
code, if properly interpreted, can be seen to carry out conditional
imports, such as this fragment recovered from

        if a is None:
                a = long(_hexlify(_urandom(16)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256) # use fractional seconds

Or even more clearly, this one from test/

if __name__ == '__main__':
    import sys

I seek the wisdom of the elders.  Is there a consensus on the matter
of conditional imports?  Are they righteous?  Or are they the way
of the wicked?


More information about the Python-list mailing list