Skip to content

Preserve encoding and line endings with --overwrite-in-place - #2743

Merged
DanielNoord merged 1 commit into
PyCQA:mainfrom
APX403:overwrite-in-place
Oct 25, 2026
Merged

DanielNoord merged 1 commit into
PyCQA:mainfrom
APX403:overwrite-in-place

Conversation

@APX403

@APX403 APX403 commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

With --overwrite-in-place, isort writes the sorted file back in the locale encoding and with the platform's line endings, not the ones the file had. On Linux with 9.0.2, a CRLF file comes back with LF and a latin-1 file with a coding cookie is rewritten in UTF-8:

$ printf 'import sys\r\nimport os\r\n' > crlf.py
$ printf '# -*- coding: latin-1 -*-\nimport sys\nimport os\n\nprint("caf\xe9")\n' > legacy.py
$ python legacy.py
café
$ isort --overwrite-in-place crlf.py legacy.py
Fixing /tmp/demo/crlf.py
Fixing /tmp/demo/legacy.py
$ python -c 'print(open("crlf.py", "rb").read())'
b'import os\nimport sys\n'
$ python legacy.py
café

A UTF-8 BOM is dropped too, while the default mode keeps all three. On Windows the same write turns LF into CRLF and uses the ANSI code page unless Python runs in UTF-8 mode. When a character doesn't fit, the write fails after the file was truncated, so isort warns, exits 0 and leaves the file empty, which matches #2199.

The in-place writer buffers the output in StringIO(newline=None) and writes it back with path.open("w"):

isort/isort/api.py

Lines 356 to 363 in a514c71

stream = StringIO(newline=None)
yield stream
if changed.is_set():
stream.seek(0)
source_file.stream.close()
with source_file.path.open("w") as fs:
shutil.copyfileobj(stream, fs)

while the default mode opens its .isorted file with encoding=source_file.encoding, newline="". The buffer now keeps the newlines and the output is encoded with source_file.encoding before the file is opened, so both modes write the same bytes, and an encoding error (a configured heading the file's encoding can't hold, for example) leaves the file as it was.

The in-place writer buffered the output in StringIO(newline=None),
which turns CRLF and CR into LF, and wrote it back with
path.open("w"), which uses the locale encoding and os.linesep, instead
of the encoding detected when the file was read. A file declaring
another encoding was rewritten in the locale one, the UTF-8 BOM was
dropped, CRLF line endings became LF (LF became CRLF on Windows), and
when the locale encoding could not represent the content the file was
left empty, which matches what PyCQA#2199 reported on Windows.

Keep newlines in the buffer as they are, encode the output with the
detected encoding before opening the file and write the bytes, the
same bytes the .isorted temporary file gets. An encoding error now
leaves the file as it was.
@codecov

codecov Bot commented Oct 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.38%. Comparing base (a514c71) to head (fd043f4).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2743      +/-   ##
==========================================
- Coverage   99.38%   99.38%   -0.01%     
==========================================
  Files          40       40              
  Lines        3274     3273       -1     
  Branches      706      706              
==========================================
- Hits         3254     3253       -1     
  Misses         12       12              
  Partials        8        8              
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approved

The focused implementation preserves the source format and adds regression coverage for the reported failures, with no unresolved findings.

No open issues 🎉

What changed in this PR

This PR makes --overwrite-in-place preserve source encoding and line endings, aligning its output with the default file-writing mode.

Changes:

  • Preserve line endings in the in-memory output buffer.
  • Encode output using the source encoding before opening the file, preventing truncation on encoding errors.
  • Add regression tests for LF/CRLF, Latin-1, UTF-8 BOM, and file preservation after encoding failures.
File Description
tests/​unit/​test_api.py Adds byte-level checks for encoding, line endings, and encoding-error safety.
isort/​api.py Preserves buffered newlines and writes pre-encoded bytes in overwrite mode.

Review effort: Balanced

@DanielNoord
DanielNoord added this pull request to the merge queue Oct 25, 2026
Merged via the queue into PyCQA:main with commit 3e68366 Oct 25, 2026
37 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants