On Mon, 20 Feb 2023 at 15:03, Otomatyk dupont <otomatyk@gmail.com> wrote:
>> #import A_WINDOW_MODULE and import A_UNIX_MODULE if except
Here's an attempt to rephrase this slightly, with the following ideas in mind:
* Reduce parser ambiguity
* Support filtering based on specific exception classes
* Rephrase the code to read more closely like natural language
>>> try import A_WINDOW_MODULE but import A_UNIX_MODULE on ImportError
If you really don't want to have the multi-line try...except, this is perfectly possible to implement as a function:
# Put this is an "import_utilities" module if you want
def best_import(*names):
for name in names:
try:
return __import__(name)
except ImportError:
continue
A_MODULE = best_import("A_WINDOW_MODULE", "A_UNIX_MODULE")
>>> try value = int(x[2]) but value = 0 on IndexError, ValueError
This is basically "exception handling expressions", which have been discussed and rejected many times - see
https://peps.python.org/pep-0463/. Personally, I have occasionally wished I could do something like this, but by the time I've thought a bit harder and found a workaround, I usually end up thinking that the workaround is *better* than a solution with an exception handling expression would have been. So although it would be convenient for quick hacks, I basically support the rejection.
In the case of this specific example, you can obviously wrap the calculation and exception handling in a function. For a one-off case, that's not worthwhile, and "toy examples" typically look like one-off cases. But in real code, you'll either be doing this a lot (and so the overhead of a function for it is worthwhile) or it will be part of a function where the exception handling will be encapsulated anyway.
Paul