On 27Dec2013 01:57, Amber Yust
It's a fairly standard pattern to see things like this:
try: import foo except ImportError: foo = None
(and of course, variants with from...import et cetera). These can potentially add a lot of clutter to the imports section of a file, given that it requires 4 lines to do a conditional import.
It seems like it'd be useful and clean to have a syntax that looked like this:
maybe import foo [...snip...]
The problem here is that the only reason to import as above is to
have access to the name "foo". What is you contingency plan for
the failed import? How does the code cope without "foo".
I'd rather have an ImportError at start than an arbitrarily delayed and
harder to diagnose NameError much later.
Because of this, I'd argue you should almost always want the except:
clause if this is realistic, because you need to have a plan for
the case of failure.
I agree the try/except is wordy and possibly ugly, but I think it
is usually needed when a failed import is not to be fatal.
Cheers,
--
Cameron Simpson