Thinking about the Python equivalents of C's
!! double negation
!! 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
- the minimalist version is just
bool(...), because (currently)
Falsecan be directly used in arithmetic expressions.
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
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
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
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.)
Comments on this page:Written on 10 July 2007.