TheAlgorithms/Python · error · TypeError

a bytes-like object is required, not '{data.__class__.__name

Error message

a bytes-like object is required, not '{data.__class__.__name__}'

What it means

Raised by base64_encode() in ciphers/base64_cipher.py when the data argument is not a bytes object. The function implements Base64 from scratch and only accepts raw bytes, mirroring the stdlib error text. Any str, int, or other type is rejected before encoding begins.

Source

Thrown at ciphers/base64_cipher.py:38

    >>> from base64 import b64encode
    >>> a = b"This pull request is part of Hacktoberfest20!"
    >>> b = b"https://tools.ietf.org/html/rfc4648"
    >>> c = b"A"
    >>> base64_encode(a) == b64encode(a)
    True
    >>> base64_encode(b) == b64encode(b)
    True
    >>> base64_encode(c) == b64encode(c)
    True
    >>> base64_encode("abc")
    Traceback (most recent call last):
      ...
    TypeError: a bytes-like object is required, not 'str'
    """
    # Make sure the supplied data is a bytes-like object
    if not isinstance(data, bytes):
        msg = f"a bytes-like object is required, not '{data.__class__.__name__}'"
        raise TypeError(msg)

    binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data)

    padding_needed = len(binary_stream) % 6 != 0

    if padding_needed:
        # The padding that will be added later
        padding = b"=" * ((6 - len(binary_stream) % 6) // 2)

        # Append binary_stream with arbitrary binary digits (0's by default) to make its
        # length a multiple of 6.
        binary_stream += "0" * (6 - len(binary_stream) % 6)
    else:
        padding = b""

    # Encode every 6 binary digits to their corresponding Base64 character
    return (
        "".join(

View on GitHub (pinned to f5988cc097)

Solutions

  1. Encode strings first: base64_encode(my_str.encode('utf-8'))
  2. Convert bytes-like inputs: base64_encode(bytes(my_bytearray))
  3. Wrap the call with a type check and raise a clearer error from your own code

Example fix

# before
base64_encode("hello")

# after
base64_encode("hello".encode("utf-8"))
Defensive patterns

Strategy: type-guard

Validate before calling

data = data.encode("utf-8") if isinstance(data, str) else data

Type guard

def as_bytes(data) -> bytes:
    if isinstance(data, str):
        return data.encode("utf-8")
    if isinstance(data, bytes):
        return data
    raise TypeError(f"expected str or bytes, got {type(data).__name__}")

Try / catch

try:
    encoded = base64_encode(data)
except TypeError as exc:
    if "bytes-like object" in str(exc):
        encoded = base64_encode(str(data).encode("utf-8"))
    else:
        raise

Prevention

When it happens

Trigger: Calling base64_encode("abc") with a str; passing an int, bytearray is rejected too (isinstance(data, bytes) is strict, so even bytearray fails); passing output of a text API (e.g. json.dumps result) without encoding.

Common situations: Porting code from stdlib base64.b64encode which accepts bytes-like objects (bytearray, memoryview) and hitting this stricter bytes-only check; reading a file in text mode and passing its contents directly; interactive testing with string literals.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/92dbed3db2956bfe. Report an issue: GitHub.