[Sugar-devel] Correct use of leading underscores in Python?
Martin Dengler
martin at martindengler.com
Mon Jul 20 18:52:29 EDT 2009
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).
- __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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://lists.sugarlabs.org/archive/sugar-devel/attachments/20090720/bcb330d7/attachment.pgp
More information about the Sugar-devel
mailing list