473,750 Members | 2,669 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Multi-line lambda proposal.

I've been reading the recent cross-posted flamewar, and read Guido's
article where he posits that embedding multi-line lambdas in
expressions is an unsolvable puzzle.

So for the last 15 minutes I applied myself to this problem and come up
with this off-the-wall proposal for you people. Perhaps this idea has
been proposed before, I don't know.

The solutions I have seen all assume that the lambda must be completely
inlined within the expression: the expression is interrupted by the
lambda, which is then completely specified (arguments and body) and the
expression somehow continues (and this is where syntactic problems
occur, giving rise to un-Python-like repugnancies).

But suppose that the expression and the multi-line lambda body are
reordered? That is to say, the expression is written normally, and the
mlambda expressions in it serve as /markers/ indicating that body
material follows. This results in the most Python-like solution.

Suppose lambda() occurs without a colon

a = lambda(x, y), lambda(s, t), lambda(u, w): u + w
statement1
statement2
lambda:
statement3
statement4

The first two lambdas do not have a colon after them. This means that
they have multi-line bodies which follow this statement, and there must
be as many bodies as there are lambdas. The third lambda is a regular
one-expression lambda, entirely written right there.

The bodies are made up of the statements which follow. If there is only
one body, it's simply the indented material. If there are two or more
lambdas in the expression, additional bodies are required, introduced
by lambda: statements, which are at the same indentation level as the
expression which contains the lambda markers.

Of course, the bodies have their respective lambda parameters in scope.
So statement1 and statement2 have access to x and y, and statement3 and
statement4 have access to s and t.

Problem solved, with no Python repugnancies.

The way you can embed indented material in an expression is by not
physically embedding it.

If you want to be completely anally retentive, you can require that the
expression which has lambda bodies after it has to be terminated by a
colon:

a = lambda(x, y), lambda(s, t), lambda(u, w): u + w:
statement1
statement2
lambda:
statement3
statement4

If we take out the last two lambdas, this reduces to:

a = lambda(x, y):
statement1
statement2

Here, the colon terminates the lambda-containing statement. It is not
the colon which introduces the body of a one-expression lambda. E.g.:

a = lambda(x, y): x + y

a = lambda(x, y):
return x + y

The two are disambiguated by what follows. You get the picture.

More examples: lambda defined in a function call argument

a = foo(lambda (x, y)):
return x + y

Confusing? Not if you read it properly. "A lambda function is
constructed with arguments x, y and passed to foo, and the result is
assigned to a. Oh, and by the way, the body of the
lambda is: return x + y."

May 9 '06 #1
23 5329
Kaz Kylheku wrote:
I've been reading the recent cross-posted flamewar, and read Guido's
article where he posits that embedding multi-line lambdas in
expressions is an unsolvable puzzle.

So for the last 15 minutes I applied myself to this problem and come up
with this off-the-wall proposal for you people. Perhaps this idea has
been proposed before, I don't know.


Well, ask yourself, what is the complexity, and what is the
benefit. You are solving a problem that causes very little
pain, and introducing a mechanism that is likely to inspire
thousands of lines of unmaintainable code. Essentially, a
rule that says, "if it is not a simple expression, pick a
name for it" is just not a bad idea.

--Scott David Daniels
sc***********@a cm.org
May 9 '06 #2
Kaz Kylheku wrote:
But suppose that the expression and the multi-line lambda body are
reordered? That is to say, the expression is written normally, and the
mlambda expressions in it serve as /markers/ indicating that body
material follows. This results in the most Python-like solution.


I think your proposal is good, but it might be more easily understood if
we gave names to the lambdas, so that they could be easily picked out in
the source code. It could look something like this:

func(lambda foo):
foo:
print "Foo!"

Come to think of it, maybe we could put the lambdas before the statement
they're used in instead of in front of it. That could look something
like this:

lambda foo:
print "Foo!"
func(lambda foo)

Then again, it would probably be simpler to reuse an existing
block-starting keyword for the purpose. Maybe something like this?

def foo():
print "Foo!"
func(foo)
May 9 '06 #3
Kaz Kylheku enlightened us with:
I've been reading the recent cross-posted flamewar, and read Guido's
article where he posits that embedding multi-line lambdas in
expressions is an unsolvable puzzle.
[...]
a = lambda(x, y), lambda(s, t), lambda(u, w): u + w
statement1
statement2
lambda:
statement3
statement4
I think it's a very ugly solution. If you need multiple lines in your
lambda, use an inner function. If you need a couple of single-line
lambdas and use them in a multi-line expression, assign them to a name
and use that name in their stead.
a = lambda(x, y):
return x + y
And what's the advantage of that above this?

def a(x, y):
return x + y
More examples: lambda defined in a function call argument

a = foo(lambda (x, y)):
return x + y

