
On Thu, Dec 26, 2013 at 5:57 PM, Amber Yust <amber.yust@gmail.com> wrote:
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 from bar maybe import baz from qux maybe import quy as quz
Where the behavior would essentially be as above - attempt to run the import normally, and in cases where the import fails, map the name to a value of None instead. Users who want a different behavior are still free to use the long-form syntax. A possibly variant might be to also only run the import if the name isn't already bound, so that you could do something like...
from frobber_a maybe import frob as frobber from frobbler_b maybe import frobble as frobber from frobber_c maybe import frobit as frobber
...to potentially try different fallback options if the first choice for an interface provider isn't available.
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
Such idioms are common. Though I don't think we should encourage their use. That said, if you want to have something like this added it should not use a new keyword ("maybe") but should use what we have. These look odd to me but are possible ideas: import foo else foo = None from foo import bar else bar = None that reuse of else on import statements would also enable the other idiom of importing one of several things to a single name: import foo as x else import bar as x Just tossing those out there. I'm not convinced this is worth adding to the language. -gps