Skip to content

[xml.etree] Allow comparing plain Element.tag with ET.Comment/PI - #16735

Open
hrithiksaini99 wants to merge 2 commits into
python:mainfrom
hrithiksaini99:fix/14671-et-comment-tag
Open

hrithiksaini99 wants to merge 2 commits into
python:mainfrom
hrithiksaini99:fix/14671-et-comment-tag

Conversation

@hrithiksaini99

@hrithiksaini99 hrithiksaini99 commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Problem

ET.Comment and ET.ProcessingInstruction are valid element tags at runtime (TreeBuilder(insert_comments=True)), but elements from findall('*') get tag type str, so el.tag is ET.Comment raises comparison-overlap (since mypy 1.15 via #13349).

Fix

Traversal APIs (Element/ElementTree.find, findall, iter, iterfind, ElementTree.parse) now return Element[Any], so .tag is Any and identity comparisons against the comment/PI factories are allowed. Element.tag itself stays str for explicitly tagged elements (Element('x').tag still infers str) — no change to the generic default.

Earlier iteration widened the TypeVar default to str | _ElementCallable; mypy_primer showed that regressed downstream (colour expected str), so this narrower version keeps tag: str intact.

Verification

python tests/mypy_test.py stdlib/xml/etree/ElementTree.pyi  # success
python tests/regr_test.py stdlib                           # success

New regression identity checks in stdlib/@tests/test_cases/check_xml.py.

Fixes #14671.

@github-actions

This comment has been minimized.

…findall/iter

mypy_primer showed widening the _Tag default to str | _ElementCallable
broke downstream (colour: tag is no longer str where str is expected).

Instead, traversal APIs return Element[Any], so el.tag is Any and
identity comparisons against ET.Comment/PI don't error, while
Element('x').tag stays str. Simpler and no downstream fallout.
@hrithiksaini99
hrithiksaini99 force-pushed the fix/14671-et-comment-tag branch from 3f6c37f to 7c6f19f Compare November 7, 2026 08:55
@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

materialize (https://github.com/MaterializeInc/materialize)
- misc/python/materialize/cli/gen-chroma-syntax.py:56: error: Incompatible types in assignment (expression has type "Element[str] | None", variable has type "Element[str]")  [assignment]
+ misc/python/materialize/cli/gen-chroma-syntax.py:56: error: Incompatible types in assignment (expression has type "Element[Any] | None", variable has type "Element[str]")  [assignment]

This branch has not been deployed

No deployments
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.

ET.Element.tag does not allow comparision with ET.Comment

1 participant