Tuesday, September 9, 2008

Python tips: the right way to show errors

I've lost count of how many times I've seen Python code like this...:

logging.error("Unknown user '%s' for '%s'"
% (username, resourcename))

This error-showing code has two problems:

  1. logging.error and other such functions do the formatting for you -- so don't duplicate their work! So, the first level of fixing is to change the call into:

    logging.error("Unknown user '%s' for '%s'",
    username, resourcename)


  2. any time you're displaying a string that's somehow "in error" (not just in calls to logging functions, but also when instantiating an exception, etc), use %r, not %s! This way, if the problem is that the string contains "invisible" characters, you'll see them clearly displayed as escape sequences, while %s might hide those characters, making debugging much harder. So, the second (and final;-) level of fixing is to further change the call into:

    logging.error("Unknown user %r for %r",
    username, resourcename)

No comments: