Skip to content

Commit 0e97999

Browse files
authored
Improve "parser=" and return annotations of fromstring() and parse() (GH-64)
`parser` can also be an HTMLParser, not just XMLParser. It's possible for these functions to return None, if the parser has `recover=True` or a custom parser target was provided. Otherwise, they always return an `_Element`. Closes #63.
1 parent 53d99b5 commit 0e97999

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

lxml-stubs/etree.pyi

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -499,12 +499,25 @@ def cleanup_namespaces(
499499
keep_ns_prefixes: Optional[Iterable[_AnyStr]] = ...,
500500
) -> None: ...
501501
def parse(
502-
source: _FileSource, parser: XMLParser = ..., base_url: _AnyStr = ...
503-
) -> _ElementTree: ...
502+
source: _FileSource,
503+
parser: Union[XMLParser, HTMLParser] = ...,
504+
base_url: _AnyStr = ...,
505+
) -> Union[_ElementTree, Any]: ...
506+
@overload
504507
def fromstring(
505-
text: _AnyStr, parser: XMLParser = ..., *, base_url: _AnyStr = ...
508+
text: _AnyStr,
509+
parser: None = ...,
510+
*,
511+
base_url: _AnyStr = ...,
506512
) -> _Element: ...
507513
@overload
514+
def fromstring(
515+
text: _AnyStr,
516+
parser: Union[XMLParser, HTMLParser] = ...,
517+
*,
518+
base_url: _AnyStr = ...,
519+
) -> Union[_Element, Any]: ...
520+
@overload
508521
def tostring(
509522
element_or_tree: _ElementOrTree,
510523
encoding: Union[Type[str], Literal["unicode"]],

test-data/test-etree.yml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,14 @@
55
document = etree.fromstring("<doc></doc>")
66
reveal_type(document) # N: Revealed type is "lxml.etree._Element"
77
8+
- case: etree_from_empty_string_with_parser_recovery_returns_none
9+
disable_cache: true
10+
main: |
11+
from lxml import etree
12+
parser = etree.HTMLParser(recover=True)
13+
document = etree.fromstring("", parser)
14+
reveal_type(document) # N: Revealed type is "Union[lxml.etree._Element, Any]"
15+
816
- case: etree_element_find
917
disable_cache: true
1018
main: |

0 commit comments

Comments
 (0)