PEP 8 exegetics: conditional imports?
wuwei23 at gmail.com
Fri Aug 7 19:29:55 CEST 2009
On Aug 8, 2:50 am, kj <no.em... at please.post> wrote:
> Conditional imports make sense to me, as in the following example[...]
> 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.
Really? It doesn't mention conditionals at all, it simply says that
imports should occur before globals and constants, not before
conditions. If you want to put conditions around your imports, then
that's the place to do it.
> 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?
Bear in mind that PEP 8 primarily applies to submissions to the
standard library, in order to provide a standard that aids in
understanding them. If a module is used throughout a body of code,
it's helpful to list these modules at the top of the code, for
clarity. However, if a module is only required under exceptional
conditions, you'll often see it imported at the point which it's
required: as the import occurs near the code, this mitigates the
initial requirement somewhat, and reduces the startup time of the
The style guide also states:
But most importantly: know when to be inconsistent -- sometimes
guide just doesn't apply. When in doubt, use your best judgment.
at other examples and decide what looks best. And don't hesitate
Checks around imports are often used to provide cross-version
compatibility. Embedded imports are often used when the code relying
on them is barely used. These are all very common uses.
pystone is a good example. Nothing within the modular code of pystone
requires sys, it's only imported if the module is executed, primarily
for error reporting & argument handling.
More information about the Python-list