Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions python-bytearray/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Python's Bytearray: A Mutable Sequence of Bytes

This folder contains code associated with the Real Python tutorial [Python's Bytearray: A Mutable Sequence of Bytes](https://realpython.com/python-bytearray/).
25 changes: 25 additions & 0 deletions python-bytearray/creation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
WIDTH = 71

print(" Empty ".center(WIDTH, "="))
print(f"{bytearray() = }")
print(f"{bytearray(0) = }")
print(f"{bytearray([]) = }")
print(f"{bytearray(b"") = }\n")

print(" Zero-filled ".center(WIDTH, "="))
print(f"{bytearray(5) = }\n")

print(" From an iterable of integers ".center(WIDTH, "="))
print(f"{bytearray([65, 66, 67]) = }")
print(f"{bytearray(range(3)) = }\n")

print(" From a bytes-like object ".center(WIDTH, "="))
print(f"{bytearray(b"Espa\xc3\xb1ol") = }\n")

print(" From a string ".center(WIDTH, "="))
print(f"{bytearray("Español", "utf-8") = }")
print(f"{bytearray("Español", "ascii", errors="ignore") = }")
print(f"{bytearray("Español", "ascii", errors="replace") = }\n")

print(" From hexadecimal digits".center(WIDTH, "="))
print(f"{bytearray.fromhex("30 8C C9 FF") = }")
35 changes: 35 additions & 0 deletions python-bytearray/introspection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
def main():
print(
"Mutator methods in bytearray:",
sorted(public_members(bytearray) - public_members(bytes)),
)
print(
"Special methods in bytearray:",
sorted(magic_members(bytearray) - magic_members(bytes)),
)
show_string_members()


def public_members(cls):
return {name for name in dir(cls) if not name.startswith("_")}


def magic_members(cls):
return {name for name in dir(cls) if name.startswith("__")}


def show_string_members():
print("String members in bytearray:")
for i, name in enumerate(
sorted(
name
for name in set(dir(bytearray)) & set(dir(str))
if not name.startswith("_")
),
start=1,
):
print(f"({i:>2}) .{name}()")


if __name__ == "__main__":
main()
88 changes: 88 additions & 0 deletions python-bytearray/mutation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
WIDTH = 71

print(">>> pixels = bytearray([48, 140, 201, 252, 186, 3, 37, 186, 52])")
print(">>> list(pixels)")
pixels = bytearray([48, 140, 201, 252, 186, 3, 37, 186, 52])
print(list(pixels))

print("\n" + " Item assignment ".center(WIDTH, "="))
print(
"""\
>>> for i in range(len(pixels)):
... pixels[i] = 255 - pixels[i]
..."""
)
for i in range(len(pixels)):
pixels[i] = 255 - pixels[i]
print(">>> list(pixels)")
print(list(pixels))

print("\n" + " Slice assignment ".center(WIDTH, "="))
print(">>> pixels[3:6] = (0, 0, 0)")
pixels[3:6] = (0, 0, 0)
print(">>> list(pixels)")
print(list(pixels))

print("\n" + " Slice deletion ".center(WIDTH, "="))
del pixels[3:6]
print(">>> del pixels[3:6]")
print(">>> list(pixels)")
print(list(pixels))

print("\n" + " Item deletion ".center(WIDTH, "="))
del pixels[3]
print(">>> del pixels[3]")
print(">>> list(pixels)")
print(list(pixels))

print("\n" + " Item popping ".center(WIDTH, "="))
print(">>> fourth_byte = pixels.pop(3)")
print(">>> last_byte = pixels.pop()")
fourth_byte = pixels.pop(3)
last_byte = pixels.pop()
print(">>> list(pixels)")
print(list(pixels))

print("\n" + " Value removal ".center(WIDTH, "="))
print(">>> pixels.remove(115)")
pixels.remove(115)
print(">>> list(pixels)")
print(list(pixels))

print("\n" + " Clearing all items ".center(WIDTH, "="))
print(">>> pixels.clear()")
pixels.clear()
print(">>> list(pixels)")
print(list(pixels))

print("\n" + " Appending an item ".center(WIDTH, "="))
print(">>> pixels.append(65)")
print(">>> pixels.append(67)")
pixels.append(65)
pixels.append(67)
print(">>> list(pixels)")
print(list(pixels))

print("\n" + " Inserting an item ".center(WIDTH, "="))
print(">>> pixels.insert(1, 66)")
pixels.insert(1, 66)
print(">>> list(pixels)")
print(list(pixels))

print("\n" + " Extending the bytearray ".center(WIDTH, "="))
print(">>> pixels.extend((1, 2, 3))")
pixels.extend((1, 2, 3))
print(">>> list(pixels)")
print(list(pixels))

print("\n" + " Reversal ".center(WIDTH, "="))
print(">>> pixels.reverse()")
pixels.reverse()
print(">>> list(pixels)")
print(list(pixels))

print("\n" + " Making a copy ".center(WIDTH, "="))
print(">>> pixels_copy = pixels.copy()")
pixels_copy = pixels.copy()
print(">>> list(pixels)")
print(list(pixels))