Private identifiers - naming

Richard Taylor rjt-usenet at thegrindstone.me.uk
Thu May 6 12:33:07 EDT 2004


Peter Hansen wrote:

> Heiko Wundram wrote:
> 
>> Am Donnerstag, 6. Mai 2004 16:00 schrieb Sridhar R:
>> 
>>>Any thoughts?
>> 
>> If you find "__varname" difficult to read, don't use it. Python doesn't
>> hide (try a dir(<instance>)) or protect access to these variables anyway,
>> so you actually gain nothing using this syntax if it makes it cryptic for
>> you.
> 
> Actually, using __varname causes the compiler to munge the name so that
> it is actually _ClassName__varname, to allow subclasses to use the same
> name without stepping on the parent class' variable of that name.  So
> cryptic or not, you actually _do_ gain something if, for example, you
> are trying to write a library for reuse and don't want to have to
> document all the attributes which are used internally, just to make sure
> nobody inadvertently defines a subclass which uses the same name and
> buggers up the works.
> 
> It's not about _preventing_ such access, just protecting against
> casual/accidental collisions.
> 
> -Peter

If that is what you are trying to do then I would be explicit about it.

        class C:
          def method(self):
            self._C_id = True

At least then it is clear what the identifier is called and a sub class that
'really' wants to mess with it can do so explicitly. Compiler name mangling
is a really pain for readability. Not every one will remember that the
compiler is doing it and sub class authors may become confused.

Better to use something like pychecker to pick up possible name clashes.

Richard




More information about the Python-list mailing list