typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

make xml module easier to work with

Open tungol opened this issue 3 months ago • 3 comments

Changes:

  • Removed the default value of _Tag, so Element is now Element[Any] instead of Element[str].
  • clean up small inconsistencies caused by the default type of _Tag obscuring where things were missed
  • The TypeAlias _AnyTag isn't strictly needed, but may be convenient for interested end users
  • ElementTree is generic over _Tag now instead of TypeVar(_Root, bound=Element[Any] | None). The None case is marginal and can be ignored. The variable represents the type of the tag attribute of elements within the tree.
  • TreeBuilder is also generic over _Tag. Ideally, it should be TreeBuilder[str] when both insert_comments and insert_pis are False, and TreeBuilder[_AnyTag] when either is true, but it wasn't possible to do something like this based on the __init__ method last time I tried. I don't know if this is worth doing without that.

XMLParser is unchanged, but worth noting because I'm not happy with it still. I don't know if it can be improved given how much duck typing is at work there, but I might take another crack at it later.

@hterik if you're able to try these stubs out against your code, can you let me know what pain points remain? You can clone this branch of typeshed down to your local machine, and tell mypy to use it with mypy --custom-typeshed-dir path/to/typeshed/repo

I don't have a lot of experience using the xml module myself, so your input is very useful.

I am also open to the idea that all of this typevar stuff was a bad idea in the first place - the main thing it's trying to do is save users from needing to guard against ET.Comment and ET.ProcessingInstruction when working with Elements that only contain string tags. It'd save a lot of complexity in the stubs if we bite the bullet on that and just type Element.tag as str | _ElementCallable universally. My intuition was that that would be a frequent papercut annoyance, but maybe the problems introduced by trying to be fancy about it are worse, actually.

tungol avatar Sep 04 '25 08:09 tungol