On Jun 28, 2017 6:26 AM, "Nick Coghlan" <ncoghlan@gmail.com> wrote:
On 28 June 2017 at 21:48, Sven R. Kunze <srkunze@mail.de> wrote:
> As it was snipped away, let me ask again:
>
> I don't see how this helps differentiating shallow and nested exceptions
> such as:
>
> try:
>     with exception_guard(ImportError):
>         import myspeciallib
> except RuntimeError: # catches shallow and nested ones
>     import fallbacks.MySpecialLib as myspeciallib

There are two answers to that:

1. In 3.3+ you can just catch ImportError, check "exc.name", and
re-raise if it's not for the module you care about

2. There's a reasonable case to be made that importlib should include
an ImportError -> RuntimeError conversion around the call to
loader.exec_module (in the same spirit as PEP 479). That way, in:

    try:
        import myspeciallib
    except ImportError:
        import fallbacks.MySpecialLib as myspeciallib

any caught ImportError would relate to "myspeciallib", while uncaught
ImportErrors arising from *executing* "myspeciallib" will be converted
to RuntimeError, with the original ImportError as their __cause__.

So it would make sense to file an RFE against 3.7 proposing that
behavioural change (we couldn't reasonably do anything like that with
the old `load_module()` importer API, as raising ImportError was how
that API signalled "I can't load that". We don't have that problem
with `exec_module()`).

What about modules that want to raise ImportError to indicate that they aren't available on the current system, perhaps because some of their dependencies are missing? For example, 'import ssl' should raise an ImportError if 'ssl.py' is present but '_ssl.so' is missing; the existence of '_ssl.so' is an internal implementation detail. And perhaps 'import trio.ssl' should raise ImportError if 'ssl' is missing. (Historically not all systems have openssl available, so this is a common situation where existing libraries contain ImportError guards.)

With PEP 479 there was a different and better way to generate a StopIteration if you wanted one (just 'return'). Here I'm afraid existing projects might actually be relying on the implicit exception leakage in significant numbers :-/

More generally, my impression is that this is one of the reasons why exceptions have fallen out of favor in more recent languages. They're certainly workable, and python's certainly not going to change now, but they do have these awkward aspects that weren't as clear 20 years ago and that now we have to live with.

-n