pythonlxmlpython-typingmypylxml.html

Type hints for lxml?


New to Python and come from a statically typed language background. I want type hints for https://lxml.de just for ease of development (mypy flagging issues and suggesting methods would be nice!)

To my knowledge, this is a python 2.0 module and doesn’t have types. Currently I’ve used https://mypy.readthedocs.io/en/stable/stubgen.html to create stub type definitions and filling in “any”-types I’m using with more information, but it’s really hacky. Are there any safer ways to get type hints?


Solution

  • There is an official stubs package for lxml now called lxml-stubs:

    $ pip install lxml-stubs
    

    Note, however, that the stubs are still in development and are not 100% complete yet (although very much usable from my experience). These stubs were once part of typeshed, then curated by Jelle Zijlstra after removal and now are developed as part of the lxml project.

    If you want the development version of the stubs, install via

    $ pip install git+https://github.com/lxml/lxml-stubs.git
    

    (the project's readme installation command is missing the git+ prefix in URL's scheme and won't work).