[Python-Dev] bitwise operations for bytes and bytearray
Cameron Simpson
cs at zip.com.au
Thu Jan 7 20:08:20 EST 2016
On 07Jan2016 16:12, Python-Dev <python-dev at python.org> wrote:
>On Jan 7, 2016, at 15:57, Martin Panter <vadmium+py at gmail.com> wrote:
>>> On 7 January 2016 at 22:26, Blake Griffith <blake.a.griffith at gmail.com> wrote:
>>> I'm interested in adding the functionality to do something like:
>>>>>> b'a' ^ b'b'
>>> b'\x03'
>>> Instead of the good ol' TypeError.
>>>
>>> I think both bytes and bytearray should support all the bitwise operations.
>>
>> There is a bug open about adding this kind of functionality:
>> <https://bugs.python.org/issue19251>.
>
>And it's in the needs patch stage, which makes it perfect for the OP: in
>addition to learning how to hack on builtin types, he can also learn the other
>parts of the dev process. (Even if the bug is eventually rejected, as seems
>likely given that it sat around for three years with no compelling use case
>and then Guido added a "very skeptical" comment.)
The use case which springs immediately to my mind is cryptography. To encrypt a
stream symmetrically you can go:
cleartext-bytes ^ cryptographicly-random-bytes-from-cipher
so with this one could write:
def crypted(byteses, crypto_source):
''' Accept an iterable source of bytes objects and a preprimed source of
crypto bytes, yield encrypted versions of the bytes objects.
'''
for bs in byteses:
cbs = crypto_source.next_bytes(len(bs))
yield bs ^ cbs
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Python-Dev
mailing list