PEP 8 exegetics: conditional imports?

Albert Hopkins marduk at letterboxes.org
Fri Aug 7 20:35:52 CEST 2009


On Fri, 2009-08-07 at 16:50 +0000, 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.
> 

I should add that in your example I would probably still put the import
at the top, e.g.:

import gzip
[...]

def foobar(filename):
    if os.path.splitext(filename)[1] == '.gz':
        f = gzip.open(filename)
    else:
        f = open(filename)

Reason being is that if later on I decide I want to write another
function inside my module that does the same thing I don't have to do
the same conditional import.

Even better, if this is something you find yourself doing often you can
create your own "smart" open and put it in a library:

# file anyfile

import __builtin__
import gzip

def open(filename, ...):
    if filename.endswith('.gz'):
        f = gzip.open(filename, ...)
    else:
        f = __builtin__.open(f, ...)

    return f

Then:

>>> import anyfile
>>> f = anyfile.open(filename, ...)

-a





More information about the Python-list mailing list