Skip to content

Re-enable custom target parser support #86

Closed
@abelcheung

Description

@abelcheung

This is most likely achievable by defining a stub-only CustomTargetParser, derived from XMLParser.__new__() whenever target argument is specified. More work is involved besides the stub-only class:

  • C14NWriterTarget and TreeBuilder need to inherit from ParserTarget and match its interface
  • Create wiki page describing how to use custome parser target in fully annotated source code
    • need to enlist all methods available in target object
  • Tie up loose ends of annotation-only ParserTarget class
    • arguments in target object methods need to be positional only, in order to avoid pyright warning about inconsistent param name
  • All methods and functions across the whole types-lxml need to add @overload to handle such custom parser
    • HTML()
    • XML()
    • _ElementTree.parse()
    • ElementTree()
    • fromstring()
    • fromstringlist()
    • parse()

It only works for pyright; mypy ignores any @overload which __new__() returns anything not from originated class or its subclass. Until python/mypy#15182 is fixed, instruct test suite to ignore mypy completely.


Boilerplate code for parser target might look like:

if TYPE_CHECKING:
    from lxml.etree import ParserTarget
else:
    class ParserTarget:
        __class_getitem__ = classmethod(GenericAlias)

class MyTarget(ParserTarget[int]):
    def close(self) -> int:
        ...  # do your stuff

parser = XMLParser(target=MyTarget())
reveal_type(parser)  # CustomeParserTarget[int] for pyright, XMLParser for runtime
with ... as file:
    result = XML(file.read(), parser)
reveal_type(result)  # int for both pyright and runtime

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions