[Python-ideas] "maybe import"?
Steven D'Aprano
steve at pearwood.info
Sat Dec 28 13:27:00 CET 2013
On Fri, Dec 27, 2013 at 12:59:48PM -0800, Andrew Barnert wrote:
> On Dec 27, 2013, at 9:43, Ryan Gonzalez <rymg19 at gmail.com> wrote:
>
> > I like that. I usually end up doing that with ElementTree:
> >
> > try:
> > from xml.etree import cElementTree as etree
>
> Python 3 has already fixed that. You just import ElementTree and you
> get the C-accelerated version.
>
> And the same is true for cPickle, etc.
Not if the C-accelerated version isn't available. Or perhaps there are
two pure-Python modules with the same API, and you're not sure which is
installed. This issue is bigger than just C-accelerators in the CPython
standard library. It applies any time you have two or more alternatives
with the same API, a preferred module and an fallback module. E.g.
readline in the stdlib, versus pyreadline, a third-party Windows port.
A point against this suggestion: the best syntactic sugar opens up new
and successful idioms. List comps and decorators have been great
successes. Being able to embed a list comp as an expression, instead of
a for-loop as a statement, is a great win. This new syntax doesn't open
up new idioms for writing code. It is purely sugar, and as such, it
isn't such a compelling feature.
On the other hand, I think it does simplify a very common use-case. I
often use fallback modules with the same API, and if only this new
syntax had been introduced back in Python 2.4 or 2.5 I would be using it
all the time now. Unfortunately, most (but not all) of my code has to
support 2.4 or 2.5, or at least 3.3, so the usefulness of new syntax is
severely limited *right now*. But if this syntax were introduced into
Python 3.5 (its surely too late for 3.4) I reckon I would be able to use
it around Python 3.6 or 3.7. And of course those who won't need to
support versions of Python prior to 3.5 could use it straight away.
So don't think of this as something you are going to use. Think of this
as an investment for future Python users who are starting with 3.5 and
don't care about backwards compatibility with Python 3.3 and 3.4 (let
alone older versions).
On that basis, I'm going to vote:
+1 on "import preferred or fallback as name".
+0 on allowing "import module or None", to cover the idiom:
try:
import module
except ImportError:
module = None
which may not be encouraged, but it is occasionally useful.
-0 on "from preferred or fallback import name", simply because I'm not
sure how to extend it to multiple names, so I'd rather leave it out.
-1 on Amber's original suggestion "maybe import name", as the
benefit is too little to justify introducing a new keyword.
--
Steven
More information about the Python-ideas
mailing list