kutsurak / python-bitstring

Automatically exported from code.google.com/p/python-bitstring
0 stars 0 forks source link

Add __contains__ to BitArray #137

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Bit Array should act like an Array and allow for the use of `in` and `not in` 
with the class.  To do this we need to add a `__contains__` method.

I don't have SVN handy, but here is a __contains__ method that works:

def __contains__(self, val):
        try:
            return self[val]
        except IndexError:
            return False

Original issue reported on code.google.com by Andrew.W...@gmail.com on 14 Jun 2013 at 6:17

GoogleCodeExporter commented 9 years ago
__contains__ has been supported for some time - can you provide an example of 
it not working?

Documentation here: 
http://pythonhosted.org/bitstring/constbitarray.html?highlight=contains#bitstrin
g.Bits.__contains__

Original comment by dr.scott...@gmail.com on 14 Jun 2013 at 7:20

GoogleCodeExporter commented 9 years ago
After some investigation, it looks like it is in place, but can return errors:

import base64
from bitstring import BitArray

base64string = "xQ=="
b = base64.b64decode(base64string) 
bin(ord(b))    # => 0b11000101

bit_array = BitArray(bytes=b)

7 in bit_array # False

bit_array[7] # True

Original comment by Andrew.W...@gmail.com on 14 Jun 2013 at 8:21

GoogleCodeExporter commented 9 years ago
bit_array[7] just tells you the value of bit 7 (it only depends on the value of 
a single bit in the bitstring)

7 in bit_array constructs a new BitArray from the initialiser 7 and checks if 
it is contained in the bitstring. Now BitArray(7) is a bitstring of seven zero 
bits, so it is checking to see if '0000000' is somewhere in bit_array, which it 
isn't.

You could say '0b111' in bit_array to look for the binary representation of 7 
within the bit_array, but that would also return False.

Your suggested implementation of __contains__ suggests you've misunderstood it. 
It is actually a form of the find() method, whereas what you have is just the 
same as indexing a bit (which returns True or False) except that if it's out of 
range you return False rather and throwing an exception, which doesn't seem 
very useful.

Original comment by dr.scott...@gmail.com on 14 Jun 2013 at 8:36

GoogleCodeExporter commented 9 years ago
Fair enough.  I was thinking of it how `in` works with Arrays instead of how 
`in` works with Strings.

Original comment by Andrew.W...@gmail.com on 14 Jun 2013 at 8:45