Skip to content

Self narrows with custom element class #51

@scanny

Description

@scanny

element: Self is used in multiple places in the stub for etree._Element. Here's a typical example:
https://github.com/abelcheung/types-lxml/blob/main/lxml-stubs/etree/_element.pyi#L97

This produces over-narrowing of the type when used with custom element classes, like this:

class Frombus(etree._Element):
    def add_child(self):
        self.insert(0, element_that_is_not_a_frombus)
# --------------- ^^^ Argument of type "NotAFrombus" cannot be assigned to parameter
#                     "element" of type "Self@Frombus" in function insert

This is because Self takes the type of self (Frombus in this case) and only wants to allow elements of the same type to be inserted.

I think the solution is to use "_Element" in most (or maybe all) places where Self appears within the _Element stub, which I expect was the original intent (that element can be any subtype of _Element). If you add from __future__ import annotations at the top of the file I believe you can leave off the double-quotes.

This works as intended when I patch in these changes locally.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions