Replacement for lambda - 'def' as an expression?
Terry Reedy
tjreedy at udel.edu
Tue Sep 6 14:56:17 EDT 2005
"talin at acm dot org" <viridia at gmail.com> wrote in message
news:1125996559.130055.154400 at z14g2000cwz.googlegroups.com...
> Of course, one can always create a named function. But there are a lot
> of cases, such as multimethods / generics and other scenarios where
> functions are treated as data, where you have a whole lot of functions
> and it can be tedious to come up with a name for each one.
Either reuse names or 'index' them: f0, f1, f2, ...
> add = def( a, b ):
> return a + b
The difference between this and def add(a,b): return a+b would be the
finding of .func_name to an uninformative generic tag (like '<lambda.>')
versus the informative 'add'.
>I need to be able to assign a block of Python code to a particular
>pattern,
How about (untested -- I have never actually written a decorator, and am
following a remembered pattern of parameterized decorators) :
patcode = {}
def pat(pattern): # return decorator that registers f in patcode
def freg(f):
f.func_name = 'pat: <%s>' % pattern # optional but useful for debug
patcode[pattern] = f
# no return needed ? since def name is dummy
return freg
@pat('pattern1')
def f(): <code for pattern 1>
@pat('pattern2')
def f(): <code> for pattern 2>
etc
or define freg(f,pat) and call freg *after* each definition
> having to invent a named function for each pattern is a burden :)
But you do not *have to* ;-)
or rather, you can replace func_name with a useful tag as suggested above.
Terry J. Reedy
More information about the Python-list
mailing list