Prothon Prototypes vs Python Classes

Joe Mason joe at notcharles.ca
Mon Mar 29 09:50:10 EST 2004


In article <mailman.55.1080568422.20120.python-list at python.org>, Jeff Epler wrote:
>> BTW, I've got three pure-python solutions now (four when this one's
>> fixed) but it turns out they all suffer from a flaw:
>> 
>> >>> class TestProto: l = []
>> ... 
>> >>> class Test2(TestProto): pass
>> ... 
>> >>> TestProto.l
>> []
>> >>> Test2.l
>> []
>> >>> Test2.l.append(0)
>> >>> Test2.l
>> [0]
>> >>> TestProto.l
>> [0]
>> 
>> We really need copy-on-write lists and dicts - and large objects in
>> general - for this to work.
> 
> Can't you just follow the Python rule for classes with a little
> difference?
> * if you want some data to be shared by reference among the Prototype
>   and all its children, declare it at 'prototype' ('class') scope
> * if you don't, create it in __init__

Possibly.  You need something, at least - full copy-on-write seems like
the most transparent, but also the most work to set up.  (I'm still
reading up on Self and others to find out how they handle these things.)

Hmm, your method sounds like it would work.  In fact, I guess it would
already do that as written, wouldn't it?

The use case I was thinking of was something like this (I'm going to use
"object" instead of "class" from now on for pseudocode):

    object UrlDispatcher:

        def __init__(self):
            self.handlers = { "http:" : HttpHandler, "ftp:" : FtpHandler }

    object SSLUrlDispatcher(UrlDispatcher):

        def __init__(self):
            UrlDispatcher.__init__(self)
            self.handlers["https:"] = SSLHttpHandler

So each instance of URLDispatcher and descendants has its own, entirely
unshared copy of handlers.  One drawback of this is that if you add a
handler to UrlDispatcher at runtime, it isn't inherited by clones that
have already been initialized.

The other approach I suggested - replacing lists and dicts in
prototype-baed objects with a customized version - could make this more
transparent.  Say, look up the value in SSLUrlDispatcher.handlers, then
UrlDispatcher.handlers only if not found, and only then throw an error
if the key still isn't found.  The question is whether it's useful to
put this complexity in the prototype system, or just provide classes
that do this in a library (which can just be done by third parties as
needed) and give coders the option of saying "handlers = ProtoDict()"
instead of "handlers = {}".

Joe



More information about the Python-list mailing list