Wandering Thoughts archives

2007-07-10

Thinking about the Python equivalents of C's !! double negation

C's !! double negation idiom is a way of compressing all non-zero values of an expression down into a 1. There's a number of things that you can use to get the same effect in Python:

  • if you know that your result is always zero or positive, you can use cmp(). I'm ambivalent about whether this is obscure usage; you're at least making it clear what you're doing, although probably not why.

    (If your result can be negative, you can use abs(cmp(...)).)

  • the minimalist version is just bool(...), because (currently) True and False can be directly used in arithmetic expressions.
  • writing int(bool(...)) has the same effect but makes it clear to readers (and programs like pylint and pychecker) that you're doing this deliberately.

I'm not sure which one I like better. Consider an expression like:

nbytes = nbits // 8 + int(bool(nbits % 8))

My C heritage says that this version is the clearest (and indeed it's the first one I thought of). I'd have to pause to think about the cmp() version, partly because I've yet to memorize which way cmp()'s arguments run so I always have to think about what its result will be.

I suspect that none of these would be considered good Python style, and that the proper Pythonic way to do this is to just use an if, or to write the whole thing as math.ceil(nbits / 8.0) and trust that floating point precision is not going to bite you.

(For some reason I have a small addiction to little overly clever Python idioms like this.)

python/DoubleNegationEquivalent written at 21:30:48; Add Comment


Page tools: See As Normal.
Search:
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.