Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions babel/messages/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,8 @@ def _parse_python_string(value: str, encoding: str, future_flags: int) -> str |
if isinstance(code, ast.Expression):
body = code.body
if isinstance(body, ast.Constant):
if isinstance(body.value, bytes):
return None # byte strings are not translatable
Comment on lines +713 to +714
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Like for the f-string case below, let's add a note for our future selves that we could warn in this case.

Suggested change
if isinstance(body.value, bytes):
return None # byte strings are not translatable
if isinstance(body.value, bytes):
# TODO: we could raise an error or warning when this occurs
return None # byte strings are not translatable

return body.value
if isinstance(body, ast.JoinedStr): # f-string
if all(isinstance(node, ast.Constant) for node in body.values):
Expand Down
14 changes: 14 additions & 0 deletions tests/messages/test_extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,17 @@ def test_issue_1195_2():
'NOTE: This should still be considered, even if',
'the text is far away',
]


def test_extract_byte_string_does_not_crash():
"""Byte strings like _(b'foo') should be skipped without crashing."""
buf = BytesIO(b"""\
_(b'foo')
_('hello')
_(b"bar")
_('world')
""")
messages = list(extract.extract('python', buf, {'_': None}, [], {}))
assert len(messages) == 2
assert messages[0][1] == 'hello'
assert messages[1][1] == 'world'