anonymous functions? class?
jeff at ccvcorp.com
Fri Nov 16 18:54:34 CET 2001
Duncan Booth wrote:
> Erik Max Francis <max at alcyone.com> wrote in
> news:3BF4288A.FC68121F at alcyone.com:
> > Yes. Python has lambda functions for this, although there are some
> > restrictions: lambda functions have to take at least one argument
> > (otherwise what's the point), and they can only evaluate to expressions,
> > rather than whole statements.
> Your second point is correct, but the first one is wrong. You can have a
> lambda with no arguments if you wish. The point is the same as any function
> with no arguments, if it calls other functions which use globals (or nested
> scope variables) or have side effects, then the lamda doesn't access the
> globals or produce the side effects until it is invoked.
> f = open('somefile')
> readchop = lambda: f.readline()[:-1]
> for i in range(10): print readchop()
> is a not terribly good example.
Neither does simply putting the code inline, it seems to me. I realize that
this is an extremely simplified example, but I don't see this as being at all
preferable to simply using
f = open('somefile')
for i in range(10): print f.readline()[:-1]
This has exactly the same semantics, and unless I'm mistaken, it's impossible
for an argument-less lambda to have different semantics than straight
substitution, at least in these days of nested scopes (which your example
Of course, I've always thought of lambdas as being confusing and less clear
than simply defining a (possibly nested) function anyhow, and never understood
how being nameless gave it an advantage.
More information about the Python-list