Skip to content

gh-135640: Adds type checking to ElementTree.ElementTree constructor, plus relevant tests #135643

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Lib/test/test_xml_etree.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,13 @@ def check_element(element):
self.assertRegex(repr(element), r"^<Element 't\xe4g' at 0x.*>$")
element = ET.Element("tag", key="value")

# Verify type checking for ElementTree constructor

with self.assertRaises(TypeError):
tree = ET.ElementTree("")
with self.assertRaises(TypeError):
tree = ET.ElementTree(ET.ElementTree())

# Make sure all standard element methods exist.

def check_method(method):
Expand Down
8 changes: 6 additions & 2 deletions Lib/xml/etree/ElementTree.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,9 @@ class ElementTree:

"""
def __init__(self, element=None, file=None):
# assert element is None or iselement(element)
if element is not None and not iselement(element):
raise TypeError(f"element must be etree.Element, "
f"not {type(element).__name__}")
self._root = element # first node
if file:
self.parse(file)
Expand All @@ -543,7 +545,9 @@ def _setroot(self, element):
with the given element. Use with care!

"""
# assert iselement(element)
if not iselement(element):
raise TypeError(f"element must be etree.Element, "
f"not {type(element).__name__}")
self._root = element

def parse(self, source, parser=None):
Expand Down
Loading