Confusing? Not if you read it properly. "A lambda function is
constructed with arguments x, y and passed to foo, and the result is
assigned to a. Oh, and by the way, the body of the
lambda is: return x + y."


I think it's very, very ugly. Use inner functions for that. They are a
much cleaner solution than this.

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
May 10 '06 #4
Op 2006-05-09, Scott David Daniels schreef <sc***********@ acm.org>:
Kaz Kylheku wrote:
I've been reading the recent cross-posted flamewar, and read Guido's
article where he posits that embedding multi-line lambdas in
expressions is an unsolvable puzzle.

So for the last 15 minutes I applied myself to this problem and come up
with this off-the-wall proposal for you people. Perhaps this idea has
been proposed before, I don't know.


Well, ask yourself, what is the complexity, and what is the
benefit. You are solving a problem that causes very little
pain, and introducing a mechanism that is likely to inspire
thousands of lines of unmaintainable code. Essentially, a
rule that says, "if it is not a simple expression, pick a
name for it" is just not a bad idea.


Well I guess that seems a good rule of thumb.

The problem is that even a simple "expression " sometimes requires
a name in python or turns it into a more complex function.

Take the following example:

def incr_cnt_by_one (obj):
obj.cnt += 1

IMO that is simple enough not to require a name. But it is almost
impossible to put this behaviour in a lambda. If you do you end
up with something like:

lambda obj: setattr(obj, 'cnt', obj.cnt + 1)
So maybe a general lambda is indeed impossible in python. A pity
IMO, but not that big a deal.

But the limit that certain statements are not expressions makes
that you sometimes require a name even with some simple stuff
like:

def Raise_ValueErro r():
raise ValueError

RegisterErrorFu nction(Raise_Va lueError)

What would be so horrible if we could do the following:

RegisterErrorFu nction(lambda: raise ValueError)

or

treat_all(aList , lambda obj: obj.cnt += 1)

--
Antoon Pardon

May 10 '06 #5
Kaz Kylheku wrote:
But suppose that the expression and the multi-line lambda body are
reordered? That is to say, the expression is written normally, and the
mlambda expressions in it serve as /markers/ indicating that body
material follows. This results in the most Python-like solution.


Unfortunately, while this idea has intuitive appeal, it leaves some
problems to solve; namely, lambdas that occur in expressions embedded
within statement syntax which has body material of its own. For
instance

# lambda defined and immediately called here
if lambda(x)(4) < 0:
print "a"
elif y = 4:
print "b"
else:
print "foo"

Where to stick the lambda body? It's not hard to come up with
straightforward answers, except that they are not particularly
appealing. One rule might be that the lambda bodies have to be placed
immediately after the statement body material, set off by the lambda:
thing. In the case of if/elif/else, they have to be placed behind the
closest suite that follows the expression in the syntax of the
statement:

if lambda(x)(4) < 0:
print "a"
lambda:
return x + 1
elif y = 4:
print "b"
else:
print "foo"

The overall rule is simple and uniform: each suite can have lambda:
clauses. These have to match lambda() occurences in the expression (or
expression list) immediately to the left in the same grammar
production.

On the other hand, some people might find this compromise more
attractive: simply do not allow multi-line lambdas in compound
statements.

May 10 '06 #6
DH
Kaz Kylheku wrote:
I've been reading the recent cross-posted flamewar, and read Guido's
article where he posits that embedding multi-line lambdas in
expressions is an unsolvable puzzle.


To say that multi-line lambda is an unsolvable problem is completely
absurd. Furthermore it has already been solved.
http://wiki.python.org/moin/Alternat...bc7ba581dec6fa
So I agree with you, but I doubt you'll have any luck getting your
proposal or any other multiline lambda proposal accepted into python
anytime soon.
May 10 '06 #7
DH wrote:
Kaz Kylheku wrote:
I've been reading the recent cross-posted flamewar, and read Guido's
article where he posits that embedding multi-line lambdas in
expressions is an unsolvable puzzle.
To say that multi-line lambda is an unsolvable problem is completely
absurd.


Note that the "solution" is understood to entail the BDFL stamp of
approval.

Furthermore it has already been solved. http://wiki.python.org/moin/Alternat...bc7ba581dec6fa

Meh. I think the syntax you linked to would result in gobs of ugly and
unreadable code. I like how the examples are always part of relatively
simple statements ("Look, it's readable!"). Try citing examples of
these statements at work in if conditions, generator expressions, as
default arguments to functions, multiple times in the same statement.
Try showing what they look like nested. The "readable" example would
turn into ASCII vomit.

Probably the day it makes it into Python is the day Python jumps the
shark.
Carl Banks

May 10 '06 #8
multi-line lambdas, had it been added to python a long time ago, would
had reduced a lot of complexity in the language.
for example - with multi-line lambdas - decorators are unneccesary.
just give the multi-line lambda as an argument to a function - no need
for special syntax..
the alternative decorators would also be simpler.
currently when you want to create a "decorator-that-accepts-additional-
arguments" you gotta make a funtion that gets those
additional-arguments and returns a function that will be the decorator.

