The correct python way to clear bytearray

I miss a memset. I have a frame buffer in the class, it has data in it from some other operations, and now I want to clear everything in this frame buffer to 0x00 or 0xFF. I did not see a clear method in the docs, zpill can work there. I thought about just calling the init method of the byte array again, but wondered if this could cause me memory problems in the future.

I am using python 2.7.

+4
source share
3 answers

Python is not C, you don't have to worry about memory at all here . Just simple:

a = bytearray("abcd") # initialized it with real data

a = bytearray(5) # just a byte array of size 5 filled with zeros
+5
source
In [1]: ba = bytearray(range(100))

In [2]: ba
Out[2]: bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abc')

In [3]: ba[:] = b'\x00' * len(ba)

In [4]: ba
Out[4]: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
+3
source

, NumPy. NumPy uint8 s:

import numpy as np
fb = np.zeros((480, 640), dtype=np.uint8) # a 640x480 monochrome framebuffer

:

fb[:] = 0 # or fb[:] = 0xff

Another big advantage is that you get a fast 2D array - you can do things like fb[80:120, 40:60]get a rectangular region cheaply and you can implement drawing operations like blitting with very little code. Also, with np.tobytesyou can still get a representation of the bytes.

+3
source

All Articles