Skip to content

ElementTree: invalid paths raise KeyError instead of SyntaxError, and C and Python disagree on them #161808

Description

@ines-besrour

Bug report

Bug description

Some malformed paths make find(), findall() and findtext() raise a bare KeyError from ElementPath, while other malformed paths raise SyntaxError("invalid path"). Which paths reach that code also depends on the implementation:

import xml.etree.ElementTree as ET

root = ET.Element("root")
root.find("@")     # KeyError: '@'   (C accelerator and pure Python)
root.find("x=y")   # pure Python: KeyError: '='   C accelerator: None
root.find(")")     # pure Python: KeyError: ')'   C accelerator: None
root.find("]")     # pure Python: KeyError: ']'   C accelerator: None

(The pure-Python results can be reproduced by blocking the accelerator: sys.modules["_elementtree"] = None before importing xml.etree.ElementTree.)

Cause. ElementPath.iterfind() looks up each token with ops[token[0]]. Tokens that start no supported step (@, =, (, ), ], !=, ::) are not in ops, so the lookup raises KeyError. The C accelerator only hands a path to ElementPath when its checkpath() finds one of / * [ @ .; any other path is compared to tags literally. So x=y, ) and ] never reach the lookup in C, but always do in the pure-Python implementation.

Expected. SyntaxError("invalid path") for every path ElementPath cannot parse, as it already raises for other malformed paths. For example, replace the lookup with ops.get(token[0]) and raise SyntaxError when it is missing.

Whether the C fast path should also send such paths to ElementPath, so that both implementations agree, is a separate choice. It would change results for existing code that looks up literal tags such as "a b" or "a:b", so I am only proposing the SyntaxError change.

I'm happy to open a PR.

CPython versions tested on:

CPython main branch, 3.14, 3.13, 3.12

Operating systems tested on:

Linux

Linked PRs

Activity

  1. picnixz commented on Nov 11, 2026

    @picnixz
    Member

    So the syntax is different depending on the implementation?

  2. added
    stdlibStandard Library Python modules in the Lib/ directory
    on Nov 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirstdlibStandard Library Python modules in the Lib/ directorytopic-XMLtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions