is it okay to call a private static method outside the class
Question:
In python, is it okay to call a private static method outside the class? The class is from an external module, so I can’t move it outside the class, but the method is useful for me.
class Vector:
@staticmethod
def _add(a,b):
return a + b
# is it okay to do:
Vector._add(1,2)
By "is it okay", I mean in terms of good practices/PEP guidelines.
Answers:
Generally speaking in languages without proper method privacy, such as Python and Perl, an underscore prefix in a method name is an indication that the author of the class does not want you to call that method.
That goes for use outside the class, in subclasses, in related classes, etc.
The exception to that would be if the author has explicitly documented (either as part of the class’s formal documentation or in code comments) that the method is part of the supported API. Reasons why an author may want to name supported methods with an underscore prefix might include:
- backwards compatibility with older versions where it was not supported; or
- the method is supported because it’s useful for subclassing, but the author doesn’t want it to be exposed to "normal users".
In python, is it okay to call a private static method outside the class? The class is from an external module, so I can’t move it outside the class, but the method is useful for me.
class Vector:
@staticmethod
def _add(a,b):
return a + b
# is it okay to do:
Vector._add(1,2)
By "is it okay", I mean in terms of good practices/PEP guidelines.
Generally speaking in languages without proper method privacy, such as Python and Perl, an underscore prefix in a method name is an indication that the author of the class does not want you to call that method.
That goes for use outside the class, in subclasses, in related classes, etc.
The exception to that would be if the author has explicitly documented (either as part of the class’s formal documentation or in code comments) that the method is part of the supported API. Reasons why an author may want to name supported methods with an underscore prefix might include:
- backwards compatibility with older versions where it was not supported; or
- the method is supported because it’s useful for subclassing, but the author doesn’t want it to be exposed to "normal users".