WarningPython Error

BytesWarning

BytesWarning: str() on a bytes instance

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    text = str(data)  # produces "b'hello'" not "hello"
BytesWarning: str() on a bytes instance

What causes this error

A questionable bytes/str operation was performed while Python was run with the -b flag. Without -b, these operations proceed silently.

How to fix it

Use explicit encoding/decoding: `.decode()` for bytes→str, `.encode()` for str→bytes. Compare only matching types. Run with `python -bb` during development to turn these into errors.

Code that causes this error

Broken
# Run with: python -b script.py
data = b"hello"
text = str(data)  # produces "b'hello'" not "hello"

Fixed code

Fixed
data = b"hello"
text = data.decode("utf-8")  # produces "hello"

About BytesWarning

A BytesWarning is issued when a questionable operation involving bytes and strings occurs. It is only active when Python is run with the `-b` flag (warning) or `-bb` flag (error). Without these flags, BytesWarning is never shown.

The warning catches common mistakes like comparing bytes and str objects, calling `str()` on a bytes object (which produces the repr like `"b'hello'"` instead of the decoded string), and other operations where bytes/str confusion is likely. This warning is valuable during development and testing to catch subtle encoding bugs that would otherwise produce incorrect results silently. Adding `-b` to your test runner's Python flags helps catch these issues early in the development cycle.

Common scenarios

1

Using deprecated APIs that will be removed in future versions

2

Performing numerical operations that produce inf or NaN values

3

Leaving files, sockets, or connections open without proper cleanup

4

Calling async functions without awaiting the result

Related errors