Locally patch missing Python type annotations?

592 views Asked by At

Python now supports type hinting, so... yay! It seems like a great method to avoid some of the more obscure runtime bugs.

Sadly, third-party library support remains an issue. Though partially solved by the typeshed project, which is also used by mypy, when trying to port some of my code to use type hints, I ran into issues due to missing stubs.

E.g.

# file:mypytest.py
import lxml.etree as et
tree = et.fromstring('<root><a>1</a><b>2</b><a>3</a></root>')
items = tree.xpath('/root/a')
print([i.text for i in items])

will work perfectly well, but mypy will produce the spurious error message

>>> mypy mypytest.py
mypytest.py:3: error: "_Element" has no attribute "xpath"

because the stub is currently incomplete.

For a larger project, downloading the stub from typeshed, adding the missing entries, and maybe even submitting the corresponding pull request is a no-brainer.

But is there some method to monkey-patch the missing information in quick-and-dirty scenarios?

Bad workaround

The best I was able to come up with was

items = tree.xpath('/root/a') # type: ignore

which silences the error, but also disables type-checking where the variable items is used afterwards. E.g. items[0] + 1 will not cause a warning anymore.

In order to preserve type-checking it is possible to use

items_tmp = tree.xpath('/root/a') # type: ignore
items = items_tmp # type: List[et._Element]

but this seems hackish; It also has to be repeated everywhere the .xpath method is used.

Update from 2017-09-12: Alternatively one can use the syntax

items_tmp : List[et._Element] = tree.xpath('/root/a') # type: ignore
0

There are 0 answers