gh-127550 Fix ElementTree write newline handling#148975
gh-127550 Fix ElementTree write newline handling#148975durawat wants to merge 1 commit intopython:mainfrom
Conversation
|
The following commit authors need to sign the Contributor License Agreement: |
|
Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool. If this change has little impact on Python users, wait for a maintainer to apply the |
0d0bc0d to
2ed04f0
Compare
|
Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool. If this change has little impact on Python users, wait for a maintainer to apply the |
|
The existing tests seem to indicate that this is a deliberate behavior. I am closing this PR because we need consensus first. Please don't open PRs in the future if no consensus is reached. In addition, don't use LLMs as we forbid them (read https://devguide.python.org/getting-started/generative-ai/ for acceptable uses) |
gh-127550: Fix ElementTree.write to ensure newline consistency between standalone and context manager use
Summary
Ensure consistent newline handling in
ElementTree.write()when writingto a filename versus a file-like object.
Relevant code in
Lib/xml/etree/ElementTree.pyFunction:
_get_writer(file_or_filename, encoding)Removing
newline="\n"from the first code block caused multiple testfailures in
Lib/test/test_xml_etree.py. In contrast, addingnewline="\n"to the second block resulted in only one failing test.Writer for file-like objects
Writer for file or filename
Changes
Added
newline="\n"to theopen()call for filename-based writing,instead of removing it from the
TextIOWrapperpath, to ensure consistentbehavior between file-like objects and filenames.
This change improves consistency between the two code paths.
Rationale
According to the XML specification, XML parsers normalize line endings.
The sequences
\r\n,\r, and\nare all normalized to\nduring parsing.Therefore, differences in newline handling at write time do not affect
parsed XML content, but consistency in output behavior is desirable.
Tests
Lib/test/test_xml_etree.pyLib/test/test_xml_etree.py