[Python-Dev] Syntax suggestion for imports
Ron Adam
rrr at ronadam.com
Thu Jan 3 18:48:28 CET 2008
Raymond Hettinger wrote:
> The standard library, my personal code, third-party packages, and my employer's code base are filled with examples of the following pattern:
>
> try:
> import threading
> except ImportError:
> import dummy_threading as threading
>
> try:
> import xml.etree.cElementTree as ET
> except ImportError:
> try:
> import cElementTree as ET
> except ImportError:
> import elementtree.ElementTree as ET
>
> try:
> from cStringIO import StringIO
> except ImportError:
> from StringIO import StringIO
>
> try:
> import readline
> except ImportError:
> pass
>
>
> How about a new, simpler syntax:
>
> * import threading or dummy_threading as threading
>
> * import xml.etree.CElementTree or cElementTree or elementree.ElementTree as ET
>
> * from cStringIO or StringIO import StringIO
>
> * import readline or emptymodule
I don't think it's as visually clear, but that may be I'm just not used to it.
An alternative possibility might be, rather than "or", reuse "else" before
import.
import threading
else import dummy_threading as threading
import xml.etree.CElementTree as ET
else import cElementTree as ET
else import elementtree.ElementTree as ET
The readline example above should be in a try except as it allows a failure
to pass. For example if you wanted to allow the above elementtree example
to pass instead of raising an exception you would write..
try:
import xml.etree.CElementTree as ET
else import cElementTree as ET
else import elementtree.ElementTree as ET
except ImportError:
pass # or handle failed import.
This still improves readability and flattens out the multiple nested
structure which I believe is what makes the current way unappealing.
I think multiple possible imports in "from - import"s statements should not
be allowed. When you consider multiple imports from possibly multiple
sources, it seems like that could get a bit messy when debugging.
Regards,
Ron
More information about the Python-Dev
mailing list