python / python/typeshed

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

Open
#14,671 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stubs: false positive
Dominant language
Python
Stars
5.1k
Forks
2.1k
Avg merge
1d 19h
Merged PRs (30d)
82

Description

To Reproduce

import xml.etree.ElementTree as ET

parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True))
doc = ET.ElementTree().parse("foo.xml", parser)
for el in doc.findall("*"):
    if el.tag is ET.Comment:     #  error: Non-overlapping identity check (left operand type: "str", right operand type: "Callable[[str | None], Element[Callable[..., Element[Any]]]]")  [comparison-overlap]
        print("Comment:", x.text)

Expected Behavior

el.tag should be allowed to be compared to ET.Comment

Actual Behavior

el.tag is constrained to str only and raises following comparision-overlap error when compared with ET.Comment:
# error: Non-overlapping identity check (left operand type: "str", right operand type: "Callable[[str | None], Element[Callable[..., Element[Any]]]]") [comparison-overlap]

This error started after upgrading from mypy 1.14 to 1.15, most likely caused by https://github.com/python/typeshed/pull/13349

Tbh this isn't exactly documented behaviour and parsing comments programmatically isn't exactly best practice either, but some times you are not in control of the xmls received and reading the tag is the the only way to identify the comments that i know.

Your Environment

  • Mypy version used: 1.17
  • Mypy command-line flags: mypy --strict test.py
  • Python version used: 3.13

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the xml.etree.ElementTree type definitions and reproduce the issue with the supplied test.py snippet under Python 3.13 and mypy 1.17 using --strict. Done means the identity comparison between el.tag and ET.Comment no longer produces comparison-overlap while comment parsing remains represented accurately.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.