[Python] Is it bad practice NOT to use private methods and functions in Python?

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    Background


    A few weeks ago, I completed a technical test in Python. While the overall feedback from the test was very positive, one of the things I was surprised to read in the feedback was:


    No encapsulation – plenty of public_functions which should be _private_functions
    ​

    This surprised me because - according to the vague picture I'd built up in the back of my mind over my two years as a Python developer - we don't really do private methods or functions in Python. All that we do have is a patchwork of conventions, shorthand and gentleman's agreements. But is that picture in the back of my mind correct?

    Underscores and Double Underscores


    So I've looked into the matter a little more deeply, consulting the standard Python documentation as well as PEP 8, and I've come to the following conclusions:

    1. The use of a double underscore before a class attribute invokes name mangling, i.e. __spam will be interpreted as _classname__spam. This can be used to emulate a crude kind of privacy, such that if one tries to call __spam from outside of its class, an exception will be raised.
    2. The programmer can use a single underscore to indicate that a function (or similar) is private, but this seems to have little syntactic effect. PEP 8 mentions that _single_leading_underscore will not be imported when from M import * is called, but I couldn't find anything else.

    However, this only tells me what I could do, not what I should do.

    What I Want to Know


    Can I write off the above feedback as coming from someone who's probably spent his professional life programming in Java/C#/etc, and therefore doesn't have the correct mindset when it comes to encapsulation in Python? Or should I re-think the way I write Python programs, so that any encapsulation is much more explicit?

    Continue reading...

Compartilhe esta Página