Refuse the temptation to pass

This is an opi­nion I so­me­ti­mes re­mem­ber when seeing so­me co­de. Do­n’t take it as a strong ad­vi­ce, or a ru­le, but ins­tead as a ge­ne­ral gui­de­li­ne that mi­ght hel­p ­you to im­pro­ve the co­de sli­gh­tl­y.

On this post I wi­ll sha­re a tiny and opi­nio­nated ar­gu­ment about why the­re are u­sua­lly be­tter things to do in the co­de ins­tead of just pa­ss.

Dis­clai­me­r: I am not sa­ying that pa­ss should be ban­ned from the lan­gua­ge, or ­that is an an­ti-­pa­tter­n, or a bad idio­m. No­thing like tha­t. If that we­re the ­ca­se, it would­n’t be a ke­yword (and we know how few ke­ywor­ds Py­tho­n ha­s, and how hard it is to in­tro­du­ce a new one, so it’s the­re for a good ­rea­so­n).

Ho­we­ve­r, what I do ar­gue, is that so­me of the ni­ce fea­tu­res of Py­thon are often o­ve­r-u­s­e­d, and the temp­ta­tion to abu­se a ni­ce fea­tu­re sha­do­ws be­tte­r o­ppor­tu­ni­tie­s.

For exam­ple, when de­fi­ning ex­cep­tion­s:

class DataValidationError(Exception):
    pass

It’s be­tter to pla­ce a do­cs­tring ex­plai­ning its rai­son d’e­tre, whi­ch e­li­mi­na­tes the ne­ce­s­si­ty for the pa­ss and the emp­ty bod­y:

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

This al­so com­plies wi­th the ge­ne­ral good prac­ti­ce of “u­se do­cs­trings in evee­r­y ­func­tio­n, cla­ss, and mo­du­le de­fi­ne­d”. In my opi­nio­n, it’s a mu­ch be­tte­r ­choi­ce.

The sa­me cri­te­ria applies for emp­ty ba­se cla­s­ses.

How about when dea­ling wi­th ex­cep­tion­s?

So­me­ti­me­s, the oc­cu­rren­ce of an ex­cep­tion is a con­tro­lled sce­na­rio, and agai­n pa­ss looks rea­lly temp­tin­g:

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

He­re the worst part is not even the pa­ss, but the co­m­men­t! Ye­s, co­m­men­ts ­re­pre­sent our fai­lu­re to ex­press our ideas in­to co­de, and they are the­re­fo­re, ­ba­d. We can cheat a li­ttle bit he­re, but (on the bri­ght si­de), do so­me­thin­g ­mo­re use­fu­l: How about lo­gging the me­ss­age?

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

If all of this see­ms un­ne­ce­ssar­y, we can su­ppress the ex­cep­tio­n:

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

The­re are lo­ts of ca­ses like this when using the ke­yword pa­ss see­ms like a ­via­ble op­tio­n. And agai­n, I’m not sa­ying it’s a bad choi­ce. I’m on­ly in­vi­tin­g ­you to thi­nk mo­re about it, and try to find a be­tter al­ter­na­ti­ve.