Skip to content

Commit

Permalink
Add documentation for bytes formatting error code (#14971)
Browse files Browse the repository at this point in the history
See #14959
  • Loading branch information
hauntsaninja committed Mar 30, 2023
1 parent 10ae912 commit a9a047e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
18 changes: 18 additions & 0 deletions docs/source/error_code_list.rst
Original file line number Diff line number Diff line change
Expand Up @@ -908,6 +908,24 @@ Functions will always evaluate to true in boolean contexts.
if f: # Error: Function "Callable[[], Any]" could always be true in boolean context [truthy-function]
pass
Check for implicit bytes coercions [str-bytes-safe]
-------------------------------------------------------------------

Warn about cases where a bytes object may be converted to a string in an unexpected manner.

.. code-block:: python
b = b"abc"
# Error: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc".
# If this is desired behavior, use f"{x!r}" or "{!r}".format(x).
# Otherwise, decode the bytes [str-bytes-safe]
print(f"The alphabet starts with {b}")
# Okay
print(f"The alphabet starts with {b!r}") # The alphabet starts with b'abc'
print(f"The alphabet starts with {b.decode('utf-8')}") # The alphabet starts with abc
Report syntax errors [syntax]
-----------------------------

Expand Down
2 changes: 1 addition & 1 deletion mypy/errorcodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def __str__(self) -> str:
"str-format", "Check that string formatting/interpolation is type-safe", "General"
)
STR_BYTES_PY3: Final = ErrorCode(
"str-bytes-safe", "Warn about dangerous coercions related to bytes and string types", "General"
"str-bytes-safe", "Warn about implicit coercions related to bytes and string types", "General"
)
EXIT_RETURN: Final = ErrorCode(
"exit-return", "Warn about too general return type for '__exit__'", "General"
Expand Down

0 comments on commit a9a047e

Please sign in to comment.