Category Archives: Python server refactor

Series where we refactor a deployed Python server script.

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.

Refactoring: Python server script episode 1 – intro

Summary

The first video in the Python Server refactor series where we discuss the project and get started with the preliminary tasks.

Heres what we did:

  • Looked at architecture and other project information
  • Got project into version control, set up Git repository
    • Dealt with line endings issue
    • Deal with trailing whitespace issue (see links)
  • Initial assessment of the code
    • Found global scope code issues
    • Found inconsistent formatting of code
    • Found massive ball-of-mud object with tons of instance variable
    • Found instance variables that really should be constants

Links:

  • https://github.com/bronson/vim-trailing-whitespace

Please do feel free to ask any questions in the comments section!