Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 329
opnightfall1771 Avatar asked Aug 13 '26 08:08

opnightfall1771


1 Answers

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.

like image 88
Abel Cheung Avatar answered Aug 16 '26 07:08

Abel Cheung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!