scott-griffiths / bitstring

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

Should pack be available for each type? #278

Open scott-griffiths opened 1 year ago

scott-griffiths commented 1 year ago

It's always been a bit strange that pack creates a BitStream object, when they're probably the least used type.

So instead of

a = bitstring.pack('...')

we can say

a = bitstring.BitStream.pack('...')
b = bitstring.Bits.pack('...')
etc.

and they'll return the expected type. These would be class methods rather than the module method currently in use.

No need to remove the current way though, so can remain backwardly compatible.

That does raise the question of other classmethod constructors. The current way probably isn't the most Pythonic, but there are a lot of constructors. I mean we could implement these:

a = Bits.from_int(14, length=9)
b = BitArray.from_float(0.2, length=32, endianness='little')
c = BitStream.from_bytes(b'123', offset=4, length=15)
etc., etc.

but I don't think that would be helpful at this stage.

scott-griffiths commented 1 year ago

But while I'm thinking about it...

Having constructor methods would allow constructors to skip __init__ (just create via __new__) which could be a real performance improvement in certain situations. It's probably worth at least profiling it.

Minimal new methods needed would be:

from_float(value: float, length: int, bigendian: bool=True)
from_int(value: int, length: int)
from_bytes(value: bytes | bytearray | memoryview)
from_file(value: file_handle)

Do we have a signed flag in from_int or add from_uint? What about bfloat, float8_152, float8_143, se, ue, sie, uie, bool, bin, oct, hex and other bitstrings?

I'm tempted by the from_uint. Not sure about from_bin, from_oct, from_hex. I guess they're used a fair bit and it would be more efficient.

scott-griffiths commented 5 months ago

fromstring has been implemented in 4.2. I quite like frombytes and fromfile as being generic enough, and also only requiring one parameter. I don't think the other from methods are worth it.