Should we use private or protected methods for implementation details?

Hello,

I read in many places that we should avoid using private methods, e.g. __fun but we should go for protected ones _fun for stuff that is not going to be accessed outside the class. However, when using pyright, I am not alerted about _fun not been used, I am only alerted when the method is private.

Not knowing that a method is no longer used and can be removed safely is problematic, I am finding a lot of dead code. If I were to subclass my class, I would just switch whatever method I need in the subclass to protected anyway. Are the people telling us not to use protected methods wrong or am I missing anything?

Cheers.

That seems like an improvement suggestion for pyright; at the very least this should be configurable.

1 Like

To answer why it it is bad practice to use private naming:

Basically in Python the saying is that we are all reasonable adults and therefore, if you use a variable starting with _, you are using internal features and it is your responsibility if something goes wrong.

Therefore private methods further force the user to not use a variable is seen as bad practice, because the user might really have a need to access it. The issue is, you can still access it via f"_{obj_class_name}{obj_name}", so for example _Student__password for a Student object with a private field __password. This process is called Name Mangling.

It just makes it harder for the user to do so, because linters and type checkers hide those variables usually.

I still rarely use private fields, but you should have good reasons to do so.

Edit: Add final quotation mark in f-string

2 Likes