473,324 Members | 2,193 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Extending Python Syntax with @

Seems like we need a simple way to extend Python syntax that doesn't
break existing syntax or clash with any other syntax in Python, is
easy to type, easy to read, and is clearly distinct from the "base"
syntax. Seems like we could put the @ symbol to good use in these
situations. Examples:

print @(separator = None) x, y, z

@x,y:x*x+y*y -- anonymous function

@f(x,y) -- generator function that can accept new arguments
with each call

@x @y @z -- short for instance variables in a method definition

Each of these examples is debatable, but my point is that there are
many enhancement requests like this, and some may be worthy of
inclusion in the core language. It would be nice if there was a
consistent way to add stuff like this. It certainly beats adding ugly
statements like 'lambda'.

It might even be possible to allow limited extension of the language
by users, provided the extensions are introduced by the special
symbol. This would allow the flexibility of Ruby or Lisp without the
cost of forking the language into many dialects.

Maybe we should collect a bunch of little enhancements like the above,
and put them all into one PEP. Any suggestions? Pet peeves? Stuff
you would like to see, but not worthy of a PEP by itself?

-- Dave

Jul 18 '05 #1
75 3797
David MacQuigg <dm*@gain.com> pisze:
Seems like we need a simple way to extend Python syntax that doesn't
break existing syntax or clash with any other syntax in Python, is
easy to type, easy to read, and is clearly distinct from the "base"
syntax.


No, we don't. You need it.

--
Jarek Zgoda
http://jpa.berlios.de/
Jul 18 '05 #2
David MacQuigg wrote:
syntax. Seems like we could put the @ symbol to good use in these
situations. Examples:


No, don't do that!! I hate perl precisley because of littering the code
with 'special characters'! The beauty of python code as it is, is that
it reads like a book, with punctuation to help the reader, rather than
the typesetter.

Jul 18 '05 #3
"David MacQuigg" <dm*@gain.com> wrote in message
news:s2********************************@4ax.com...
Seems like we need a simple way to extend Python syntax that doesn't
break existing syntax or clash with any other syntax in Python, is
easy to type, easy to read, and is clearly distinct from the "base"
syntax. Seems like we could put the @ symbol to good use in these
situations. Examples:


There is indeed a cost to adding new keywords and operators;
it's possible that existing programs will break. It's quite possible
to design a language where this wouldn't happen, but Python is
not that language.

As it turns out, there is one very simple key to a language
with keywords where adding new ones won't break existing
programs: put them in a lexically distinguishable namespace.
It happens that solution is quite unpleasant to work with -
unless it's supported by a syntax aware editor/IDE. Someday
people will get over their attachment with being able to write
programs with any old text editor that happens to be lying
around, and being able to print their programs without
needing a special formatting program, but that day isn't today,
and I doubt if it's tomorrow.

The problem with adding new operators is a quite different
issue. It arises from the language designer trying to be too
nice to the developers. If the lexer simply collected the longest
possible string of special characters *before* checking if that
collection of special characters made a valid token, and declared
a syntax error if it didn't, then there would be no difficulty with
adding new operators.

That solution is also fairly unpleasant: we're a bit too used to
being able to string special character operators together without
separating them with white space. Again, an intelligent editor/IDE
would help here, too.

An intelligent editor/IDE would also make it possible to add
any of the numerous mathematical symbols from the Unicode
set easily: it could adjust for the developer's preferences in
entering them, and would, of course, display them properly.

I am, I suppose, getting old and cynical enough to have quit
expecting anything quite so radical as a language that actually
expectes the editor/IDE to pull its share of the work.

John Roth

Jul 18 '05 #4
On Wed, 10 Mar 2004 16:50:58 -0500, John Roth wrote:
Someday people will get over their attachment with being able to write
programs with any old text editor that happens to be lying around, and
being able to print their programs without needing a special
formatting program, but that day isn't today, and I doubt if it's
tomorrow.


I doubt it's ever, because such a day would have to be preceded by the
day when programs no longer need to be inspected, maintained or
transferred between systems not specifically set up as developer
workstations.

