Borg - is that a singleton?

Alex Martelli aleax at aleax.it
Sun Mar 2 10:37:52 EST 2003


Graham Fawcett wrote:

> Alex Martelli <aleax at aleax.it> wrote in message
> news:<T5Z7a.253209$0v.7059112 at news1.tin.it>...
>> 
>> Too much work!  Just:
>> 
>> class Foo(Borg): _shared_state = {}
>> 
>> > class Bar:
>> >     __shared_state = {}
>> >     def __init__(self):
>> >         self.__dict__ = self.__shared_state
>> 
>> Ditto: just
>> 
>> class Bar(Borg): _shared_state = {}
> 
> Beautiful!

Yep, Python's "data overriding" feature sure IS -- and is why one
should think twice about it before using a leading DOUBLE underscore
rather than a single one, and almost always access class attributes
as self.attname (so that subclasses can override them easily).

I've fallen into both traps -- accessing a class attribute as
Theclass.attname and ensuring against clashes by naming it __att
are both rather natural things.  There's no real workaround (except
correcting the accessing code) for the former, though for the
latter one MIGHT workaround it by using _Borg__shared_state in
the subclasses (it's just a tad ugly, but it does work...).


Alex





More information about the Python-list mailing list