lambda
Roman Suzi
rnd at onego.ru
Thu May 24 08:30:48 EDT 2001
On Thu, 24 May 2001, Alex Martelli wrote:
> "Duncan Booth" <duncan at NOSPAMrcp.co.uk> wrote in message
> news:Xns90AB6AF2DA789duncanrcpcouk at 127.0.0.1...
> > Laura Creighton <lac at cd.chalmers.se> wrote in
> > news:mailman.990635563.6483.python-list at python.org:
> > > If I had just used w.grid up there I would get a yellow button with
> > > pink text. This form is concise. What do the lambda dislikers
> > > suggest I do instead? (This is a serious question)
> >
> > If you are using Python 2.1, then the lambda form becomes much neater:
>
> ...but so does the named-function form, equally -- see my latest
> post in this thread. Nested scopes apply in just the same way to
> lambda's and to normal (named) nested functions.
>
> As was noted in another post, nested scopes don't let you REBIND
> the local variables of the function you're nested in -- lambdas
> can't rebind anything anyhow, of course -- well I guess one COULD
> use an elegant and readable construct such as:
>
> lambda x: setattr(sys.module[__name__], 'k', k+x) or k
If counters are so common in the application in question, why not to:
class counter:
def __init__(self, start=0):
self._counter = start
def __call__(self, delta=1):
self._counter = self._counter + delta
return self._counter
bc = counter()
lambda x, ...: F(bc(x), ...) # where F() does something useful
Counter logic may be more complicated than just addition. For example,
counting Parts, Chapters, etc of a book could be more complex. Even LaTeX
has special macros for counters.
Its more safe to have global objects than global counters. I had
situations where I messed things up because of global variables. That is
why I think counters must be part of the object, where counting occurs:
this way one may be sure about counter's initialization and such.
For example, I have a script to index thumbernails of images (it also
counts them of course.) And I had an error in it when I forgot to
initialize counters/data accumulators before processing next web-page...
> to get an unnamed equivalent of
>
> def adder(x):
> global k
> k += x
> return k
>
> but then the PSU might
Sincerely yours, Roman A.Suzi
--
- Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru -
More information about the Python-list
mailing list