PEP 8 exegetics: conditional imports?

kj no.email at please.post
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 = gzip.open(filename)
    else:
        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 random.py:

        if a is None:
            try:
                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/pystone.py:

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?

kynn



More information about the Python-list mailing list