generator expressions: performance anomaly?

Steven Bethard steven.bethard at gmail.com
Tue Jan 18 19:38:20 EST 2005


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()

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)

I guess my point is that if you want attribute associated with the 
function, it's often easy enough to write a class instead...

Steve



More information about the Python-list mailing list