kutsurak / python-bitstring

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

Mutation of slices via property setters (a[0:2].uint = 4) ignored. #129

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
The following works as anticipated:

    a = bitstring.BitArray(length=80)
    v = a[0:2]
    v.uint = 1
    a[0:2] = v

However, in the following case, the requested mutation is silently ignored, 
leaving `a` containing its prior contents:

    a = bitstring.BitArray(length=80)
    a[0:2].uint = 1

Which version of bitstring are you using (bitstring.__version__), which version 
of Python (e.g. 2.7, 3.2) and what platform (Linux, Windows, etc.)?

    bitstring 3.0.2
    python 2.7.3
    Linux (x86_64)

Original issue reported on code.google.com by char...@dyfis.net on 11 Oct 2012 at 3:23

GoogleCodeExporter commented 9 years ago
I don't believe this is a bug. When you take a slice of the BitArray you get a 
new BitArray object. In your second example you set the uint property of this 
new BitArray, but the BitArray itself isn't bound to any name and so is lost.

The a[0:2] object is correctly changed by setting its uint property (so no 
error is thrown) but it's just a temporary object.

For comparison, this is similar to your first example, but using the standard 
bytearray:

    >>> a = bytearray(8)
    >>> v = a[0:2]
    >>> v[0] = 1
    >>> a[0:2] = v
    >>> a
    bytearray(b'\x01\x00\x00\x00\x00\x00\x00\x00')

and this is the equivalent of your second example:

    >>> a = bytearray(8)
    >>> a[0:2][0] = 1
    >>> a
    bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')

So the temporary a[0:2] is lost, there's no error and no change to the original.

Original comment by dr.scott...@gmail.com on 11 Oct 2012 at 3:42

GoogleCodeExporter commented 9 years ago
I agree with you as to the mechanism by which this behavior occurs. My 
expectation was that slices would be "views" into the larger, mutable 
bitstring, rather than completely independent objects.

Original comment by char...@dyfis.net on 11 Oct 2012 at 3:49

GoogleCodeExporter commented 9 years ago
The BitArray class tries to mimic the bytearray type where possible (rather 
than for example mimicking numpy). For the const classes (Bits / 
ConstBitStream) the slices *are* views into the larger object, but of course 
they're not mutable for these classes.

Original comment by dr.scott...@gmail.com on 11 Oct 2012 at 3:56