Skip to content

Commit

Permalink
Improve "parser=" and return annotations of fromstring() and parse() (G…
Browse files Browse the repository at this point in the history
…H-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.
  • Loading branch information
DMRobertson committed Jul 26, 2022
1 parent 53d99b5 commit 0e97999
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
19 changes: 16 additions & 3 deletions lxml-stubs/etree.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -499,12 +499,25 @@ def cleanup_namespaces(
keep_ns_prefixes: Optional[Iterable[_AnyStr]] = ...,
) -> None: ...
def parse(
source: _FileSource, parser: XMLParser = ..., base_url: _AnyStr = ...
) -> _ElementTree: ...
source: _FileSource,
parser: Union[XMLParser, HTMLParser] = ...,
base_url: _AnyStr = ...,
) -> Union[_ElementTree, Any]: ...
@overload
def fromstring(
text: _AnyStr, parser: XMLParser = ..., *, base_url: _AnyStr = ...
text: _AnyStr,
parser: None = ...,
*,
base_url: _AnyStr = ...,
) -> _Element: ...
@overload
def fromstring(
text: _AnyStr,
parser: Union[XMLParser, HTMLParser] = ...,
*,
base_url: _AnyStr = ...,
) -> Union[_Element, Any]: ...
@overload
def tostring(
element_or_tree: _ElementOrTree,
encoding: Union[Type[str], Literal["unicode"]],
Expand Down
8 changes: 8 additions & 0 deletions test-data/test-etree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
document = etree.fromstring("<doc></doc>")
reveal_type(document) # N: Revealed type is "lxml.etree._Element"
- case: etree_from_empty_string_with_parser_recovery_returns_none
disable_cache: true
main: |
from lxml import etree
parser = etree.HTMLParser(recover=True)
document = etree.fromstring("", parser)
reveal_type(document) # N: Revealed type is "Union[lxml.etree._Element, Any]"
- case: etree_element_find
disable_cache: true
main: |
Expand Down

0 comments on commit 0e97999

Please sign in to comment.