0

I'm developing a module in Python which should be used by others users in my project. I came to a problem that I couldn't find a good answer:

How do I hide a method of an object from users, but I want to use it in other objects (different class).

By hiding it I mean indicating that shouldn't be used by them.

As far I understand it is not a clear usage of an underscore before the function because that indicates that the method is protected and shouldn't be used by objects of other classes.


EDIT: To clarify, the PEP-8 says:

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

Does this "internal use" implies internal use of object/class or internal use of the module? If I put an underscore in this function, would that be a "good" design decision?

(Thanks for the comments)

Community
  • 1
  • 1
  • 7
    If you prefix it with an underscore, you are discouraging other users from using it, but you can still call it from places that you know it is appropriate. Is that not enough? – khelwood Feb 16 '18 at 14:18
  • 2
    A single leading underscore is just a convention to indicate private or protected access. But it doesn't actually prevent you from using those members. – 0x5453 Feb 16 '18 at 14:19
  • Possible duplicate of [What is the meaning of a single- and a double-underscore before an object name?](https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-a-single-and-a-double-underscore-before-an-object-name) – roganjosh Feb 16 '18 at 14:20
  • 1
    Possible duplicate of https://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private – jlandercy Feb 16 '18 at 14:26
  • 3
    Possible duplicate of [Why are Python's 'private' methods not actually private?](https://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private) – jlandercy Feb 16 '18 at 14:26
  • If you really want to hide a method you can create a Cython extension with a cdef method. Take note, that there is no need to use any C semantics in Cython extensions, so it might as well be an exact copy of your class, except for `cdef`. – Eli Korvigo Feb 16 '18 at 14:27
  • 3
    It is common in python for users to interface with objects that have protected members or methods, so I think most users will get the hint. If they use it and screw things up, that is on them and not a flaw with your API as you gave a very clear hint not to use the method. – Garrett Gutierrez Feb 16 '18 at 14:32

0 Answers0