PEP 8 exegetics: conditional imports?

Peter Otten __peter__ at web.de
Fri Aug 7 15:42:16 EDT 2009


kj wrote:

> 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?

If you want to take a rational approach measure speed and memory footprint 
of your program both with the conditional and unconditional imports. Then go 
with the conditional imports only if you can demonstrate a noticeable 
benefit.

This criterion is unlikely to be met for the examples you give above. time 
is a built-in module, and gzip a thin wrapper around zlib which is also 
built-in.

Peter




More information about the Python-list mailing list