Stop propagating if import wx fails

Boštjan Mejak wrote:

The code is worth a thousand words, so here are my thousand words:

try:
    import wx_ # Intentionally added the trailing underscore to
invoke ImportError
except ImportError:
    print("You don't seem to have wxPython installed.")

class MyFrame(wx.Frame):
    pass

I have a problem that even though the ImportError exception is
properly handled the propagation does not stop there but propagates to
class MyFrame(wx.Frame) and then throws the NameError exception at
me, saying "Name 'wx' is not defined.". It doesn't print the "You
don't seem to have wxPython installed." message at all.

You are misdiagnosing the situation. This is not a case of error
propagation. "Name 'wx' is not defined" is a brand-new and entirely
correct error. If you delete the first four lines completely and do
nothing but:

    class MyFrame(wx.Frame):
        pass

you would get exactly the same error, and for exactly the same reason.

How can I fix my code so that if an ImportError is caught the
propagation to class MyFrame(wx.Frame) does not happen?

If you fail to import wx, how can you possibly hope to drive a class
from wx.Frame?

···

--
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.