boto/boto3 · error · TypeError

Value must be of the following types

Error message

Value must be of the following types: {types}

What it means

boto3.dynamodb.types.Binary is a wrapper that explicitly delimits binary data for DynamoDB. Its constructor checks that value is an instance of BINARY_TYPES (bytearray, bytes, and memoryview on supported versions); otherwise it raises TypeError listing the accepted types. Strings and unicode are intentionally rejected to avoid silent encoding bugs.

Solutions

  1. Encode strings to bytes first: Binary(my_str.encode('utf-8')).
  2. Pass bytes/bytearray directly: Binary(b'...').
  3. Validate the source is bytes before constructing Binary.

Example fix

# before
Binary('hello')
# after
Binary(b'hello')
# or
Binary('hello'.encode('utf-8'))
Defensive patterns

Strategy: type-guard

Validate before calling

BINARY_TYPES = (bytes, bytearray, memoryview)
def to_binary(v):
    if isinstance(v, str):
        v = v.encode('utf-8')
    assert isinstance(v, BINARY_TYPES), f'Binary requires bytes, got {type(v)}'
    from boto3.dynamodb.types import Binary
    return Binary(v)

Type guard

def is_binary_value(v) -> bool:
    return isinstance(v, (bytes, bytearray, memoryview))

Try / catch

try:
    from boto3.dynamodb.types import Binary
    b = Binary(value)
except TypeError:
    b = Binary(str(value).encode('utf-8'))

Prevention

When it happens

Trigger: Binary('hello'), Binary(b'x'.decode()), Binary(123), or passing a str where bytes are required.

Common situations: Porting Python 2 code that used str for binary data; receiving a base64-decoded value as a string; forgetting to encode a string before wrapping.

Related errors


AI-assisted analysis of boto/boto3@6e10b029c1 (2026-08-11). Data as JSON: /api/errors/968c6a8065f5b337. Report an issue: GitHub.

Appendix: source

Thrown at boto3/dynamodb/types.py:59

    traps=[Clamped, Overflow, Inexact, Rounded, Underflow],
)


BINARY_TYPES = (bytearray, bytes)


class Binary:
    """A class for representing Binary in dynamodb

    Especially for Python 2, use this class to explicitly specify
    binary data for item in DynamoDB. It is essentially a wrapper around
    binary. Unicode and Python 3 string types are not allowed.
    """

    def __init__(self, value):
        if not isinstance(value, BINARY_TYPES):
            types = ', '.join([str(t) for t in BINARY_TYPES])
            raise TypeError(f'Value must be of the following types: {types}')
        self.value = value

    def __eq__(self, other):
        if isinstance(other, Binary):
            return self.value == other.value
        return self.value == other

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        return f'Binary({self.value!r})'

    def __str__(self):
        return self.value

    def __bytes__(self):
        return self.value

View on GitHub (pinned to 6e10b029c1)