[Tutor] Why begin a function name with an underscore

Steven D'Aprano steve at pearwood.info
Wed Aug 29 15:57:12 CEST 2012


On 28/08/12 10:26, Richard D. Moores wrote:
> I've been going through Steven D'Aprano's pyprimes
> (<http://pypi.python.org/pypi/pyprimes/0.1.1a>) and have many
> questions. One is why begin a function name with an underscore. He has
> several functions that do this. Two are:
[...]
> I'm stealing these for their usefulness. But why the underscores?


Single-underscore names are generally the convention for "private"
functions, methods, classes, or other names.

Here, "private" means:

- the function depends on platform-specific features that may not always
   be available;

- the function is experimental, and will become part of the public
   library some day, but not yet;

- the author doesn't want to treat the function as a supported part of
   the library, but only as an internal detail;

- the function is subject to change without notice;

- it is an implementation detail, and may become obsolete if the
   implementation changes;

- or all of the above.


Think of a single leading underscore as the Python equivalent of those
stickers you see on electrical equipment that say "No user-serviceable
parts". If you mess with it, you void your warranty.

Python will not stop you if you use call a library's private functions
from your code, but you can't exactly rely on it. The library author
makes no promise (implied or explicit) that single underscore _functions
will work the way you expect, or still be there in the next version.

There are a few exceptions. For example, the collections.namedtuple type
uses single underscore methods as part of its *public* interface, to
ensure that the namedtuple methods don't clash with the tuple's named
fields. But that's quite unusual.

Also, when you do "from module import *", Python will skip any single
underscore names.



-- 
Steven


More information about the Tutor mailing list