Simple prototyping in Python

Bengt Richter bokr at oz.net
Sun May 2 23:57:35 EDT 2004


On Mon, 03 May 2004 02:31:53 -0000, Dave Benjamin <ramen at lackingtalent.com> wrote:

>In article <c74830$hrfbu$1 at ID-169208.news.uni-berlin.de>, Greg Ewing wrote:
>> Dave Benjamin wrote:
>>> Hey, I never knew that "this" could be used inside of an anonymous object
>>> in JavaScript. Thanks for pointing that out!
>>> 
>>> In Python, you'd have to give the object a name, since there's no "self" to
>>> refer to.
>> 
>> No, you wouldn't, because the Python equivalent would
>> be something like
>> 
>> def F():
>>    c = [105]
>> 
>>    class C:
>>      a = 5
>> 
>>      def incr(self):
>>        self.a += 1
>>        c[0] += 1
>>        return [self.a, c[0]]
>> 
>>    return C()
>
>I don't know if I'd call it equivalent. Similar in effect, naybe, but the
>idea was to create an anonymous, classless object.

Anonymous follows, though not classless ;-)

 >>> o=type('',(),{'incr':lambda s: setattr(s,'a',getattr(s,'a',5)+1) or getattr(s,'a')})()
 >>> o.incr()
 6
 >>> o.incr()
 7
 >>> o.incr()
 8

 Or perhaps better, using the class variable as initial value as Greg is doing above:

 >>> o=type('',(),{'a':5,'incr':lambda s: setattr(s,'a',getattr(s,'a')+1) or getattr(s,'a')})()
 >>> o.incr()
 6
 >>> o.incr()
 7
 >>> o.incr()
 8

You could also concoct a bound method operating on the variable held in a list

 >>> oincr = (lambda s:s.__setitem__(0,s[0]+1) or s[0]).__get__([5], list)
 >>> oincr()
 6
 >>> oincr()
 7
 >>> oincr()
 8

Or perhaps more cleanly, just subclass list and instantiate with initial value:

 >>> o = type('',(list,),{'incr':lambda s:s.__setitem__(0,s[0]+1) or s[0]})([5])
 >>> o.incr()
 6
 >>> o.incr()
 7

This stuff is fun for exploring ins and outs of the language, but
readable is best, if there's a readable alternative ;-)


>
>> It's a bit more awkward in Python due to the inability to
>> directly rebind a name in an outer scope.
>
Yes, I wouldn't mind more and cleaner control of binding and evaluation,
as to when and where (e.g. read time, def time, call time and
local binding vs find-and-rebind in lexically nested or mro name spaces).

>This is an issue, but not a serious one. In my original example, I used a
>pretty simple workaround (an anonymous object).
>
OTOH, if something strikes you as a workaround, it's not something you want
to be struck with regularly ;-)

>> BTW, IMO this is a seriously warped technique that I
>> would never use, even in Javascript. I can't see any
>> benefit in it that's anywhere near worth the obfuscation.
>
>One benefit, which applies equally to both languages, is that this technique
>gets you closer to enforced private attributes than the standard ways of
>making objects. I'm sure you could hack frames or something, but "c" is
>pretty much inaccessible to the casual programmer in your example above.
>
Gotta go.

Regards,
Bengt Richter



More information about the Python-list mailing list