[Sugar-devel] Correct use of leading underscores in Python?

Tomeu Vizoso tomeu at sugarlabs.org
Mon Jul 20 12:23:13 EDT 2009


On Mon, Jul 20, 2009 at 17:59, Jim Simmons<nicestep at gmail.com> wrote:
> I don't want to start a religious war here, but I could use some
> guidance.  In writing my Activities I have often copied and pasted
> bits of code from other Activities.  For instance, the toolbars from
> Read and Speak.  As a result of this I have code in which leading
> underscores are used in both variable names and method names, with no
> particular rhyme or reason for it.  I want my code to follow good
> practices, but the only thing I've found which talks about leading
> underscores in Python is the PEP 8 style guide, which says:
>
> "In addition, the following special forms using leading or trailing
> underscores are recognized (these can generally be combined with any
> case convention):
>
> - _single_leading_underscore: weak "internal use" indicator.  E.g.
> "from M import *" does not import objects whose name starts with an
> underscore."
>
> and also
>
> "Use one leading underscore only for non-public methods and instance variables."
>
> None of the leading underscores in my code seem to be for these reasons.
>
> So when do you use leading underscores to name something?  Or do you
> ever use them?

All code in Sucrose has to follow these rules, if they don't, they are
in violation of the law. But modules out of Sucrose follow their own
rules.

In more practical terms, when you code a class, by using a leading
underscore or not you are defining its public API. And if you use
another class and use methods or variables with a leading underscore,
you are using private API that is more bound to be broken in
subsequent releases.

Also, by defining what is public and what is private, you are making a
clear distinction between the what and the how, which helps greatly in
readability and general maintainability.

Regards,

Tomeu

> Thanks,
>
> James Simmons
> _______________________________________________
> Sugar-devel mailing list
> Sugar-devel at lists.sugarlabs.org
> http://lists.sugarlabs.org/listinfo/sugar-devel
>


More information about the Sugar-devel mailing list