May 10 '06 #9
Op 2006-05-10, ya*****@gmail.c om schreef <ya*****@gmail. com>:
multi-line lambdas, had it been added to python a long time ago, would
had reduced a lot of complexity in the language.
for example - with multi-line lambdas - decorators are unneccesary.
I don't like the words neccesary or unneccesary in these discussions,
because they rarely add anything. For instances decorators are
unneccesary in python now, even without multi-line lambdas.

There is nothing you can do with decorators that you can't do
without.
just give the multi-line lambda as an argument to a function - no need
for special syntax..
There is no need for special syntax. The decorators are just syntactic
sugar to do something that was already possible before.
the alternative decorators would also be simpler.
currently when you want to create a "decorator-that-accepts-additional-
arguments" you gotta make a funtion that gets those
additional-arguments and returns a function that will be the decorator.


Could you give me an example. Suppose I have the following:

def arg_range(inf, sup):

def check(f):

def call(arg):
if inf <= arg <= sup:
return f(arg)
else:
raise ValueError

return call

return check

@arg_range(3, 12)
def func(arg):
return arg

How would this look simpler with multi-line lambda's?

--
Antoon Pardon
May 10 '06 #10

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

Similar topics

37
4895
by: ajikoe | last post by:
Hello, Is anyone has experiance in running python code to run multi thread parallel in multi processor. Is it possible ? Can python manage which cpu shoud do every thread? Sincerely Yours, Pujo
4
4673
by: Frank Jona | last post by:
Intellisense with C# and a multi-file assembly is not working. With VB.NET it is working. Is there a fix availible? We're using VisualStudio 2003 Regards Frank
12
3879
by: * ProteanThread * | last post by:
but depends upon the clique: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&threadm=954drf%24oca%241%40agate.berkeley.edu&rnum=2&prev=/groups%3Fq%3D%2522cross%2Bposting%2Bversus%2Bmulti%2Bposting%2522%26ie%3DUTF-8%26oe%3DUTF-8%26hl%3Den ...
0
3784
by: frankenberry | last post by:
I have multi-page tiff files. I need to extract individual frames from the multi-page tiffs and save them as single-page tiffs. 95% of the time I receive multi-page tiffs containing 1 or more black and white CCITT4 compressed files (frames) inside the tiff. Every now and then I receive a mixture of black and white CCITT4 and JPEG compressed files, and sometimes just multi-page tiffs with JPEG only. The code runs great when dealing with the...
6
8178
by: cody | last post by:
What are multi file assemblies good for? What are the advantages of using multiple assemblies (A.DLL+B.DLL) vs. a single multi file assembly (A.DLL+A.NETMODULE)?
6
4893
by: Joe | last post by:
I have 2 multi-list boxes, 1 displays course categories based on a table called CATEGORIES. This table has 2 fields CATEGORY_ID, CATEGORY_NAME The other multi-list box displays courses based on a table called COURSES. This table has 2 fields CATEGORY_ID, COURSE_NAME. The CATEGORY_ID is a FK in COURSES and a PK in CATEGORIES. I want to populate the course list box based on any category(s)
4
17874
by: mimmo | last post by:
Hi! I should convert the accented letters of a string in the correspondent letters not accented. But when I compile with -Wall it give me: warning: multi-character character constant Do the problem is the charset? How I can avoid this warning? But the worst thing isn't the warning, but that the program doesn't work! The program execute all other operations well, but it don't print the converted letters: for example, in the string...
5
5997
by: Shane Story | last post by:
I can seem to get the dimensions of a frame in a multiframe tiff. After selecting activeframe, the Width/Height is still really much larger than the page's actual dimensions. When I split a TIFF to several PNG files this causes a problem, becuase the resulting image is (the page to the far left and a lot of black space surrounding it and a filesize that is larger than needed. Any ideas?
5
5766
by: bobwansink | last post by:
Hi, I'm relatively new to programming and I would like to create a C++ multi user program. It's for a project for school. This means I will have to write a paper about the theory too. Does anyone know a good place to start looking for some theory on the subject of multi user applications? I know only bits and pieces, like about transactions, but a compendium of possible approches to multi user programming would be very appreciated!
0
2328
by: Sabri.Pllana | last post by:
We apologize if you receive multiple copies of this call for papers. *********************************************************************** 2008 International Workshop on Multi-Core Computing Systems (MuCoCoS'08) Barcelona, Spain, March 4 - 7, 2008; in conjunction with CISIS'08. <http://www.par.univie.ac.at/~pllana/mucocos08> *********************************************************************** Context
0
9001
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
9583
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...
0
9396
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9342
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8263
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6808
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
4716
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2807
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2226
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.