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
5 changes: 5 additions & 0 deletions isort/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,11 @@ def sort_stream(
if not output_stream.readable():
_internal_output = StringIO()

if config.sort_reexports and not _internal_output.seekable():
raise ValueError(
"sort_reexports requires a seekable output stream "
"and cannot be used with non-seekable streams such as stdout."
)
try:
changed = core.process(
input_stream,
Expand Down
33 changes: 33 additions & 0 deletions tests/unit/test_regressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1985,3 +1985,36 @@ def test_comment_on_opening_line_of_aliased_import_does_not_move():
isort.code(short_line, profile="black")
== "from mod import attr as alias # type: ignore[attr-defined] # My comment\n"
)


def test_sort_reexports_with_non_seekable_stream_issue_2393():
"""Ensure --sort-reexports raises a clear error when output stream is
issues #2393
"""
import io
import sys

code = "from test import B, A\n__all__ = ['B', 'A']\n"

# Simulate a non-seekable stream (like a pipe/stdout)
class NonSeekableStream(io.StringIO):
def seekable(self):
return False

with pytest.raises(ValueError, match="sort_reexports"):
isort.api.sort_stream(
input_stream=io.StringIO(code),
output_stream=NonSeekableStream(),
sort_reexports=True,
)

# Seekable stream should still work correctly
output_stream = io.StringIO()
isort.api.sort_stream(
input_stream=io.StringIO(code),
output_stream=output_stream,
sort_reexports=True,
)
output_stream.seek(0)
assert "import A, B" in output_stream.read()