[Python-ideas] "maybe import"?

Chris Angelico rosuav at gmail.com
Sat Dec 28 17:10:10 CET 2013


On Sun, Dec 29, 2013 at 1:59 AM, spir <denis.spir at gmail.com> wrote:
>> This would also be allowed:
>>
>>      from this or that or another import spam
>
>
> We'd also, or rather, need:
>
>         from this import foo or that import bar or another import baz as
> spam
>
> which starts to be a bit complicated... Maybe (or perhaps) with parens:
>
>         from ((this import foo) or (that import bar) or (another import
> baz)) as spam

Can't say I like that variant - getting complicated and hard to read,
even with parens. If you're importing different names from different
modules, it's going to get very long, and then people are going to
want to split it across lines, and then the obvious question is:
what's been gained over the try/except variant?

There is one thing, though, that I'm seeing of all this. Exception
throwing is asymmetrical: you can attempt a series of statements until
one fails, but there's no convenient syntax to attempt a series of
statements until one succeeds. I wonder, could the more general case
be solved? Is there a way to, without stupid stuff like eval, wrap up
a few statements so they can be executed in a loop:

def import_any(statement_list):
    for try_me in statement_list:
        try:
            # uhh, this is the bit I'm not sure about...
            try_me() # this would work if they're functions instead!
            return
        except ImportError:
            pass
    raise ImportError

This works for a set of functions, but not for a bunch of "from this
import that" statements. Would it be worth mangling the top of your
script until it can be done with importlib or __import__? Doesn't seem
nearly as clean, somehow.

ChrisA


More information about the Python-ideas mailing list