9.6 Private Variables

There is limited support for class-private identifiers. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is now textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard of the syntactic position of the identifier, so it can be used to define class-private instance and class variables, methods, as well as globals, and even to store instance variables private to this class on instances of other classes. Truncation may occur when the mangled name would be longer than 255 characters. Outside classes, or when the class name consists of only underscores, no mangling occurs.

Name mangling is intended to give classes an easy way to define ``private'' instance variables and methods, without having to worry about instance variables defined by derived classes, or mucking with instance variables by code outside the class. Note that the mangling rules are designed mostly to avoid accidents; it still is possible for a determined soul to access or modify a variable that is considered private. This can even be useful, e.g. for the debugger, and that's one reason why this loophole is not closed. (Buglet: derivation of a class with the same name as the base class makes use of private variables of the base class possible.)

Notice that code passed to exec, eval() or evalfile() does not consider the classname of the invoking class to be the current class; this is similar to the effect of the global statement, the effect of which is likewise restricted to code that is byte-compiled together. The same restriction applies to getattr(), setattr() and delattr(), as well as when referencing __dict__ directly.

Here's an example of a class that implements its own __getattr__ and __setattr__ methods and stores all attributes in a private variable, in a way that works in Python 1.4 as well as in previous versions:

class VirtualAttributes:
    __vdict = None
    __vdict_name = locals().keys()[0]
     
    def __init__(self):
        self.__dict__[self.__vdict_name] = {}
    
    def __getattr__(self, name):
        return self.__vdict[name]
    
    def __setattr__(self, name, value):
        self.__vdict[name] = value

guido@python.org