BytesWarning
BytesWarning: str() on a bytes instance
Traceback
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 instanceWhat 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
# Run with: python -b script.py data = b"hello" text = str(data) # produces "b'hello'" not "hello"
Fixed code
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
Using deprecated APIs that will be removed in future versions
Performing numerical operations that produce inf or NaN values
Leaving files, sockets, or connections open without proper cleanup
Calling async functions without awaiting the result