[issue19915] int.bit_at(n) - Accessing a single bit in O(1)

Tim Peters report at bugs.python.org
Mon Dec 9 23:40:19 CET 2013


Tim Peters added the comment:

@HCT, see http://bugs.python.org/issue19915#msg205713 for what's "semantically wrong".  Ints are not arrays - slicing is unnatural.

The point about error checking is that if this were supported via slicing notation, then the _helpful_ exceptions of the form, e.g.,

    TypeError: 'int' object has no attribute '__getitem__'

would no longer occur for code like

    myarray[1:12]

where `myarray` is mistakenly bound to an integer.  We always lose something when assigning a meaning to an operation that formerly raised an exception.

About:

> calling a function is way more expensive than doing
> bit shift and/or AND operation

read the very first message in this issue.  There is no upper bound on how expensive bit shifts and logical operations can be on Python integers:  they can take time proportional to the number of bits.  But a function to extract a bit can be written internally to require small constant time, independent of the number of bits in the integer.  At least that's true for CPython ints >= 0; it may well take longer for negative CPython ints in some cases.

If speed on small ints is your primary concern, by all means continue to fiddle the bits by hand ;-)

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue19915>
_______________________________________


More information about the Python-bugs-list mailing list