opnightfall1771
opnightfall1771

Reputation: 163

Correct way to type hint protected / private classes in Python?

I have a sample class here that I would like to use lxml to parse xml files.

class XMLParser:

    def __init__(self, path: str):
        self.root: etree._Element | None = None

However, PyCharm complains about access to a protected member _Element when I use this type hint. Is there a more correct way to annotate such a variable? The _Element class is the correct one when I type check this.

Thanks for your help!

Upvotes: 5

Views: 2160

Answers (1)

Abel Cheung
Abel Cheung

Reputation: 526

The best approach for OP is to ignore PyCharm warnings. With my few years of experience working on lxml type annotations, the "public" / "private"-ness and class names do not have definite relation -- some private structures unable to be constructed by users have public-class-like names (exported publicly and without underscore, like DocInfo).

Although etree._Element is seemingly declared as "private" by author, lxml users simply can't avoid it in function signatures. The same is also true for other "private" classes like _ElementTree, _Comment etc.

Upvotes: 2

Related Questions