[Sugar-devel] Correct use of leading underscores in Python?
Tomeu Vizoso
tomeu at sugarlabs.org
Tue Jul 21 03:46:07 EDT 2009
On Tue, Jul 21, 2009 at 00:52, Martin Dengler<martin at martindengler.com> wrote:
> On Mon, Jul 20, 2009 at 10:59:05AM -0500, Jim Simmons 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."
>
> Did you miss the following points on double leading underscores?
>
> - __double_leading_underscore: when naming a class attribute,
> invokes name
> mangling (inside class FooBar, __boo becomes _FooBar__boo; see
> below).
This is actually important in Sugar, we use double leading underscores
for signal handlers because a subclass that listens to the same signal
could inadvertently override the parent's handler and lead to very
difficult to debug problems, ex.: __button_clicked_cb
Regards,
Tomeu
> - __double_leading_and_trailing_underscore__: "magic" objects or
> attributes that live in user-controlled namespaces.
> E.g. __init__,
> __import__ or __file__. Never invent such names; only use them
> as documented.
>
> IMO:
>
> - one leading underscore is "private" ("weak internal use") or, in
> the context of inheritance, like java's "protected" (private to a
> class and its subclasses but can be / is expected to be overridden).
>
> - two leading underscores is "extra private" ("strong internal use")
> or, in the context of inheritance, like java's "private" (private to
> a class and not visible to subclasses without good,
> you-better-know-why-you're-thumbing-your-nose-at-name-mangling
> reasons).
>
>> So when do you use leading underscores to name something? Or do you
>> ever use them?
>
> They're used a lot by python code. One should almost certainly be
> using them in code that's used by other code.
>
>> Thanks,
>>
>> James Simmons
>
> Martin
>
> _______________________________________________
> 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