[Python-ideas] import fallback syntax

Mike Graham mikegraham at gmail.com
Thu Mar 8 19:08:01 CET 2012


On Thu, Mar 8, 2012 at 12:55 PM, Chris Withers <chris at simplistix.co.uk> wrote:
>
> I see a lot of Python like this:
>
> try:
>  from cDecimal import Decimal
> except ImportError:
>  from decimal import Decimal
>
> ...and nest deeper if you're talking about ElementTree.
>
> How about some syntactical sugar to make this less obnoxious:
>
> from cDecimal or decimal import Decimal
>
> from x.y.z import X as X or
>     a.b.z import Y as X or
>
> what do people think?
>
> Chris


It's worthy of note that the `import cFoo as foo` pattern has given
way to implementing foo to try to defer to cFoo on import. The other
situation--a dropin replacement potentially-third-party module--like
the various etree implementations is somewhat less that compelling
since a) these are rare and a few lines to do it doesn't hurt and b)
they're usually lies--a lot of use-lxml-but-fallback-on-xml.etree
import programs out there would fail if lxml wasn't present anyhow.

If something like this is introduced, we should consider an "import
foo or None" kind of case (maybe not written exactly like that) to
replace the conditional-dependency pattern of

    try:
        import foo
    except ImportError:
        foo = None


Mike



More information about the Python-ideas mailing list