import in try/except in examples is pointless and broken?

Issue #12 resolved
Isaac Freeman created an issue

I don't understand this idiom:

    import something
except ImportError:
    import traceback

Why not just do the import and let python print the exception and exit? I can't figure out any use-case where explicitly catching and printing the exception is preferable. In fact, it seems the only effect this has is to break various tools which rely on normal python exception handling, like "python --pdb ..." or ipython's prettified exception printing. I really can't figure out why all the examples use this pattern....

Comments (6)

  1. Steven Johnson

    I suppose this way, it's easier to add in extra information like

    print("Something not installed!")

    And it shows that the API explicitly handles this particular ImportError.

  2. Marcus von Appen repo owner

    On some platforms the ImportError would not produce a proper error code, when the example scripts fail. This idiom was introduced to allow proper error handling (originally taken from pgreloaded, years back...).

    It might not be elegant, when it comes to the typical python way of doing things (fail ungracefully), but it certainly does not break things, since the definition of normal python exception handling does not state not to catch ImportErrors ;-).

    Enough of nitpicking - I'll check the status quo on the different test platforms and see, if it makes sense to remove the code in order to simplify the examples and cause less confusion.

  3. Isaac Freeman reporter

    Fair enough, both replies do make some good points. But there is still the problem of how it changes the expected behavior WRT tools that expect a normal python exception to "flow off the bottom of the stack", such as invoking the debugger at the place the exception was generated, etc.

    Anyways, thanks for looking in to this. I hate to be a nit-picker, but it does kind of agitate my "Right Way spidy-senses". :P Especially since this is in example code that others might develop (potentially) bad habits from.

  4. anatoly techtonik

    "On some platforms the ImportError would not produce a proper error code" - is there a bug on Python tracker? It could have been fixed already.

  5. Log in to comment