I use ElementTree
to parse/build a number of slightly complicated but well-defined xml files, and use mypy
for static typing. I have .find
statements strewn all over the place, which leads to things like this:
from xml.etree.ElementTree import Element
...
root.find('tag_a').append(Element('tag_b'))
# run mypy..
-> type None from Optional[Element] has no attribute append
This makes sense, since find
could simply not find the tag I give it. But I know that it's there and don't want to add stuff like try..except
or assert
statements to essentially simply silence mypy
without adding functionality while making the code less readable. I'd also like to avoid commenting # type: ignore
everywhere.
I tried monkey patching Element.find.__annotations__
, which would be a good solution in my opinion. But since it's a builtin I can't do that, and subclassing Element
feels like too much again.
Is there a good way to solve this?