scott-griffiths / bitstring

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

4.2.0: Typing of BitStream-slice #320

Closed prauscher closed 7 months ago

prauscher commented 7 months ago

Hello,

First of all thank you for this library, which makes it a real breeze to work with nifty Bit-oriented protocols. Sadly we encoutered a problem related to static typing with the latest 4.2.0 release:

Prior to 4.2.0 (specifically 4.1.4 which we were using) slicing a BitStream resulted in a new BitStream (typing-wise):

from bitstring import BitStream
a = BitStream('0xbeef')
print(a.uint)  # 48879
print(a[2:4].uint)  # 3

probably due with commit d9beb0d3 slicing got a new method, which always returns Union[TBits, bool]. Static typing therefore yields to errors like Item "bool" of "Any | bool" has no attribute "uint". Probably a typing-overloads such as

@overload
def __getitem__(self: TBits, key: slice, /) -> TBits:
    ...

@overload
def __getitem__(self: TBits, key: int, /) -> bool:
    ...

could help already? Happy to help with a PR if you like.

prauscher commented 7 months ago

Just to confirm: Prior to d9beb0d the inherited Bits.__getitem__ was used, which has such overloads specified: https://github.com/scott-griffiths/bitstring/blob/main/bitstring/bits.py#L223

scott-griffiths commented 7 months ago

Hi. Thanks for bug report and the kind words. I don't think I can reproduce the issue you're having but different tools have different requirements for static typing and the library does do some stuff that annoys a few of them!

But you're definitely right that the overloads should have been added as they have been elsewhere. I'll make the change for the 4.2.1 release which will hopefully fix the issue for you.

Thanks.

scott-griffiths commented 7 months ago

I've made the suggested additional overloads in the 4.2.1 release, so hopefully that will help.