generator expressions: performance anomaly?

Bengt Richter bokr at oz.net
Tue Jan 18 22:00:05 EST 2005


On Tue, 18 Jan 2005 17:38:20 -0700, Steven Bethard <steven.bethard at gmail.com> wrote:

>Bengt Richter wrote:
>> Which make me wonder what plans there are for providing a better
>> mechanism than default arguments as a way of initializing local function
>> variables. Nested def's to create a closure with initialized values is
>> pretty crufty for that, IMO.
>
>What about using a class?  Associating functions with data is pretty 
>much what they're for...
>
>> Maybe extending the default argument space
>> with whatever comes after e.g. a triple star delimiter in the argument list,
>> but which wouldn't be counted as part of the normal arguments? E.g.,
>> 
>>     def foo(x, y=123, *args, **kw, *** i=1, deftime=time.ctime()):
>>         return x*y, kw.get('which_time')=='now' and time.ctime() or deftime
>
>If what you want is to have i=1 and deftime=time.ctime() available 
>within foo, you could do something like (untested):
>
>class foo(object):
>     def __init__(self):
>         self.i = 1
>         self.deftime = time.ctime()
>     def __call__(self, x, y=123, *args, **kwds):
>         return x*y, (kw.get('which_time') == 'now'
>                      and time.ctime() or self.deftime)
>foo = foo()
Total: 8 lines, much irrelevant cruft.

>
>Or if you don't like 'foo = foo()', you could probably abuse the __new__ 
>method (also untested):
>
>class foo(object):
>     i = 1
>     deftime = time.ctime()
>     def __new__(cls, x, y=123, *args, **kwds):
>         return x*y, (kw.get('which_time') == 'now'
>                      and time.ctime() or self.deftime)
Total: 6 lines, newbie-unfriendly abuse of __new__ ;-)

>
>I guess my point is that if you want attribute associated with the 
>function, it's often easy enough to write a class instead...
vs. 2 easy lines with minimal irrelevant cruft ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list