473,774 Members | 2,248 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Lambda going out of fashion

Hi guys,

I'm a little worried about the expected disappearance of lambda in
python3000. I've had my brain badly broken by functional programming
in the past, and I would hate to see things suddenly become harder
than they need to be.

An example of what I mean is a quick script I wrote for doing certain
actions based on a regexp, which I will simlify in this instance to
make the pertanant points more relevent.

{
'one': lambda x:x.blat(),
'two': lambda x:x.blah(),
}.get(someValue , lambda x:0)(someOtherV alue)

The alternatives to this, reletively simple pattern, which is a rough
parallel to the 'switch' statement in C, involve creating named
functions, and remove the code from the context it is to be called
from (my major gripe).

So, the questions I am asking are:
Is this okay with everyone?
Does anyone else feel that lambda is useful in this kind of context?
Are there alternatives I have not considered?

merrily-yr's
Stephen.
Jul 18 '05
63 3415
Terry Reedy wrote:
Ok, add 'assuming that func and args are a valid callable and sequence
respectively.' Error messages are not part of the specs, and may change
for the same code from version to version.
While true, the difference in error messages suggests that the
two approaches use slightly different and possibly exploitable
mechanisms.
To be equivalent to len(*blah), this should be apply(len, blah), no *.


Oops. Here's one that really works. I have an idea of why
there's a difference but would rather someone explain it to me.

import traceback

def YieldTest():
yield "Test"

class Blah:
__len__ = None
__iter__ = YieldTest().__i ter__

func = len
args = Blah()

try:
print "apply", apply(func, args)
except TypeError, err:
print "does not work:", err
try:
print "call", func(*args)
except TypeError, err:
print "does not work:", err

The output from running it under Python 2.3 is

apply 4
call does not work: len() takes exactly one argument (0 given)

If I make Blah be a new-style class (ie "class Blah(object):")
I get the opposite success behavior:

apply does not work: apply() arg 2 expected sequence, found Blah
call 4

Andrew
da***@dalkescie ntific.com

Jul 18 '05 #51
Python 2.4 interactive session:
Py> class Blah:
.... def __iter__(self):
.... yield "Test"
....
Py> args = Blah()
Py> apply(len, args)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: apply() arg 2 expected sequence, found instance
Py> len(*args)
4
Py> class Blah(object):
.... def __iter__(self):
.... yield "Test"
....
Py> args = Blah()
Py> apply(len, args)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: apply() arg 2 expected sequence, found Blah
Py> len(*args)
4
And you're right, there is a behavioural difference - apply() expects a real
sequence, whereas the extended function call syntax accepts any iterable.

However, there's also a bug in your demo code:

Py> def YieldTest():
.... yield "Test"
....
Py> x = YieldTest().__i ter__
Py> list(x())
['Test']
Py> list(x())
[]

Your failing case with len(*args) was due to the iterator having already been
consumed :)

Cheers,
Nick.
--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #52
Nick Coghlan wrote:
And you're right, there is a behavioural difference - apply() expects a real
sequence, whereas the extended function call syntax accepts any iterable.

However, there's also a bug in your demo code:


I guess I must be getting over this cold -- I'm only 1/2 wrong
this time. :)

Andrew
da***@dalkescie ntific.com

Jul 18 '05 #53
In article <ma************ *************** ***********@pyt hon.org>,
Fredrik Lundh <fr*****@python ware.com> wrote:

(I've said it before, and I'll say it again: native unicode and
generators are the only essential additions I've seen since 1.5.2, with
properties and sub-classable C types sharing a distant third place.
the rest of the stuff has had zero impact on my ability to write solid
code in no time at all, and negative impact on my ability to download
stuff that others have written and expect it to work in any Python
version but the latest...)


Hmmm... I find code much more readable and writable now that apply() is
going away. And unless you mean "generator" to include iterators in
general, I believe that iterators are another critical addition.

I'm surprised that you don't include garbage collection and augmented
assignment, though. String methods have been a net gain, I think.

Reviewing the various What's New documents, it appears that we really
have been holding the line since 2.2 on language changes.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing." --Alan Perlis
Jul 18 '05 #54
Aahz wrote:
(I've said it before, and I'll say it again: native unicode and
generators are the only essential additions I've seen since 1.5.2, with
properties and sub-classable C types sharing a distant third place.
the rest of the stuff has had zero impact on my ability to write solid
code in no time at all, and negative impact on my ability to download
stuff that others have written and expect it to work in any Python
version but the latest...)


Hmmm... I find code much more readable and writable now that apply() is
going away. And unless you mean "generator" to include iterators in
general, I believe that iterators are another critical addition.

I'm surprised that you don't include garbage collection and augmented
assignment, though. String methods have been a net gain, I think.


garbage collection is a CPython implementation detail, not a language
property (it's a nice implementation detail, sure).

and we had iterators before we got the iterator protocol; the protocol made
things slightly more convenient, but it didn't enable you to do anything you
couldn't do before (using __getitem__ instead of __next__). generators are
something entirely different. writing inverted code is hard; yielding is trivial.

func(*arg) instead of apply() is a step back -- it hides the fact that functions
are objects, and it confuses the heck out of both C/C++ programmers and
Python programmers that understand the "def func(*arg)" form, because it
looks like something it isn't (there's a false symmetry between the call-form
and the def-form).

and I still do enough 1.5.2-programming to use "x = x + y"; when I find
myself in a situation where my code would benefit a lot from being able to
write "x += y" instead, I go back and fix the design.

