Skip to content
Merged
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
18 changes: 17 additions & 1 deletion python/markupever/dom.py
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,16 @@ def __delitem__(self, index: int | str | _rustlib.QualName) -> None:

self.__raw.remove(index)

@typing.overload
def __setitem__(self, index: int, val: tuple[_rustlib.QualName | str, str]) -> None: ...

@typing.overload
def __setitem__(
self,
index: str | _rustlib.QualName,
val: str | tuple[_rustlib.QualName | str, str],
) -> None: ...

def __setitem__(
self,
index: int | str | _rustlib.QualName,
Expand All @@ -865,7 +875,10 @@ def __setitem__(
a new attribute is pushed. If the key exists, the attribute is updated.

- index: An integer index or a string/QualName key to set.
- val: A value to set, either as a string or a (key, value) tuple.
- val: A value to set, either as a string or a (key, value) tuple. With an integer
index, it must be a (key, value) tuple.

Raises `TypeError` if the index is an integer and the value is a string.
"""
if not isinstance(index, int):
key, value = (index, val) if isinstance(val, str) else val
Expand All @@ -877,6 +890,9 @@ def __setitem__(

val = (key, value)

if isinstance(val, str):
raise TypeError("an attribute index must be assigned a (key, value) tuple, not a str")

self.__raw.update_item(index, val[0], val[1])

@typing.overload
Expand Down
7 changes: 7 additions & 0 deletions python/tests/test_dom.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,13 @@ def test_element():
html.attrs.insert(0, "onclick", "alert")
assert html.attrs[0] == (markupever.dom.QualName("onclick"), "alert")

# An attribute index must be assigned a (key, value) tuple.
with pytest.raises(TypeError):
html.attrs[0] = "confirm" # type: ignore[call-overload]
assert html.attrs[0] == (markupever.dom.QualName("onclick"), "alert")
html.attrs[0] = ("onload", "init")
assert html.attrs[0] == (markupever.dom.QualName("onload"), "init")

html.attrs = [("id", "id1"), ("id", "id2"), ("data-role", "button")]
assert html.id == "id1"

Expand Down
Loading