Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use cases for bytearray

Tags:

python

arrays

Can you point out a scenario in which Python's bytearray is useful? Is it simply a non-unicode string that supports list methods which can be easily achieved anyway with str objects?

I understand some think of it as "the mutable string". However, when would I need such a thing? And: unlike strings or lists, I am strictly limited to ascii, so in any case I'd prefer the others, is that not true?

like image 455
Bach Avatar asked Mar 21 '23 08:03

Bach


2 Answers

Bach,

bytearray is a mutable block of memory. To that end, you can push arbitrary bytes into it and manage your memory allocations carefully. While many Python programmers never worry about memory use, there are those of us that do. I manage buffer allocations in high load network operations. There are numerous applications of a mutable array -- too many to count.

It isn't correct to think of the bytearray as a mutable string. It isn't. It is an array of bytes. Strings have a specific structure. bytearrays do not. You can interpret the bytes however you wish. A string is one way. Be careful though, there are many corner cases when using Unicode strings. ASCII strings are comparatively trivial. Modern code runs across borders. Hence, Python's rather complete Unicode-based string classes.

A bytearray reveals memory allocated by the buffer protocol. This very rich protocol is the foundation of Python's interoperation with C and enables numpy and other direct access memory technologies. In particular, it allows memory to be easily structured into multi-dimensional arrays in either C or FORTRAN order.

You may never have to use a bytearray.

Anon, Andrew

like image 145
adonoho Avatar answered Mar 27 '23 21:03

adonoho


deque seems to need much more space than bytearray.

>>> sys.getsizeof(collections.deque(range(256)))
1336
>>> sys.getsizeof(bytearray(range(256)))
293

I Guess this is because of the layout.

If you need samples using bytearray I suggest searching the online code with nullege.

bytearray also has one more advantage: you do not need to import anything for that. This means that people will use it - whether it makes sense or not.

Further reading about bytearray: the bytes type in python 2.7 and PEP-358

like image 37
User Avatar answered Mar 27 '23 19:03

User