--
\ "Those who can make you believe absurdities can make you commit |
`\ atrocities." -- Voltaire |
_o__) |
Ben Finney <http://bignose.squidly.org/>
Jul 18 '05 #5
> @x @y @z -- short for instance variables in a method definition

This is completely unnecessary. Leo uses the following convention:

def whatever(self):
v = self
v.whatever

The assignment v = self (or x = self etc.) indicates the expected type of
self and saves keystrokes. This convention has been useful in refactorings
when moving methods from one class to another: all that had to be done is to
change the v = self line to something else.

BTW, it would also be possible to define the function as follows:

def whatever(v):
v.whatever

However, this isn't proper Python style and Pychecker complains.

Edward
--------------------------------------------------------------------
Edward K. Ream email: ed*******@charter.net
Leo: Literate Editor with Outlines
Leo: http://webpages.charter.net/edreamleo/front.html
--------------------------------------------------------------------
Jul 18 '05 #6
"Ben Finney" <bi****************@and-benfinney-does-too.id.au> wrote in
message news:sl*******************************@iris.polar. local...
On Wed, 10 Mar 2004 16:50:58 -0500, John Roth wrote:
Someday people will get over their attachment with being able to write
programs with any old text editor that happens to be lying around, and
being able to print their programs without needing a special
formatting program, but that day isn't today, and I doubt if it's
tomorrow.


I doubt it's ever, because such a day would have to be preceded by the
day when programs no longer need to be inspected, maintained or
transferred between systems not specifically set up as developer
workstations.


How much real development (I don't mean archiving) do we do
today on systems without appropriate tools? Very little. The issue
isn't trying to develop on systems without appropriate tools, it's
developers that won't use tools that help them work.

John Roth

/>
Jul 18 '05 #7
Personally, I'd much prefer that we get things like

def @del

instead of

def __del__

Save some keystrokes and I think the @ is attention-drawing-enough that
we don't lose anything. Of course, all it's doing is adding @ to the
legal characters in a variable name, which might be a waste instead of
attaching a syntax to it, but...
Jul 18 '05 #8
I don't like your suggestion. You propose using @ in 4 different
ways, one of which I don't even understand
-- to pass keyword arguments to statements
-- instead of the perfectly good "lambda" keyword
-- mumble generators mumble (this is the example I don't understand)
-- instead of the perfectly good "self." idiom

Jeff

Jul 18 '05 #9
Hey guys, let's not go in four different directions and waste all this
bandwidth on debating the four examples I gave. Everyone has
different ideas on enhancing the language. If you believe this is a
bad idea, regardless of the particular examples, let's talk.

If you believe as I do that Python is not yet the ultimate language,
and some syntactical changes are still to come, then it seems like
using a very distinct symbol like @ may have some merits. This is not
a suggestion to make the language "perlesque". The difference is that
@ not a menagerie of symbols with various tricky meanings, but one
very noticable and unique symbol that says "Pay attention, I am
different." It has no other meaning.

Wouldn't it be nice, for example, if instead of special keywords like
'lambda' and 'yield', we had used '@(args)' and '@return'. ( No, I'm
not advocating we go back and change what has been done.) In both
these cases, we had a well-established syntax that needed a slight
variation.

The 'lambda function' for example, was needed to cram a small block of
code into a tight space. By saying '@x,y:' instead of 'lambda x,y:',
we not only avoid the need for a new keyword, but we better serve the
purpose of tightly packing some code. We would also avoid mystifying
beginners. "It has no magic meaning. It's just a way to write a
function without a name."

Sorry if my intentions weren't clear in my original post.

-- Dave

On Wed, 10 Mar 2004 14:01:00 -0700, David MacQuigg <dm*@gain.com>
wrote:
Seems like we need a simple way to extend Python syntax that doesn't
break existing syntax or clash with any other syntax in Python, is
easy to type, easy to read, and is clearly distinct from the "base"
syntax. Seems like we could put the @ symbol to good use in these
situations. Examples:
[ add your own examples here ]
Each of these examples is debatable, but my point is that there are
many enhancement requests like this, and some may be worthy of
inclusion in the core language. It would be nice if there was a
consistent way to add stuff like this. It certainly beats adding ugly
statements like 'lambda'.

It might even be possible to allow limited extension of the language
by users, provided the extensions are introduced by the special
symbol. This would allow the flexibility of Ruby or Lisp without the
cost of forking the language into many dialects.

Maybe we should collect a bunch of little enhancements like the above,
and put them all into one PEP. Any suggestions? Pet peeves? Stuff
you would like to see, but not worthy of a PEP by itself?


Jul 18 '05 #10
Ivan Voras wrote:
David MacQuigg wrote:
syntax. Seems like we could put the @ symbol to good use in these
situations. Examples:


No, don't do that!! I hate perl precisley because of littering the
code
with 'special characters'! The beauty of python code as it is, is that
it reads like a book, with punctuation to help the reader, rather than
the typesetter.


Further, @ and $ are already used by some Python meta-applications in
order to signal embedding Python code in something else, since these
symbols are not used in Python itself. Templating systems often rely on
such symbols not being in the language and staying out.

But the Perlification of Python is the most relevant objection here.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ An ounce of hypocrisy is worth a pound of ambition.
-- Michael Korda
Jul 18 '05 #11
In article <fk********************************@4ax.com>,
David MacQuigg <dm*@gain.com> wrote:
Jul 18 '05 #12
DH

I would prefer "anonymous" or "implicit" things be referred to by
nothing at all instead of @. For example, instead of "self.x", just
have ".x". Instead of lambda, allow for unnamed "def" code blocks with
[] or () to allow for multiple lines.
def (optional params) [optional decorator]: [
some code here...
]

Some things I might like to see in python, in no particular order:
- an "=~" operator
- pychecker bundled with python, since it catches so many errors
beginners and non-beginners make.
- allow for curly braces to specify a multi-line code block so []
and () are not abused.
- use the keyword "function" instead of "def"
- make colons optional after function and class declarations. People
forget to type them anyway.
- be able to refer to variables case-insensitively though they
are still stored case-sensitively. Make keywords like None,
True, and False case insensitive.
- no more "self" parameter required for class methods. If need be,
maybe class instance methods could be specified by
starting the name with "."

Of course, the chances of any of these happening in python = None, so a
better long term idea is to make it easier for people to create custom
scripting languages for a common virtual machine like jvm, parrot, maybe
python in python (pypy), etc.
http://grunge.cs.tu-berlin.de/~tolk/vmlanguages.html
http://codespeak.net/pypy/index.cgi?home
http://www.parrotcode.org/
Jul 18 '05 #13
On 2004-03-10, David MacQuigg <dm*@gain.com> wrote:
print @(separator = None) x, y, z

@x,y:x*x+y*y -- anonymous function

@f(x,y) -- generator function that can accept new arguments
with each call

@x @y @z -- short for instance variables in a method definition Each of these examples is debatable, but my point is that there are


No, they're not. You want Perl, use Perl. I used it for 5 freakin' years
and have had enough of "and this line noise means THIS but only after that
line noise!" I finally gave up when I read that they were thinking about
making case significant declarations. #$%#$ that.

--
Steve C. Lamb | I'm your priest, I'm your shrink, I'm your
PGP Key: 8B6E99C5 | main connection to the switchboard of souls.
-------------------------------+---------------------------------------------
Jul 18 '05 #14
On Wed, 10 Mar 2004 16:50:58 -0500,
"John Roth" <ne********@jhrothjr.com> wrote:
... Someday people will get over their attachment with being
able to write programs with any old text editor that happens to
be lying around, and being able to print their programs without
needing a special formatting program, but that day isn't today,
and I doubt if it's tomorrow.


It will be *never*.

At least emacs and vi share a common file format. Even if you
prefer [the wrong one], you are free to use it to edit "our" files
should we ever collaborate.

Not only that, but sed, grep, awk, diff, cvs, tr, m4, perl (gasp),
python (whew!), lex, yacc, uncountable interactive shells, and any
other tool(s) you or I care to write for whatever odd requirement
comes up also share that common format (the occasional OS-imposed
newline convention notwithstanding).

Is your IDE that flexible/extensible/powerful?

So perhaps you're right, and that IDE that replaces "any old text
editor" is Unix (with all due copyright apologies) and everything
in its $PATH.

IMO, YMMV, etc.

Regards,
Heather

--
Heather Coppersmith
That's not right; that's not even wrong. -- Wolfgang Pauli
Jul 18 '05 #15
>>>>> "David" == David MacQuigg <dm*@gain.com> writes:

David> Wouldn't it be nice, for example, if instead of special keywords
David> like 'lambda' and 'yield', we had used '@(args)' and '@return'.
David> ( No, I'm not advocating we go back and change what has been
David> done.) In both these cases, we had a well-established syntax
David> that needed a slight variation.

I don't think it is an improvement. If you get puzzled reading a program
with lambda expressions, you remember that you conveniently skipped reading
"lambda" in the docs. If you read a program with generator, you know the
"yield" section at the new Python docs will help. Both is very clear
mentally: you can easily recall what you've learnt. If you read a program
containing silly @, where should you look? And will you still remember it
after 2 years of programming solely in Perl? I think everybody trying to
add language construct should remember "explicit is better than implicit".

David> The 'lambda function' for example, was needed to cram a small
David> block of code into a tight space. By saying '@x,y:' instead of
David> 'lambda x,y:', we not only avoid the need for a new keyword, but
David> we better serve the purpose of tightly packing some code. We
David> would also avoid mystifying beginners. "It has no magic meaning.
David> It's just a way to write a function without a name."

There is no real need to "cram a small block of code into a tight space":
your space is unlimited when writing programs. There are times when you
should want using less space: when you are expressing a sequence of really
simple things. If you are writing something as complicated as a "lambda x,
y: ..." and that "..." can't be put into your program conveniently, the odds
are that it really takes effort to understand that part. Then I don't think
that one really should try to put it into less space.

Regards,
Isaac.
Jul 18 '05 #16
On Thu, 11 Mar 2004 01:28:47 -0000, cl****@lairds.com (Cameron Laird)
wrote:
In article <fk********************************@4ax.com>,
David MacQuigg <dm*@gain.com> wrote:
.
.
.
Wouldn't it be nice, for example, if instead of special keywords like
'lambda' and 'yield', we had used '@(args)' and '@return'. ( No, I'm
not advocating we go back and change what has been done.) In both
these cases, we had a well-established syntax that needed a slight
variation.

The 'lambda function' for example, was needed to cram a small block of
code into a tight space. By saying '@x,y:' instead of 'lambda x,y:',
we not only avoid the need for a new keyword, but we better serve the
purpose of tightly packing some code. We would also avoid mystifying
beginners. "It has no magic meaning. It's just a way to write a
function without a name."

.
.
.
No, for me it would be so far from nice I first suspected you
of jesting, because, from my background, "lambda" *does* have
a magic meaning, one that long precedes its (entirely apt) use
in Python. For you, '@(args)' might indeed be more evocative;
for me, not calling a lambda "lambda" would be a big loss.

I think APL and J (and Perl) are plenty meritorious. I prefer
Python--much.


I guess this reflects our different backgrounds. I've been an
electronic design engineer for many years. I never heard of lambda's
or lambda calculus until learning Python, and the name still doesn't
evoke much meaning for me. I've never used APL, J, or Perl. I wonder
how many technical professionals who are *not* programmers would know
what a lambda is? I wonder if Python is becoming more a language for
programmers, and less for "everyone".

My initial impression in learning Python was that 'lambda' was
something tricky. Then it became clear it was just a way to cram a
function into a small space like an argument list, except that there
were some strange restrictions on what could be put in the function.
Even now, it seems like 'lambda x,y:' is awkward if you are trying to
save space. It seems like we have paid a price for the dubious
assumption that most users will benefit from the magic meaning of
'lambda'.

Ruby uses a notation like |x,y|, which is compact, but I don't like
adding special punctuation for every little task. (The Perl problem.)
If the goal is to cram a function into a tight space, we could do it
compactly, and have the extra burden of the new syntax be shared by
many other features. They key characteristic is that they are small
departures from existing features and syntax, so the symantic burden
is not carried by the @ symbol. It's just a flag to modify something
already well understood. All @X says is "I'm like X, but different."
You still need to learn about X.

Again, my intention is not to change lambda functions, but to propose
a better way of introducing new syntax to a language that already has
all the basics worked out. I would rather have one special symbol
than a bunch of new keywords that mean nothing to me.

-- Dave

Jul 18 '05 #17
David MacQuigg wrote:
@x @y @z -- short for instance variables in a method definition


The explicit self in front of accesses is what bugged me the most when
I first started with Python. (I liked the indentation. All my
C/C++/Java code is appropriately indented anyway, so the Python
rules didn't change my indentation style, and only removed now
superfluous punctuation).

But now when I go back to C++ code, the lack of self/this bugs
me. I often expect to not compile since I am not to sure where
it is resolving a name to. (Try writing MFC code on PocketPC
sometime - the layers of abstractions and inheritance get to be
fun).

Of course I could use this->x in the code, but that is non-standard
and not something I would want to inflict on someone who has to
maintain the code.

explicit is better than implicit!

Roger
Jul 18 '05 #18
> Wouldn't it be nice, for example, if instead of special keywords like
'lambda' and 'yield', we had used '@(args)' and '@return'. ( No, I'm
not advocating we go back and change what has been done.) In both
these cases, we had a well-established syntax that needed a slight
variation.


It would not be nice for me either. I *much* prefer the explicit way of
Python using explicit keywords than cryptic one. And besides, if typing
is an issue, then an editor can be programmed to extend the words as you
type or insert the keywords.

I really don't see what benefit it would do to Python which is easy to
learn as it is.

IMHO, I'd stay away from these 'nice' (?) tricks.

Sorry... I do like the zen of the current Python.

Pierre Rouleau
Jul 18 '05 #19
"David MacQuigg" <dm*@gain.com> wrote in message
news:s2********************************@4ax.com...
Seems like we need a simple way to extend Python syntax that doesn't
break existing syntax or clash with any other syntax in Python, is
easy to type, easy to read, and is clearly distinct from the "base"
syntax. Seems like we could put the @ symbol to good use in these
situations. Examples:

print @(separator = None) x, y, z

@x,y:x*x+y*y -- anonymous function

@f(x,y) -- generator function that can accept new arguments
with each call

@x @y @z -- short for instance variables in a method definition

Each of these examples is debatable, but my point is that there are
many enhancement requests like this, and some may be worthy of
inclusion in the core language. It would be nice if there was a
consistent way to add stuff like this. It certainly beats adding ugly
statements like 'lambda'.

It might even be possible to allow limited extension of the language
by users, provided the extensions are introduced by the special
symbol. This would allow the flexibility of Ruby or Lisp without the
cost of forking the language into many dialects.

Maybe we should collect a bunch of little enhancements like the above,
and put them all into one PEP. Any suggestions? Pet peeves? Stuff
you would like to see, but not worthy of a PEP by itself?

-- Dave

Pet peeve: gratuitous inclusion of magic symbols into an otherwise
easy-to-understand language syntax.

-- Paul
Jul 18 '05 #20
David MacQuigg wrote:
On Thu, 11 Mar 2004 01:28:47 -0000, cl****@lairds.com (Cameron Laird)
wrote:

<snip>


I guess this reflects our different backgrounds. I've been an
electronic design engineer for many years. I never heard of lambda's
or lambda calculus until learning Python, and the name still doesn't
evoke much meaning for me. I've never used APL, J, or Perl. I wonder
how many technical professionals who are *not* programmers would know
what a lambda is? I wonder if Python is becoming more a language for
programmers, and less for "everyone".


I was trained as an EE myself and started programming in assembler on
microprocessors, then in C , then in C++, reading, reading, reading,....

Just the mere fact that you are talking about lambda shows that you know
what it is, as I do now and as people learning Python will know when
they use it. They'll learn, that why they are technical professionals, no?

I have no problem with the way Python uses lambda and I like the fact
that it does not have cryptic keywords. I don't need to think about the
way things have to be written when I write Python programs, I think
about system design. I would think that a technical person that is not
a programmer would like that too.

Regards,

Pierre Rouleau

Jul 18 '05 #21
[...]
print @(separator = None) x, y, z

@x,y:x*x+y*y -- anonymous function

@f(x,y) -- generator function that can accept new arguments
with each call

@x @y @z -- short for instance variables in a method definition


That's great!! All of our problems are gone! I'm really excited
wondering about what we could do with $!! :-)

--
Gustavo Niemeyer
http://niemeyer.net

Jul 18 '05 #22
In article <tP*********************@news20.bellglobal.com>,
Pierre Rouleau <pr******@impathnetworks.com> wrote:
David MacQuigg wrote:
On Thu, 11 Mar 2004 01:28:47 -0000, cl****@lairds.com (Cameron Laird)
wrote:

<snip>


I guess this reflects our different backgrounds. I've been an
electronic design engineer for many years. I never heard of lambda's
or lambda calculus until learning Python, and the name still doesn't
evoke much meaning for me. I've never used APL, J, or Perl. I wonder
how many technical professionals who are *not* programmers would know
what a lambda is? I wonder if Python is becoming more a language for

Jul 18 '05 #23
DH wrote:
- pychecker bundled with python, since it catches so many errors
beginners and non-beginners make.
I would LOVE to see that, or even a special "checking" mode for the
interpretter even if it ran ten times slower. Pychecker has been
become increasingly useless to me. Part of that is due to bugs
(SF #844960, #708546), part due it being incomplete, and part
due to wxWidgets defining every function as (*args, **kwargs)
and indirecting through a layer of Swig. I get a huge list
of false positives.
- make colons optional after function and class declarations. People
forget to type them anyway.


I don't agree with that. With the current scheme, it is trivial for
editors to auto-indent. They just have to do so after any line
ending in a colon, with no exceptions to that rule.

The case suggestion makes things appear better in the short term,
but do lots more harm in the long term, making maintenance and
performance significantly harder. If you would like to understand
some of the issues, I would recommend writing a translator between
the "relaxed" Python you describe and the standard Python.

Roger
Jul 18 '05 #24
On Thu, 11 Mar 2004 05:13:25 -0000, cl****@lairds.com (Cameron Laird)
wrote:
Pierre Rouleau <pr******@impathnetworks.com> wrote: .
I was trained as an EE myself and started programming in assembler on
microprocessors, then in C , then in C++, reading, reading, reading,....
Just the mere fact that you are talking about lambda shows that you know
what it is, as I do now and as people learning Python will know when
they use it. They'll learn, that why they are technical professionals, no?

I agree. Lamdas are no big deal once you get past some obfuscation
and understand they perform a very simple function. Of course, both
of us could be missing something important. There is a lot of deep
theory behind the lambda calculus. While drawing a tentative
conclusion, we have to always keep an open mind to something new.

On Thu, 11 Mar 2004 05:13:25 -0000, cl****@lairds.com (Cameron Laird)
wrote: For more on what lambda means to me, and others, see
<URL: http://www.csse.monash.edu.au/~lloyd.../00.Intro.html >
or
<URL: http://www.mactech.com/articles/mact...ambdaCalculus/ >
or
<URL: http://www.alcyone.com/software/church/ > or ...


This is an impressive body of knowledge, but unless I see how it is
going to help me write some code, I won't have time to study it. My
understanding of lambda functions is simply that they are a way to
squeeze functions into a tight space:

list_of_funcs = [(lambda x: 2**x), (lambda x: 3**x), (lambda x: 4**x)]

If you are not concerned about space, simply use normal defs:

def f2(x): return 2**x
def f3(x): return 3**x
def f4(x): return 4**x
list_of_funcs = [f2, f3, f4]

Is there any other reason in Python to use lambdas?

-- Dave

Jul 18 '05 #25
David MacQuigg wrote, amongst other things:

If you believe as I do that Python is not yet the ultimate language,
If Python were the ultimate language, it would be a Lisp ;-)
and some syntactical changes are still to come, then it seems like
using a very distinct symbol like @ may have some merits. This is not


Perhaps, but as it stands, Python syntax is the best compromise in
readability I have seen in any programming language, and I for one am
very comfortable with less cryptic symbols - another case for explicit
is better than implicit.

--
Christopher
Jul 18 '05 #26
David MacQuigg wrote, amongst other things:
electronic design engineer for many years. I never heard of lambda's
or lambda calculus until learning Python, and the name still doesn't
evoke much meaning for me. I've never used APL, J, or Perl. I wonder
how many technical professionals who are *not* programmers would know
what a lambda is? I wonder if Python is becoming more a language for
programmers, and less for "everyone".


To program, everyone eventually will have to be a programmer. Powerful
programming languages offer concepts that aren't always easy to grasp,
but in order to use them, some kind of understanding will have to
happen. Mostly it's easier if you learn them using Python, or after
your 3rd or 4th not too similar language...

--
Christopher
Jul 18 '05 #27
On Wed, 10 Mar 2004 15:31:12 -0600, Jeff Epler <je****@unpythonic.net>
wrote:
I don't like your suggestion. You propose using @ in 4 different
ways, one of which I don't even understand
-- to pass keyword arguments to statements
-- instead of the perfectly good "lambda" keyword
-- mumble generators mumble (this is the example I don't understand)
-- instead of the perfectly good "self." idiom


The details of these suggestions don't matter. The key concept, which
nobody seems to appreciate, is that we can *avoid* different and
confusing ways of extending an existing syntax. Perhaps a better
example will help.

Paul Prescod in a recent thread proposed deprecating the print
statement in favor of a "show()" function. The new function would
provide the same defaults as our current print statement, but would
also allow changing those defaults via keyword arguments. As you
might expect there were lots of objections to deprecating the existing
syntax. The arguments in favor were good, however, and I could see
this being done in some future version of Python.

There are lots of other examples where it would be nice to extend the
current syntax without changing the old. So how would we do that with
the print statement? We could do it by adding keywords, like was done
did with 'lambda' and 'yield'. That seems to be the implication of
the arguments in this thread against using a special symbol.

What I'm saying is, rather than add new keywords, it would be better
to have a standard symbol that has no specific meaning other than
"modify this statement". Beginners will learn the basic statements,
and ignore the modifications. Later they will see an @ symbol on some
otherwise familiar statement, and they will go to the docs for that
statement to figure out what it means. This is quite different than
Perl, where symbols themselves convey many complex meanings.

Maybe there will be no more changes in Python. I think that would be a
mistake as bad as adding more unnecessary keywords for seldom-used
statements.

-- Dave

Jul 18 '05 #28
David MacQuigg schrieb:
Seems like we need a simple way to extend Python syntax that doesn't
break existing syntax or clash with any other syntax in Python, [...] @x,y:x*x+y*y -- anonymous function


Advantage of your proposal:

- easy to extend the language without breaking existing code.

Disadvantages of your proposal:

- The advantage is also a disadvantage: a lowered barrier for
new semantics could bloat the language definition. Python's
strength is that it has *few* concepts that are usable in *many*
places. This could be compromised by your proposal.

- Python is a readable language. lambda says "function literal",
yield says "generator", @ just says "different". Python would
be less readable if this notation would be adopted.

Therefore I vote against it.

Mit freundlichen Gruessen,

Peter Maas

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24
Tel +49-241-93878-0 Fax +49-241-93878-20 eMail pe********@mplusr.de
-------------------------------------------------------------------
Jul 18 '05 #29
In article <2f********************************@4ax.com>,
David MacQuigg <dm*@gain.com> wrote:
Jul 18 '05 #30
cl****@lairds.com (Cameron Laird) writes:
Part of tribal lore--a true,
documented part, by the way--is that Big Cheese Guido depre-
cates lambdas. He says they're a mistake, and people shouldn't
be using 'em.
Interesting! I had assumed lambdas to be a necessity. I rarely
used them until I learned Scheme, but I didn't realize there was
a clean alternative.
Whenever you feel like a lambda, define a named
function;


How do you cleanly do that?
foo = range(-10, 10)
my_op = lambda x: float(x) / max(map(abs, foo))
bar = map(my_op, foo)

--kyler
Jul 18 '05 #31
David MacQuigg <dm*@gain.com> writes:
Sorry if my intentions weren't clear in my original post.


If your intention wasn't humour, then yes, it was not clear. I
seriously thought you were joking.

Nick

--
# sigmask || 0.2 || 20030107 || public domain || feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?')
Jul 18 '05 #32

"Cameron Laird" <cl****@lairds.com> wrote in message
news:10*************@corp.supernews.com...
In article <2f********************************@4ax.com>,
David MacQuigg <dm*@gain.com> wrote:
.
.
.
going to help me write some code, I won't have time to study it. My
understanding of lambda functions is simply that they are a way to
squeeze functions into a tight space:

list_of_funcs = [(lambda x: 2**x), (lambda x: 3**x), (lambda x: 4**x)]

If you are not concerned about space, simply use normal defs:

def f2(x): return 2**x
def f3(x): return 3**x
def f4(x): return 4**x
list_of_funcs = [f2, f3, f4]

Is there any other reason in Python to use lambdas? .
.
.
In fact, *that*'s not a reason. Part of tribal lore--a true,
documented part, by the way--is that Big Cheese Guido depre-
cates lambdas. He says they're a mistake, and people shouldn't
be using 'em. Whenever you feel like a lambda, define a named
function; it forces the developer to come up with a name for
the operation, and that's likely to make the code more read-
able (I'm slightly abbreviating the argument here).


I tend to agree, but for slightly different reasons. Lambdas
are a means of in-lining a function definition. However, they
are so restricted that we constantly get suggestions for
"improving" them by adding more syntax.

Given the restrictions, I see the natural growth path as leading
to a callable instance or a bound method, not a module level
function. Module level functions are a distraction; usually you
want to interface with an object, and module level functions make
that very difficult.

The other reason to avoid lambdas is the DRY principle:
Don't Repeat Yourself. Most uses of lambdas I've seen
lead to duplication in anything larger than a toy program.

What I'd really like is for all of the instructional material
with lambdas to just magically vanish and be replaced by
instructional material that does whatever it is in proper
object oriented fashion, using bound methods for callbacks.
Relegate lambda to a sidebar.

John Roth

--

Cameron Laird <cl****@phaseit.net>
Business: http://www.Phaseit.net

Jul 18 '05 #33
On Thu, 11 Mar 2004 14:09:47 GMT, Kyler Laird <Ky***@news.Lairds.org>
wrote:
cl****@lairds.com (Cameron Laird) writes:
Whenever you feel like a lambda, define a named
function;


How do you cleanly do that?
foo = range(-10, 10)
my_op = lambda x: float(x) / max(map(abs, foo))
bar = map(my_op, foo)

--kyler


foo = range(-10, 10)
# my_op = lambda x: float(x) / max(map(abs, foo))
def my_op(x): return float(x) / max(map(abs, foo))
bar = map(my_op, foo)

-- Dave
Jul 18 '05 #34
David MacQuigg wrote:
If you believe as I do that Python is not yet the ultimate language,
and some syntactical changes are still to come, then it seems like
using a very distinct symbol like @ may have some merits.


If what motivates you is the 'ultimate language' and think you can get
closer to it by adding special characters then you are going to be very
disappointed. The history of computing is littered with 'ultimate
languages' that have had much more thought put into them than adding
special characters to an existing language (C++ comes to mind) and they
all have in common the fact that they failed.

To be fair C++ was never touted as an 'ultimate language' but you get
the picture.

If you feel python has a significant flaw then say what it is and how
you believe it would best be addressed. Using @ as a special character
is just adding sugar to the syntax.

Maybe what we need is a language that has only a grammer and the syntax
/ vocabulary comes from the objects. Or is that AppleScript?
Jul 18 '05 #35

[Cameron]
Whenever you feel like a lambda, define a named function;
[Kyler] How do you cleanly do that?
foo = range(-10, 10)
my_op = lambda x: float(x) / max(map(abs, foo))
bar = map(my_op, foo)


foo = range(-10, 10)
def my_op(x):
return float(x) / max(map(abs, foo))
bar = map(my_op, foo)

....did I misunderstand?

--
Richie Hindle
ri****@entrian.com
Jul 18 '05 #36
In article <40***********************@news.easynet.co.uk>,
Peter Hickman <pe***@semantico.com> wrote:
Jul 18 '05 #37
In article <10*************@news.supernews.com>,
John Roth <ne********@jhrothjr.com> wrote:
Jul 18 '05 #38
On Thu, 11 Mar 2004 12:55:20 -0000, cl****@lairds.com (Cameron Laird)
wrote:
In article <2f********************************@4ax.com>,
David MacQuigg <dm*@gain.com> wrote:
.
.
.
going to help me write some code, I won't have time to study it. My
understanding of lambda functions is simply that they are a way to
squeeze functions into a tight space:

list_of_funcs = [(lambda x: 2**x), (lambda x: 3**x), (lambda x: 4**x)]

If you are not concerned about space, simply use normal defs:

def f2(x): return 2**x
def f3(x): return 3**x
def f4(x): return 4**x
list_of_funcs = [f2, f3, f4]

Is there any other reason in Python to use lambdas? .
.
.
In fact, *that*'s not a reason. Part of tribal lore--a true,
documented part, by the way--is that Big Cheese Guido depre-
cates lambdas. He says they're a mistake, and people shouldn't


Wow!! And I thought it was just me. Could you point me to a PEP or
other discussion? I would sure like to know the history of this.
Could it be that in adding "lambda calculus" to Python, Guido was
snowed by the language theorists? <half wink>

I think it is really cool that a language can actually have a mistake
like this corrected. In the commercial world I'm used to, such a
feature would become part of the core religion, and any questioning
would eventually be met with "There are just some things you can't
understand. Get back to work!"
be using 'em. Whenever you feel like a lambda, define a named
function; it forces the developer to come up with a name for
the operation, and that's likely to make the code more read-
able (I'm slightly abbreviating the argument here).

Space, in the sense you're using it above, should NOT concern
Pythoneers. Correctness and clarity of express should.
Agree 110%
It pains my sensitivities every time you claim lambdas are
just a way of making functions "small". Again, I understand
how natural that is from your background. Around this
mathematician, 'twould be less distracting to run your finger-
nails down a chalkboard.
Sorry for the pain, and many thanks for the enlightenment.
I think this ties back to your broader original propositions:
the Python aesthetic assesses little merit for the brevity of
@-anything, and much for the presumed evocativeness of "yield".
An abundance of *good* keywords is a good thing. That's
definitely not the attitude of all languages.


I agree that brevity in itself has little merit. This whole
side-discussion on lambdas was on the presumption that brevity was the
intent. I now think deprecation of this wart is the better
alternative.

The choice between adding a keyword and modifying an existing
statement with a standard 'modify' symbol may now be largely a matter
of personal preference. ( 'yield' vs @return, 'self.x' vs @x ).
Still, there is a small syntactic burden added with each keyword. We
just have to be careful that the benefit (evoking an instant meaning
to the majority of users) is actually realized.

A new keyword 'printraw', would certainly do that. It just doesn't
feel right to me, however. So if we can't have
print @(separator = None) x,y,z
then I would opt for deprecating 'print' and going with the function
syntax proposed by Paul Prescod:
show(x,y,z, separator = None)

-- Dave

Jul 18 '05 #39

"David MacQuigg" <dm*@gain.com> wrote in message
news:mu********************************@4ax.com...
On Thu, 11 Mar 2004 12:55:20 -0000, cl****@lairds.com (Cameron Laird)
wrote:
In article <2f********************************@4ax.com>,
David MacQuigg <dm*@gain.com> wrote:
.
.
.
going to help me write some code, I won't have time to study it. My
understanding of lambda functions is simply that they are a way to
squeeze functions into a tight space:

list_of_funcs = [(lambda x: 2**x), (lambda x: 3**x), (lambda x: 4**x)]

If you are not concerned about space, simply use normal defs:

def f2(x): return 2**x
def f3(x): return 3**x
def f4(x): return 4**x
list_of_funcs = [f2, f3, f4]

Is there any other reason in Python to use lambdas? .
.
.
In fact, *that*'s not a reason. Part of tribal lore--a true,
documented part, by the way--is that Big Cheese Guido depre-
cates lambdas. He says they're a mistake, and people shouldn't


Wow!! And I thought it was just me. Could you point me to a PEP or
other discussion? I would sure like to know the history of this.
Could it be that in adding "lambda calculus" to Python, Guido was
snowed by the language theorists? <half wink>


There's a presentation on the Python site - go to Doc, then to
Guido's Essay's, then to Presentations. It's called Python Regrets.
Google has an HTML version if you use "Python Regrets Guido"
as the keywords.

The lambda keyword really has almost nothing to do with the
lambda calculus: it's about a number of functional extensions
that are all being phased out over a period of time.

I think it is really cool that a language can actually have a mistake
like this corrected. In the commercial world I'm used to, such a
feature would become part of the core religion, and any questioning
would eventually be met with "There are just some things you can't
understand. Get back to work!"
There are a few too many of these in Python as well. It's going
to be a long time for the language to evolve, especially since
there seems to be a religious cult that is holding on to release
1.5.2 like it will insure their salvation.

John Roth

Jul 18 '05 #40
On Thu, 11 Mar 2004 13:15:39 +0100, Peter Maas
<fp********@netscape.net> wrote:
David MacQuigg schrieb:
Seems like we need a simple way to extend Python syntax that doesn't
break existing syntax or clash with any other syntax in Python,[...]
@x,y:x*x+y*y -- anonymous function


Advantage of your proposal:

- easy to extend the language without breaking existing code.

Disadvantages of your proposal:

- The advantage is also a disadvantage: a lowered barrier for
new semantics could bloat the language definition. Python's
strength is that it has *few* concepts that are usable in *many*
places. This could be compromised by your proposal.


This is actually a separate issue. Adding a few @ mods to selected
statements does not mean that users can add their own.
- Python is a readable language. lambda says "function literal",
yield says "generator", @ just says "different". Python would
be less readable if this notation would be adopted.


Readability, in this case, is in the eye of the beholder. 'lambda' to
me says 'wavelength', which I know has nothing to do with programming.
I suspect many users are like me, not enough computer science
background to know that lambda means 'function literal'.

'yield' is a little closer to the intent, but again, to most new users
it probably means something more like 'give way' or 'acquiesce', the
opposite of 'resist'. If you had never seen 'yield' used as it is now
in Python, and your first encounter with generator functions was when
you saw @return, would you not think "Ah yes, a modified return.", and
would that not be closer to reality than whatever you might associate
with the word 'yield'?

@ would never be used alone. Like the '\' symbol used as an escape,
its meaning beyond 'different' is seen by its context.

Again, these examples are to illustrate a discussion on syntax, not to
urge changing what has already been done. ( Althugh I just learned
from another part of this thread that 'lambda' *is* going to be
deprecated !! )

I almost wish Python had adopted the Unix philosphy of using short,
meaningless words for primitives. That would have avoided the problem
we are having now with 'print'. Words like 'cat' and 'grep' acquire
their own meaning, not dependent on previous meanings in English.

-- Dave

Jul 18 '05 #41
David MacQuigg wrote:
'yield' is a little closer to the intent, but again, to most new users
it probably means something more like 'give way' or 'acquiesce', the
opposite of 'resist'. If you had never seen 'yield' used as it is now
in Python, and your first encounter with generator functions was when
you saw @return, would you not think "Ah yes, a modified return.", and
would that not be closer to reality than whatever you might associate
with the word 'yield'?


No! The "give way" meaning is _much_ closer to what is going on than
"modified return", in my way of looking at it. Return winds up the call
stack and just happens to include a result value. Yield temporarily
"gives way" but leaves the stack frame in place, available for
resumption at a later time. You could say that the result value is
incidental, in the return case, while the permanent transfer of context
is the key thing. Just the opposite in the case of yield, and therefore
much different from a "modified return".

This is all semantics, probably, but I don't believe you can make a
strong case that yield is an ill-chosen name.

-Peter
Jul 18 '05 #42
On Thu, 11 Mar 2004 11:17:08 -0500, "John Roth"
<ne********@jhrothjr.com> wrote:
"David MacQuigg" <dm*@gain.com> wrote in message
news:mu********************************@4ax.com.. .

Wow!! And I thought it was just me. Could you point me to a PEP or
other discussion? I would sure like to know the history of this.
Could it be that in adding "lambda calculus" to Python, Guido was
snowed by the language theorists? <half wink>


There's a presentation on the Python site - go to Doc, then to
Guido's Essay's, then to Presentations. It's called Python Regrets.
Google has an HTML version if you use "Python Regrets Guido"
as the keywords.


http://python.org/doc/essays/ppt/regrets/6
Interesting that Guido says lambda is confusing.

Interesting also that he is proposing two functions in place of
print(x,y,z):
write(x,y,z)
writeln(x,y,z)
This sounds very similar to Paul Prescod's proposal a few days ago on
this newsgroup, except that Paul is proposing to do it all with one
show() function. I like the one function.

Other surprises: Deprecating reload()

Thanks for the link.

-- Dave

Jul 18 '05 #43
On Thu, 11 Mar 2004 12:01:57 -0500, Peter Hansen <pe***@engcorp.com>
wrote:
David MacQuigg wrote:
'yield' is a little closer to the intent, but again, to most new users
it probably means something more like 'give way' or 'acquiesce', the
opposite of 'resist'. If you had never seen 'yield' used as it is now
in Python, and your first encounter with generator functions was when
you saw @return, would you not think "Ah yes, a modified return.", and
would that not be closer to reality than whatever you might associate
with the word 'yield'?
No! The "give way" meaning is _much_ closer to what is going on than
"modified return", in my way of looking at it. Return winds up the call
stack and just happens to include a result value. Yield temporarily
"gives way" but leaves the stack frame in place, available for
resumption at a later time. You could say that the result value is
incidental, in the return case, while the permanent transfer of context
is the key thing. Just the opposite in the case of yield, and therefore
much different from a "modified return".


A normal return terminates the function and returns a result. A
modified return (yield) suspends the function and returns a result.
This is all semantics, probably, but I don't believe you can make a
strong case that yield is an ill-chosen name.
It's not ill chosen, just arbitrary. I would be just as happy with
'rtn' or 'tsr' or any fanciful word that doesn't convey a _wrong_
meaning.

We seem to have lost the top of this sub-thread, which is what I was
responding to:
- Python is a readable language. lambda says "function literal",
yield says "generator",


All I'm saying is that these names don't convey the stated meanings to
most new users. I could be wrong, as I haven't done a survey.

-- Dave

Jul 18 '05 #44

"David MacQuigg" <dm*@gain.com> wrote in message
news:u3********************************@4ax.com...
On Thu, 11 Mar 2004 11:17:08 -0500, "John Roth"
<ne********@jhrothjr.com> wrote:
"David MacQuigg" <dm*@gain.com> wrote in message
news:mu********************************@4ax.com.. .
Wow!! And I thought it was just me. Could you point me to a PEP or
other discussion? I would sure like to know the history of this.
Could it be that in adding "lambda calculus" to Python, Guido was
snowed by the language theorists? <half wink>


There's a presentation on the Python site - go to Doc, then to
Guido's Essay's, then to Presentations. It's called Python Regrets.
Google has an HTML version if you use "Python Regrets Guido"
as the keywords.


http://python.org/doc/essays/ppt/regrets/6
Interesting that Guido says lambda is confusing.

Interesting also that he is proposing two functions in place of
print(x,y,z):
write(x,y,z)
writeln(x,y,z)
This sounds very similar to Paul Prescod's proposal a few days ago on
this newsgroup, except that Paul is proposing to do it all with one
show() function. I like the one function.


There's also a basic difference. Write takes a string (or
strings with the proposal). Print took anything and called
str() or repr() to convert.

The difference between write and writeln is that the latter
puts in the return. Since it's on Guido's list, and since I
don't think it will cause compatibility problems, I suspect
that a patch to do it wouldn't be rejected out of hand. I'd
suggest making writeln (which is a new method) default
to inserting a single space, and leave write to default to
not inserting anything between the strings. (And remember
to do the doc update at the same time - the core developers
really like that.)
Other surprises: Deprecating reload()
Reload doesn't work the way most people think
it does: if you've got any references to the old module,
they stay around. They aren't replaced.

It was a good idea, but the implementation simply
doesn't do what the idea promises.

Thanks for the link.
You're welcome.

-- Dave
John Roth

Jul 18 '05 #45
Richie Hindle <ri****@entrian.com> writes:
[Cameron]
Whenever you feel like a lambda, define a named function;
[Kyler]
How do you cleanly do that?
foo = range(-10, 10)
my_op = lambda x: float(x) / max(map(abs, foo))
bar = map(my_op, foo)
foo = range(-10, 10)
def my_op(x):
return float(x) / max(map(abs, foo))
bar = map(my_op, foo) ...did I misunderstand?


Well, your solution depends on a global variable. That's going to
get *really* ugly if we move beyond the trivial example given here.
There are other problems but they're apparently not obvious with
that example.

How 'bout some non-working code to shine some more light on it? (If
pressed, I should be able to come up with similar code that works!)

def make_translation_function(GCPs, type, invert=False):
if type == 'LSF' and len(GCPs) < 12:
# Do lots of time-consuming magic to calculate A, B, ...
return(
lambda x, y: (
x * A + y * B +
x * y * C +
...,
x * G + y * H +
x * y * I +
...
)
)
elif ... # Repeat lots of times for variations.

map_im = foo.open('map.tif')
map_translation = make_translation_function(map_im.get_GCPs, type='LSF')

path_im = foo.open('path.tif')
path_translation_i = make_translation_function(path_im.get_GCPs, type='LSF', invert=True)

# Mark all points on map that are red in path.
for (x, y) in all_red_pixels(path_im):
(lon, lat) = path_translation_i(x, y)
(x, y) = map_translation(lon, lat)
map_im.putpixel((x, y), mark_val)

Now, let's pretend that this is part of a larger program that's doing lots
of things with, potentially, lots of images, and let's also say that we
allow user-defined/imported extensions to make_translation_function().
How are you going to make a *clean* solution using named functions?

--kyler
Jul 18 '05 #46
On Thu, 11 Mar 2004 14:50:57 +0000, Peter Hickman
<pe***@semantico.com> wrote:
If what motivates you is the 'ultimate language' and think you can get
closer to it by adding special characters then you are going to be very
disappointed. The history of computing is littered with 'ultimate
languages' that have had much more thought put into them than adding
special characters to an existing language (C++ comes to mind) and they
all have in common the fact that they failed.
Perl seems to be a better example of too much syntax.
To be fair C++ was never touted as an 'ultimate language' but you get
the picture.

If you feel python has a significant flaw then say what it is and how
you believe it would best be addressed. Using @ as a special character
is just adding sugar to the syntax.


It's not a single flaw. In fact I can't imagine a single flaw that
would justify adding a special symbol. It only makes sense if adding
the symbol *improves* consistency by reducing the number of syntactic
variations, compared to adding each new feature with a *different*
syntax or unique keyword.

If someone new to Python saw a function with '@return' instead of
'return', it would be pretty easy to remember this has something to do
with efficiency, just think of it as a normal function until you start
writing your own code.

There is an optimum balance between too much syntax and too little. I
think Python is pretty close to that optimum. There are a few things
I would eliminate, and a few things I would add. Same with Ruby. I
like their use of the @ symbol, but I can't see the advantage of their
cryptic 'code blocks' over a normal Python function. I don't like
their subtle distinction between single and double-quoted strings.

Much of this is just personal preference, but in some cases you can
see a real advantage. I like their simple but powerful string
methods. You can put a lot on one line without sacrificing clarity.
See http://userlinux.com/cgi-bin/wiki.pl?RubyPython for details. I
think we can learn some things from Ruby, which after all, was
developed after a few years of learning from Python.

-- Dave

Jul 18 '05 #47
David MacQuigg schrieb:
David MacQuigg schrieb:
Disadvantages of your proposal:

- The advantage is also a disadvantage: a lowered barrier for
new semantics could bloat the language definition. Python's
strength is that it has *few* concepts that are usable in *many*
places. This could be compromised by your proposal.

This is actually a separate issue. Adding a few @ mods to selected
statements does not mean that users can add their own.


I assumed that in my response but also GvR and the Python community
can do too much with @.
Readability, in this case, is in the eye of the beholder. 'lambda' to
me says 'wavelength', which I know has nothing to do with programming.
:-)) OK, of course I was talking about the semantics within the
language framework. Otherwise you could claim that def says deaf and
for says four ;-)
'yield' is a little closer to the intent, but again, to most new users
it probably means something more like 'give way' or 'acquiesce', the
opposite of 'resist'. If you had never seen 'yield' used as it is now
in Python, and your first encounter with generator functions was when
you saw @return, would you not think "Ah yes, a modified return.", and
would that not be closer to reality than whatever you might associate
with the word 'yield'?


Sometimes it's an advantage to be a non-native speaker. I know exactly
one meaning of yield (something like deliver) and that fits nicely to
generators. :)

Mit freundlichen Gruessen,

Peter Maas

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Hubert-Wienen-Str. 24
Tel +49-241-93878-0 Fax +49-241-93878-20 eMail pe********@mplusr.de
-------------------------------------------------------------------
Jul 18 '05 #48
At some point, Kyler Laird <Ky***@news.Lairds.org> wrote:
Richie Hindle <ri****@entrian.com> writes:
[Cameron]
Whenever you feel like a lambda, define a named function;[Kyler]
How do you cleanly do that?
foo = range(-10, 10)
my_op = lambda x: float(x) / max(map(abs, foo))
bar = map(my_op, foo)

foo = range(-10, 10)
def my_op(x):
return float(x) / max(map(abs, foo))
bar = map(my_op, foo)

...did I misunderstand?


Well, your solution depends on a global variable. That's going to
get *really* ugly if we move beyond the trivial example given here.
There are other problems but they're apparently not obvious with
that example.


The lambda depends on a global variable too (or at least, a variable
up one scope).
How 'bout some non-working code to shine some more light on it? (If
pressed, I should be able to come up with similar code that works!)

def make_translation_function(GCPs, type, invert=False):
if type == 'LSF' and len(GCPs) < 12:
# Do lots of time-consuming magic to calculate A, B, ...
return(
lambda x, y: (
x * A + y * B +
x * y * C +
...,
x * G + y * H +
x * y * I +
...
)
)
elif ... # Repeat lots of times for variations.

map_im = foo.open('map.tif')
map_translation = make_translation_function(map_im.get_GCPs, type='LSF')

path_im = foo.open('path.tif')
path_translation_i = make_translation_function(path_im.get_GCPs, type='LSF', invert=True)

# Mark all points on map that are red in path.
for (x, y) in all_red_pixels(path_im):
(lon, lat) = path_translation_i(x, y)
(x, y) = map_translation(lon, lat)
map_im.putpixel((x, y), mark_val)

Now, let's pretend that this is part of a larger program that's doing lots
of things with, potentially, lots of images, and let's also say that we
allow user-defined/imported extensions to make_translation_function().
How are you going to make a *clean* solution using named functions?


Umm, easily? You don't have to refer to functions by their original
name; they are first-class objects.

def make_translation_function(GCPs, type, invert=False):
if type == 'LSF' and len(GCPs) < 12:
# Do lots of time-consuming magic to calculate A, B, ...
def LSF_function(x, y):
xy = x*y
lon = x*A + y*B + xy*C + ...
lat = x*G + y*H + xy*I + ...
return (lon, lat)
return LSF_function
elif ... # Repeat lots of times for variations.

I've even optimized by premultiplying x and y, which couldn't do in
the lambda, and made the code clearer by breaking up the calculation.

--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
Jul 18 '05 #49
[David MacQuigg]
print @(separator = None) x, y, z


For this particular example, you might get farther by proposing a
builtin print function that takes optional keyword arguments:

def newprint(*args, separator=' ', destination=sys.stdout):
print >> destination, separator.join(args)

Guido at one time wished that print was a function instead of a
statement. Here's your chance to push that idea forward.

Using a function instead of a statement is inherently more flexible,
easier to extend, and helps address a couple of micro-warts (i.e. a
handful of people hate the automatic spacing, and more than a handful
hate the >> notation).
Raymond Hettinger
Jul 18 '05 #50

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

Similar topics

4
by: Alicia Haumann | last post by:
I accidentally sent this to webmaster@python.org, so this could be a duplicate if "webmaster" forwards it to this list. :{ Hi, there. Thanks for any help that can be offered. I've been...
3
by: Eli Daniel | last post by:
Hi, I am relative new to Python. Please tell me if the following is possible. I have a command line shell written in C. This shell executes some commands which I would like to import to the...
11
by: Soeren Sonnenburg | last post by:
Hi all, Just having started with python, I feel that simple array operations '*' and '+' don't do multiplication/addition but instead extend/join an array: a= >>> b= >>> a+b
1
by: Richard Townsend | last post by:
In the "Extending and Embedding" part of the Python documentation: section 5.4 "Extending Embedded Python" - it describes how to use a Python extension module from Python that is embedded in a C...
3
by: Marco Meoni | last post by:
Hi all! I've a problem with a C++ class that has to be included in a python application. One way to do it is Extending and Embedding the Python Interpreter Now i have 2 questions 1) Is there a...
5
by: vbgunz | last post by:
Hello everyone. I own two books. Learning Python and Python in a nutshell. When cross referencing the two books to try and clarify the ideas behind extending methods and delegates, this is where...
1
by: jeremito | last post by:
I am trying to learn how to extend and/or embed Python. I have looked at the document "Extending and Embedding the Python Interpreter" and also "Python/C API Reference Manual. In the examples...
7
by: Maximus Decimus | last post by:
HI all, I am using python v2.5 and I am an amateur working on python. I am extending python for my research work and would like some help and guidance w.r.t this matter from you experienced...
0
by: Tim Spens | last post by:
--- On Fri, 6/27/08, Tim Spens <t_spens@yahoo.comwrote: I think I know where the problem is but I'm unsure how to fix it. When I call Register_Handler(...) from python via...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.