Refactoring: Python server script episode 2 – environment setup

Refactoring: Python server script episode 2 – environment setup

Summary

Here’s a quick summary of what happened in the video:

  • Set up a virtual environment for packages
    • Updated PIP pip install --upgrade pip
    • Installed packages then stored those packages in requirements.txt
  • Ran into hard-coded platform specific paths that stopped script from running
  • Dealt with exceptions that caught everything

Try with no except:

In this episode we ran into some code that had some exception handling anti-patterns. In particular when you have a  try with no  except you actually have a catch-all.

try:
    #some code here

Is equivalent to:

try:
    #some code here
except:
    pass

Which is in turn equivalent to:

try:
    #some code here
except Exception:
    pass
except SystemExit:
    pass
except KeyboardInterrupt:
    pass
except GeneratorExit:
    pass

Essentially this will eat up all exceptions, including some exceptions you don’t want to catch like SystemExit, something you very rarely want to do. The python2 howto had an entire section devoted to why this is a bad idea: https://docs.python.org/2/howto/doanddont.html#except

Catching the base Exception while bad would have been much better.

try:
    #some code here
except Exception:
    pass

But really you want to be as specific as possible, explicitly catch only what you need and no more. If you need to handle an IO exception handle it explicitly via IOerror, if you have a socket error use the specific error class. If you aren’t specific then you will catch things you didn’t want to catch which is a massive liability as it hides all manner of serious bugs.

As far as I know the only time I will use a  try with no  except is to do some sort of cleanup via  finally :

try:
    #some code here
finally:
    #cleanup code here always runs

This is useful in a situation where you absolutely must handle cleanup for something.

Leave a Reply

Your email address will not be published. Required fields are marked *