Refuse the temptation to pass

This is an opin­ion I some­times re­mem­ber when see­ing some code. Don’t take it as a strong ad­vice, or a rule, but in­stead as a gen­er­al guide­line that might help you to im­prove the code slight­ly.

On this post I will share a tiny and opin­ion­at­ed ar­gu­ment about why there are usu­al­ly bet­ter things to do in the code in­stead of just pass.

Dis­claimer: I am not say­ing that pass should be banned from the lan­guage, or that is an an­ti-­pat­tern, or a bad id­iom. Noth­ing like that. If that were the case, it would­n’t be a key­word (and we know how few key­words Python has, and how hard it is to in­tro­duce a new one, so it’s there for a good rea­son).

How­ev­er, what I do ar­gue, is that some of the nice fea­tures of Python are of­ten over-used, and the temp­ta­tion to abuse a nice fea­ture shad­ows bet­ter op­por­tu­ni­ties.

For ex­am­ple, when defin­ing ex­cep­tion­s:

class DataValidationError(Exception):
    pass

It’s bet­ter to place a doc­string ex­plain­ing its rai­son d’e­tre, which elim­i­nates the ne­ces­si­ty for the pass and the emp­ty body:

class DataValidationError(Exception):
    """A client error (400) when wrong data was provided."""

This al­so com­plies with the gen­er­al good prac­tice of “use doc­strings in eveery func­tion, class, and mod­ule de­fined”. In my opin­ion, it’s a much bet­ter choice.

The same cri­te­ria ap­plies for emp­ty base class­es.

How about when deal­ing with ex­cep­tion­s?

Some­times, the oc­cur­rence of an ex­cep­tion is a con­trolled sce­nar­i­o, and again pass looks re­al­ly tempt­ing:

try:
    custom_parsing(data)
except AttributeError:
    pass  # data is already parsed

Here the worst part is not even the pass, but the com­men­t! Yes, com­ments rep­re­sent our fail­ure to ex­press our ideas in­to code, and they are there­fore, bad. We can cheat a lit­tle bit here, but (on the bright side), do some­thing more use­ful: How about log­ging the mes­sage?

try:
    custom_parsing(data)
except AttributeError:
    logger.debug("data is already parsed")

If all of this seems un­nec­es­sary, we can sup­press the ex­cep­tion:

with contextlib.suppress(AttributeError):
    custom_parsing(data)

There are lots of cas­es like this when us­ing the key­word pass seems like a vi­able op­tion. And again, I’m not say­ing it’s a bad choice. I’m on­ly invit­ing you to think more about it, and try to find a bet­ter al­ter­na­tive.