[Tutor] under, under

eryksun eryksun at gmail.com
Mon May 13 23:47:17 CEST 2013


On Mon, May 13, 2013 at 1:18 PM, Dave Angel <davea at davea.name> wrote:
> Underscores aren't anything special to the Python language itself, whether
> leading or trailing.

I'm pretty sure you were just talking about dunder, dunder.
Underscores in general do have special uses in the language. They're
used to enable name mangling and to implicitly control star imports.

In a class definition, a leading dunder without a trailing dunder
enables name mangling with the class name:

    class Bar:
        def foo(self):
            self.__attr = 'spam'

    >>> obj = Bar()
    >>> obj.foo()
    >>> obj._Bar__attr
    'spam'

A subclass with a different name will use a different mangling, so
this provides a semi-private name. The purpose is to protect a private
implementation detail in the base class from being modified by a
subclass, either accidentally or intentionally.  I won't debate the
merits of this. Generally, however, one signals that an attribute is
'private' by using a single leading underscore. This is just a hint to
other programmers.

Name mangling is a compile-time operation. The compiler replaces all
identifiers that have a leading dunder (and no trailing dunder) with
the corresponding mangled name:

    >>> Bar.foo.__code__.co_names
    ('_Bar__attr',)

Another use of underscore is in a star import. To show this, create a module:

    >>> import sys, imp
    >>> sys.modules['mod'] = mod = imp.new_module(name='mod')

Add two global variables to the module, one with a leading underscore:

    >>> mod._foo = 'foo'
    >>> mod.bar = 'bar'

Do a star import. Observe that the name with the leading underscore was skipped:

    >>> from mod import *
    >>> '_foo' in locals()
    False
    >>> 'bar' in locals()
    True

Typically it's better to specify the names used in a star import by
defining __all__:

    >>> mod.__all__ = ['_foo', 'bar']
    >>> from mod import *
    >>> '_foo' in locals()
    True


More information about the Tutor mailing list