string methods are nice, but nothing groundbreaking, and their niceness is
almost entirely offset by the horrid "".join(seq ) construct that keeps popping
up when people take the "the string module is deprecated" yada yada too
seriously. and what do the python-devers do? they add a "sum" built-in,
but no "join"? hello?

</F>

Jul 18 '05 #55
In article <ma************ *************** ***********@pyt hon.org>,
"Fredrik Lundh" <fr*****@python ware.com> wrote:
func(*arg) instead of apply() is a step back
Strongly disagree. I find func(*args) much more readable than
apply(func, args).
-- it hides the fact that functions are objects,
What does this have to do with anything?
and it confuses the heck out of both C/C++ programmers and
Python programmers that understand the "def func(*arg)" form, because it
looks like something it isn't (there's a false symmetry between the call-form
and the def-form).
What's false about the symmetry?

Call: you supply a sequence of args
Def: you receive a sequence of args

Lovely.
and I still do enough 1.5.2-programming to use "x = x + y"; when I find
myself in a situation where my code would benefit a lot from being able to
write "x += y" instead, I go back and fix the design.

string methods are nice, but nothing groundbreaking, and their niceness is
almost entirely offset by the horrid "".join(seq ) construct that keeps
popping
up when people take the "the string module is deprecated" yada yada too
seriously. and what do the python-devers do? they add a "sum" built-in,
but no "join"? hello?


That's what you get for unsubscribing ;-)

Just
Jul 18 '05 #56
In article <ma************ *************** ***********@pyt hon.org>,
Fredrik Lundh <fr*****@python ware.com> wrote:

func(*arg) instead of apply() is a step back -- it hides the fact
that functions are objects, and it confuses the heck out of both
C/C++ programmers and Python programmers that understand the "def
func(*arg)" form, because it looks like something it isn't (there's a
false symmetry between the call-form and the def-form).
For me, it works the other way around, but I can see how you perceive it
that way.
and I still do enough 1.5.2-programming to use "x = x + y"; when I find
myself in a situation where my code would benefit a lot from being able
to write "x += y" instead, I go back and fix the design.
Okay, it wasn't clear in your original post that you're still stuck with
1.5.2. That makes a huge difference in the convenience of newer
features.
string methods are nice, but nothing groundbreaking, and their niceness
is almost entirely offset by the horrid "".join(seq ) construct that
keeps popping up when people take the "the string module is deprecated"
yada yada too seriously. and what do the python-devers do? they add a
"sum" built-in, but no "join"? hello?


While I'm in complete agreement about the "".join() construct on the
basis of looks, I have come to appreciate the fact that I *never* mess up
the order of arguments any more.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing." --Alan Perlis
Jul 18 '05 #57
On 2004-12-26, Fredrik Lundh <fr*****@python ware.com> wrote:
string methods are nice, but nothing groundbreaking, and their niceness is
almost entirely offset by the horrid "".join(seq ) construct that keeps popping
up when people take the "the string module is deprecated" yada yada too
seriously. and what do the python-devers do? they add a "sum" built-in,
but no "join"? hello?


I happen to not mind the ''.join syntax, but if I did, I would use

str.join('', seq)

which is just like a join builtin except that it's not as easy to make
it work on pre-string-method Pythons.
Jul 18 '05 #58
aa**@pythoncraf t.com (Aahz) writes:
While I'm in complete agreement about the "".join() construct on the
basis of looks, I have come to appreciate the fact that I *never* mess up
the order of arguments any more.


Yeah. When I needed joinable arrays of strings in Eiffel, I added them
to the ARRAY[STRING] class. array.join("") is *much* saner looking.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05 #59
Dima Dorfman wrote:
I happen to not mind the ''.join syntax, but if I did, I would use

str.join('', seq)

which is just like a join builtin except that it's not as easy to make
it work on pre-string-method Pythons.


just like join, except that it isn't:
string.join(seq , sep) u'axbxc' sep.join(seq) u'axbxc' str.join(sep, seq)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: descriptor 'join' requires a 'str' object but received a 'unicode'

</F>

Jul 18 '05 #60

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

53
3696
by: Oliver Fromme | last post by:
Hi, I'm trying to write a Python function that parses an expression and builds a function tree from it (recursively). During parsing, lambda functions for the the terms and sub-expressions are constructed on the fly. Now my problem is lazy evaluation. Or at least I think it is. :-)
2
1796
by: Skip Montanaro | last post by:
Stephen> { Stephen> 'one': lambda x:x.blat(), Stephen> 'two': lambda x:x.blah(), Stephen> }.get(someValue, lambda x:0)(someOtherValue) One thing to remember is that function calls in Python are pretty damn expensive. If x.blat() or x.blah() are themselves only one or two lines of code, you might find that your "switch" statement is better written as an if/elif/else statement. You're making potentially three function calls (get(),...
26
3504
by: Steven Bethard | last post by:
I thought it might be useful to put the recent lambda threads into perspective a bit. I was wondering what lambda gets used for in "real" code, so I grepped my Python Lib directory. Here are some of the ones I looked, classified by how I would rewrite them (if I could): * Rewritable as def statements (<name> = lambda <args>: <expr> usage) These are lambdas used when a lambda wasn't needed -- an anonymous function was created with...
181
8913
by: Tom Anderson | last post by:
Comrades, During our current discussion of the fate of functional constructs in python, someone brought up Guido's bull on the matter: http://www.artima.com/weblogs/viewpost.jsp?thread=98196 He says he's going to dispose of map, filter, reduce and lambda. He's going to give us product, any and all, though, which is nice of him.
0
9621
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10267
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
7463
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6717
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4012
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3611
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2852
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.