Skip to content

How to store text and bytes

Text and bytes vary in length, but every field of a box has a fixed size. So when you declare a str or bytes field, you also say how much room it gets, its capacity: the most bytes it can hold. This guide shows how to choose it and what happens when a value doesn't fit.

1. Declare the field with a capacity

Wrap the type in Annotated and add a Capacity, as owner does below, or keep the annotation plain and give the capacity to field, as barcode does. Both lay out the field the same way:

from typing import Annotated

from sharedbox import Capacity, SharedBox


class Envelope(SharedBox, name="example-envelope"):
    owner: Annotated[str, Capacity(16)] = ""
    barcode: Annotated[bytes, Capacity(1024)] = b""

2. Write and read values

From then on you use the field like any other attribute:

envelope = Envelope()
envelope.owner = "Ada"
envelope.barcode = bytes(range(8))
print(envelope.owner, len(envelope.barcode))  # Ada 8

You can also assign a bytearray or a memoryview to a bytes field; reading it back always gives you bytes.

3. Handle a value that is too long

If you assign a value longer than the capacity, you get a ValueError and the field keeps its old value, so a reader never sees half of it:

try:
    envelope.owner = "Ada Lovelace, 12 High St"
except ValueError as error:
    print(error)  # Envelope.owner holds at most 16 bytes; the value encodes to 24
print(envelope.owner)  # Ada

A bytearray field reads back as a bytearray that can grow past the capacity, and the capacity is checked when you assign it back to the field.

4. Count bytes, not characters

The capacity counts bytes of the UTF-8 encoding, not characters, and a character takes between 1 and 4 bytes. Text with accents or other scripts fills the room faster than it looks:

print(len("été"), len("été".encode()))  # 3 5

To be sure n characters of any language fit, give the field a capacity of 4 * n. If you know the text is plain ASCII, n is enough.

5. Cut a value to fit

Sometimes you'd rather keep the start of a long text than refuse it. Cut its encoding to the capacity, and drop any character the cut split in two, as this helper does:

def fit(text: str, size: int) -> str:
    return text.encode()[:size].decode(errors="ignore")


envelope.owner = fit("Ada Lovelace, 12 High St", 16)
print(envelope.owner)  # Ada Lovelace, 12
The whole script
"""The script of the guide "How to store text and bytes"."""

from typing import Annotated

from sharedbox import Capacity, SharedBox


class Envelope(SharedBox, name="example-envelope"):
    owner: Annotated[str, Capacity(16)] = ""
    barcode: Annotated[bytes, Capacity(1024)] = b""



envelope = Envelope()
envelope.owner = "Ada"
envelope.barcode = bytes(range(8))
print(envelope.owner, len(envelope.barcode))  # Ada 8

try:
    envelope.owner = "Ada Lovelace, 12 High St"
except ValueError as error:
    print(error)  # Envelope.owner holds at most 16 bytes; the value encodes to 24
print(envelope.owner)  # Ada

print(len("été"), len("été".encode()))  # 3 5


def fit(text: str, size: int) -> str:
    return text.encode()[:size].decode(errors="ignore")


envelope.owner = fit("Ada Lovelace, 12 High St", 16)
print(envelope.owner)  # Ada Lovelace, 12

envelope.close()
Envelope.unlink()