scott-griffiths / bitstring

A Python module to help you manage your bits
https://bitstring.readthedocs.io/en/stable/index.html
MIT License
401 stars 67 forks source link

Setting a bit using a numpy int as key no longer works in 4.1.0 #286

Closed m472 closed 11 months ago

m472 commented 11 months ago

I use the following code to create bitflips at random positions:

from bitstring import BitStream
import numpy as np

bs = BitStream([True, False, True, True, True, False, False, False])
flip_pos = np.random.default_rng().integers(low=0, high=len(bs), size=3)

for i in flip_pos:
    bs[i] = not bs[i]

print('success')

With version 4.0.2 of bitstring this used to work just fine. However with version 4.1.0 this no longer works and instead produces the following error message:

Traceback (most recent call last):
  File "bug_report_bitstring.py", line 9, in <module>
    bs[i] = not bs[i]
  File "/home/matz/.conda/envs/ds-core/lib/python3.8/site-packages/bitstring/bitstream.py", line 608, in __setitem__
    super().__setitem__(key, value)
  File "/home/matz/.conda/envs/ds-core/lib/python3.8/site-packages/bitstring/classes.py", line 2847, in __setitem__
    self._setitem_slice(key, value)
  File "/home/matz/.conda/envs/ds-core/lib/python3.8/site-packages/bitstring/classes.py", line 2822, in _setitem_slice
    if key.step not in [None, -1, 1]:
AttributeError: 'numpy.int64' object has no attribute 'step'

If I cast the index on the right hand side of the assignment it works just fine, which I will now use as a workaround:

for i in flip_pos:
    bs[int(i)] = not bs[i]

Used versions: bitstring: 4.0.2 and 4.1.0 numpy: 1.24.0 python: 3.8.16

scott-griffiths commented 11 months ago

Hi. Thanks for the bug report. I've reproduced it and can see what's happened. The fix should be simple but I should write a few tests to make sure it doesn't happen again.

I was planning a bug fix release in a day or two, so a fix should be available soon.

Cheers.

scott-griffiths commented 11 months ago

Version 4.1.1 just released should fix this issue.