Skip to content

Commit

Permalink
Add support for list flattening args
Browse files Browse the repository at this point in the history
  • Loading branch information
MaddyGuthridge committed Sep 29, 2023
1 parent 2b413e0 commit d48ef21
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
4 changes: 2 additions & 2 deletions pyhtml/__tag_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def __init__(self, *children: Any, **properties: Any) -> None:
"""
Create a new tag instance
"""
self.children = list(children)
self.children = util.flatten_list(list(children))
"""Children of this tag"""

self.properties = util.filter_properties(properties)
Expand All @@ -34,7 +34,7 @@ def __call__(
properties are based on this original tag, but with additional children
appended and additional properties unioned.
"""
new_children = self.children + list(children)
new_children = self.children + util.flatten_list(list(children))
new_properties = self.properties | properties

return self.__class__(*new_children, **new_properties)
Expand Down
20 changes: 19 additions & 1 deletion pyhtml/__util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
Random helpful functions used elsewhere
"""
from typing import Any
from typing import Any, TypeVar


T = TypeVar('T')


def increase_indent(text: list[str], amount: int) -> list[str]:
Expand Down Expand Up @@ -111,3 +114,18 @@ def render_children(children: list[Any], sep: str = ' ') -> list[str]:
for ele in children:
rendered.extend(render_inline_element(ele))
return increase_indent(rendered, 2)


def flatten_list(the_list: list[T | list[T]]) -> list[T]:
"""
Flatten a list by taking any list elements and inserting their items
individually. Note that other iterables (such as str and tuple) are not
flattened.
"""
result: list[T] = []
for item in the_list:
if isinstance(item, list):
result.extend(item)
else:
result.append(item)
return result
19 changes: 19 additions & 0 deletions tests/basic_rendering_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,22 @@ def test_format_through_repr():
doc = html()

assert repr(doc) == "<html></html>"


def test_flatten_element_lists():
"""
If a list of elements is given as a child element, each element should be
considered as a child.
"""
doc = html([p("Hello"), p("world")])

assert repr(doc) == "\n".join([
"<html>",
" <p>",
" Hello",
" </p>",
" <p>",
" world",
" </p>",
"</html>",
])

0 comments on commit d48ef21

Please sign in to comment.