473,396 Members | 1,864 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,396 software developers and data experts.

map/filter/reduce/lambda opinions and background unscientificmini-survey

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.

What really struck me, though, is the last line of the abstract:

"I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme
folks. :-)"

I disagree strongly with Guido's proposals, and i am not an ex-Lisp,
-Scheme or -any-other-functional-language programmer; my only other real
language is Java. I wonder if i'm an outlier.

So, if you're a pythonista who loves map and lambda, and disagrees with
Guido, what's your background? Functional or not?

tom

--
Batman always wins
Jul 19 '05
181 8582
Robert Kern wrote:
Dan Bishop wrote:
There's also the issue of having to rewrite old code.

It's Python 3000. You will have to rewrite old code regardless if reduce
stays.


And from what I understand Python 2.x will still be maintained and
supported. It will probably be more reliable than Python 3000 for a
version or two as well.

It's going to take time for all the batteries included to catch up, so
it won't be like we have to all of a sudden rewrite all the old Python
programs over night. We'll probably have a couple of years to do that
to our own programs if we decide it's worth while. And if not, Python
2.x will still work.

Jul 21 '05 #101
On Tuesday 05 July 2005 06:57 pm, Steven D'Aprano wrote:
On Tue, 05 Jul 2005 12:11:47 -0700, mcherm wrote:
And besides, "def" isn't a "magic" word... it's an abreviation for
"define"...


Really? I thought it was an abbreviation for "definition". As in,
"definition of MyFunc is..."


Does it matter? But no, "define" is correct, because the def
keyword is active. It is *not* a declaration of a function but
a command to define one then and there.
I hope that any student who didn't understand a word as
common as "define" wouldn't have graduated from our school.


How about tuple?


It's a generalization rather than a specialization:

double (or couple)
triple
quadruple
quintuple
sextuple
septuple
octuple
nontuple
....

Maybe a wee bit less obvious, but still understandable.

Besides, the existence of another poor choice of words wouldn't
make the first one any better, would it?

If you are arguing that "lambda" is the "right and proper"
word for this operator that Python should use, I still will
have to disagree.

OTOH, if you just want the functionality of lambda to remain,
I must say I agree. It's a useful construct.

But it *is* poorly named. It really stands out as the least
intuitive keyword in the language, IMHO.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 21 '05 #102
Terry Hancock wrote:
It's a generalization rather than a specialization:

double (or couple)
triple
quadruple
quintuple
sextuple
septuple
octuple
nontuple
...

Maybe a wee bit less obvious, but still understandable.


The general form is explicitly called an "n-tuple" or "tuple" in
mathematics.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Death to all fanatics!
-- Malaclypse the Younger
Jul 21 '05 #103
On Tuesday 05 July 2005 03:43 pm, Tom Anderson wrote:
I understand that the backslash is popular in some ivory-tower functional
languages. Currently, a backslash can be used for explicit line joining,
and is illegal elsewhere on a line outside a string literal, so i think
it's available for this. It would be utterly unpythonic to use puntuation
instead of a keyword, and it would make no sense to novices, but it would
scare the crap out of C programmers, which has to be worth something.


With list comprehensions and generators becoming so integral, I'm
not sure about "unpythonic". And a syntax just occured to me --
what about this:

[y*x for x,y]

?

(that is:

[<expression> for <argument list>]

It's just like the beginning of a list comprehension or generator, but
without the iterator. That implies that one must be given, and
the result is therefore a callable object.

Wouldn't do anything more or less than present day "lambda", but
gets rid of the weird keyword, and integrates nicely with list comps
and generators. It's currently a syntax error, and it requires no
special delimiter -- it's really just an extension of list comp syntax.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com

Jul 21 '05 #104
I said I'd drop the discussion about lambda, but this
isn't really the same discussion even if it is part of
the same thread. That's my excuse, and I'm sticking to it.

Terry Hancock wrote:
On Tuesday 05 July 2005 03:43 pm, Tom Anderson wrote:
I understand that the backslash is popular in some ivory-tower functional
languages. Currently, a backslash can be used for explicit line joining,
and is illegal elsewhere on a line outside a string literal, so i think
it's available for this. It would be utterly unpythonic to use puntuation
instead of a keyword, and it would make no sense to novices, but it would
scare the crap out of C programmers, which has to be worth something.

With list comprehensions and generators becoming so integral, I'm
not sure about "unpythonic". And a syntax just occured to me --
what about this:

[y*x for x,y]

?

(that is:

[<expression> for <argument list>]

It's just like the beginning of a list comprehension or generator, but
without the iterator. That implies that one must be given, and
the result is therefore a callable object.


That is a very long chain of implication:

"It looks like a list comprehension... but there is no
iterator... so we have to supply an iterator... so it
takes an argument... so it is a callable object... oh
and by the way, it can take any arguments, not just
iterators."

It is also far too easy to make a mistake, eg to write
something like newlist = [y*x for x,y] when you
actually wanted the list comp [y*x for x,y in L].

This would create an anonymous function where you
expected to create a list. It is hard to think of a
usage case where you didn't discover the error
reasonably soon, but it would be better for leaving the
iterator out of a list comp to remain a syntax error,
rather than produce an unexpected, but legal, object.

Besides, I think Guido should be very cautious about
introducing new features that use punctuation, instead
of keywords. We don't want to become perl do we? :-)

--
Steven.

Jul 21 '05 #105
Op 2005-07-01, Mike Meyer schreef <mw*@mired.org>:
"iK" <Ik@sdsfsfd.com> writes:
Seems like he wants python programmers to solve their problems all in the
same way. While that is great for corporate slaves it is terrible for the
creative programmer.


No, he wants Python to be Pythonic. TMTOWTDI is not Pythonic.


If Guido should change his mind on this, then it will be pythonic.
I don't think a concept that has so little meaning has any real
value.
Python is quickly becoming the visual basic of the 21 century. If you want
to have fun while getting some work done you need to look elsewhere. It's a
shame...


If you'd rather spend your time figuring out which of multiple ways to
do things is the best for the job at hand than producing code, there's
a language that makes TMTOWTDI a way of life.


There are always many ways to do things, and depending on circumstances
the best way to do something may differ every time.

So if python no longer allows multiple ways to do things, it won't help
the programmer. The programmer will now face the question if python
is still the right language to do the job.

--
Antoon Pardon
Jul 21 '05 #106
Op 2005-07-02, Mike Meyer schreef <mw*@mired.org>:
"Sean McIlroy" <se**********@yahoo.com> writes:
Peter Hansen wrote:
<snip>
Sean, what gave you the impression this would change?

if that's the case then list comprehensions and/or "first class
functions" are likely to be the next target.


The existence of list comprehensions are the reason that these
functions are going away, so they aren't likely to be next. It's all
part of "There should be one-- and preferably only one --obvious way
to do it."


IMO people concentrate too much on the "and preferably only one" part
of this.

If you really want at least one obvious way to do things then,
there also will be a lot of things that have more than one
obvious way. Trying to eliminate all those mulitiple obvious ways,
which seems to be one of the goals here, will result in removing
the one obvious way for doing other things.

--
Antoon Pardon
Jul 21 '05 #107
Full Acknowledge

Jul 21 '05 #108
"Terry Reedy" <tj*****@udel.edu> wrote:
"George Sakkis" <gs*****@rutgers.edu> wrote in message
news:11*********************@g43g2000cwa.googlegro ups.com...
Still it's hard to explain why four specific python keywords - def,
del, exec and elif - were chosen to be abbreviated,


Precedence in other languages and CS usage?


What precedence ? I don't know of another language that uses def or del
at least; even C++ which compared to python is much more terse uses
"delete" instead of del. And in any case, curly braces for grouping
statements is much more prevalent in other languages and CS usage but
(fortunately) python chose indentation.
So, who would object the full-word versions for python 3K ?
def -> define
del -> delete
exec -> execute


These three I might prefer to keep.
elif -> else if


This one I dislike and would prefer to write out. I never liked it in
whatever else language I first encountered it and still don't.


In contrast to the first three changes which would be straightforward,
changing "elif" to "else if" would add (a little?) complexity to the
parser by allowing "else" to be followed either by a colon (the only
choice now) or "if", though I don't think this would be a decisive
factor.

George

Jul 21 '05 #109
map, filter, reduce and lambda
Lisp constructs, bring flexibility to the language and is why I started
programming in python to begin with. Removing these constructs will be
a shame and one step closer to the death of some of the basic features
that make python great.

Jul 21 '05 #110
On Wed, 5 Jul 2005, George Sakkis wrote:
"Steven D'Aprano" <st***@REMOVETHIScyber.com.au> wrote:
On Tue, 05 Jul 2005 09:46:41 -0500, Terry Hancock wrote: [snip]
Def would be short for ... defend? defile? defer? defame? default? deflect?

There's always *something* to learn. Why def instead of define? Because
"easy to write" beats "instantly obvious to a beginner", if the word is
used all the time and is easy to memorize.


Still it's hard to explain why four specific python keywords - def,
del, exec and elif - were chosen to be abbreviated, while all the rest
are full words (http://docs.python.org/ref/keywords.html). "Ease of
typing" is a joke for an excuse;


For exec and probably del, yes, but def and elif are two of the most
frequently used keywords in the language, so i think it's reasonable to
keep them short.
So, who would object the full-word versions for python 3K ?

def -> define
I'd keep this short - it's one of the most commonly-used keywords. It's
particularly commonly used if you break your programs down into lots of
little functions; since this is, IMHO, something we want to encourage
people to do, we should strive to minimise boilerplate.
del -> delete
How about just getting rid of del? Removal from collections could be done
with a method call, and i'm not convinced that deleting variables is
something we really need to be able to do (most other languages manage
without it).
exec -> execute
This should be a function somewhere, maybe a builtin, maybe not - it
absolutely should not be a keyword. What that function should be called, i
don't know!
elif -> else if


I'm not sure about splitting it into two words; there's currently a very
simple relationship between flow control keywords, meanings, and blocks of
code, which would be broken if we moved to using "else if". I don't know
that this relationship is actually important, though.

tom

--
Don't believe his lies.
Jul 21 '05 #111
On Wed, 6 Jul 2005, Terry Hancock wrote:
On Tuesday 05 July 2005 03:43 pm, Tom Anderson wrote:
I understand that the backslash is popular in some ivory-tower
functional languages. Currently, a backslash can be used for explicit
line joining, and is illegal elsewhere on a line outside a string
literal, so i think it's available for this. It would be utterly
unpythonic to use puntuation instead of a keyword, and it would make no
sense to novices, but it would scare the crap out of C programmers,
which has to be worth something.
With list comprehensions and generators becoming so integral, I'm
not sure about "unpythonic".


I'm going to resist the temptation to argue that list comps are themselves
unpythonic :).

Hang on, where's the punctuation in either of those? They *are* done with
keywords! A generator is just a function with "yield" instead of "return",
list comprehensions are just list literals where the explicit sequence of
items is replaced with code producing them, using the keywords "for", "in"
and "if", and a generator expression is a list comp *without any
punctuation!*
And a syntax just occured to me -- what about this:

[y*x for x,y]

?


Terrible. Square brackets mean a list, and a lambda is not anything like a
list.

I see where you're coming from, though; a lambda is a lot like the first
half of a list comp that's broken off and is roaming free. I can't think
of a good syntax for it, though.

tom

--
find porn apricot
Jul 21 '05 #112
Tom Anderson wrote:
How about just getting rid of del? Removal from collections could be
done with a method call, and i'm not convinced that deleting variables
is something we really need to be able to do (most other languages
manage without it).


Arguing the case for del: how would I, in doing automated testing,
ensure that I've returned everything to a "clean" starting point in all
cases if I can't delete variables? Sometimes a global is the simplest
way to do something... how do I delete a global if not with "del"?

-Peter
Jul 21 '05 #113
[Tom Anderson]
del -> delete
How about just getting rid of del? [...] i'm not convinced that
deleting variables is something we really need to be able to do
While surely not in every program, I still use `del' often. Compare:

x = None
del x

when the goal is to cut the reference being held in x. Both statements
do it, yet the intent is expressed more legibly by the second.
(most other languages manage without it).


Hardly an excuse against some good ideas Python has on its own! :-)

--
François Pinard http://pinard.progiciels-bpi.ca
Jul 21 '05 #114
Peter Hansen wrote:
Arguing the case for del: how would I, in doing automated testing,
ensure that I've returned everything to a "clean" starting point in all
cases if I can't delete variables? Sometimes a global is the simplest
way to do something... how do I delete a global if not with "del"?


globals ().__delitem__ (varname)

except that the method would probably be called delete.

Daniel
Jul 21 '05 #115
Tom Anderson wrote:
del -> delete

How about just getting rid of del? Removal from collections could be
done with a method call, and i'm not convinced that deleting variables
is something we really need to be able to do (most other languages
manage without it).


Since this is a Python 3k item... What would be the consequence of
making None the default value of an undefined name? And then assigning
a name to None as a way to delete it?

Some benefits
=============

*No more NamesError exceptions!

print value
None
value = 25
print value 25


value = None #same as 'del value'
*No initialization needed for a while loop!

While not something:
if <condition>:
something = True
*Test if name exists without using a try-except!

if something == None:
something = value
*And of course one less keyword!
Any drawbacks?
Cheers,
Ron

PS... not much sleep last night, so this may not be well thought out.

Jul 21 '05 #116
On Wed, 06 Jul 2005 14:33:47 GMT,
Ron Adam <rr*@ronadam.com> wrote:
Since this is a Python 3k item... What would be the consequence of
making None the default value of an undefined name? And then assigning
a name to None as a way to delete it?
[ ... ]
Any drawbacks?


Lots more hard-to-find errors from code like this:

filehandle = open( 'somefile' )
do_something_with_an_open_file( file_handle )
filehandle.close( )

Regards,
Dan

--
Dan Sommers
<http://www.tombstonezero.net/dan/>
Jul 21 '05 #117
Terry Hancock wrote:
And a syntax just occured to me -- what about this:

[y*x for x,y]

?

(that is:

[<expression> for <argument list>]


If you haven't already, see:

http://wiki.python.org/moin/AlternateLambdaSyntax

for other similar proposals.

STeVe
Jul 21 '05 #118
Ron Adam wrote:
Yes, I think a different key word would help. My current favorite
alternative is to put it in parentheses similar to list comprehensions
and use "let".

(let x,y return x+y)


If you haven't already, see:

http://wiki.python.org/moin/AlternateLambdaSyntax

for other similar proposals.

STeVe
Jul 21 '05 #119
Peter Hansen wrote:
Tom Anderson wrote:
How about just getting rid of del? Removal from collections could be
done with a method call, and i'm not convinced that deleting variables
is something we really need to be able to do (most other languages
manage without it).


Arguing the case for del: how would I, in doing automated testing,
ensure that I've returned everything to a "clean" starting point in all
cases if I can't delete variables? Sometimes a global is the simplest
way to do something... how do I delete a global if not with "del"?

I generally find that unit tests force me to structure the code in a
cleaner manner, e.g. to not use globals as much, but if you do need to
delete a global you do it in exactly the same way as you delete anything:
use the "del" statement:
x = 3
def f(): global x
del x

x 3 f()
x
Traceback (most recent call last):
File "<pyshell#7>", line 1, in -toplevel-
x
NameError: name 'x' is not defined


Where I have used 'del' in a unit test it has been to delete local
variables rather than globals. Specifically I wanted to ensure that some
data structures were being torn down properly, so the test went something
like this:

setup: creates a weakref dictionary.

teardown: asserts that the weakref dictionary is empty.

then each test does:

try:
create something
add it to the weakref dictionary
then test it
finally:
use del to remove local variables
force a garbage collection

Without the del, when a test fails you get two failures, because the
traceback information keeps the variables alive.
Jul 21 '05 #120
On Wed, 06 Jul 2005 14:28:55 +0100, Tom Anderson wrote:
del -> delete
How about just getting rid of del? Removal from collections could be done
with a method call,


Which would be called object.del() I presume. And that opens a big
can of worms.

Suppose we have a list L = [4, 3, 2, 1, 0], what should L.del(1) do?

It looks like it should result in L becoming [4, 3, 2, 0]. An easy mistake
to make, if you forget that the argument is (presumably) an index.
You could make it clear by insisting on L.del[1] but that requires a big
change in Python's syntax.

What should L.del() do, with no arguments? Raise an error?

Now, you have something like this:

class thing:
pass
obj = thing()
obj.alpha = [4, 3, 2, 1, 0]
obj.beta = 5

Python's object model suggests that obj.alpha.del() should call
alpha's del method, in the same way that obj.alpha.append() would call
alpha's append method.

So how do you delete obj.alpha? obj.del("alpha") might work. But what if
obj itself is a mapping, with a key "alpha" as well as an attribute alpha.
Which one should obj.del("alpha") delete?

Now, if you said that L.del() should raise an exception earlier, what
about obj.beta.del()?
Presumably every object automatically has a del method, so you
don't have to program a del method yourself. obj.del is a method object.
So it has a del method. (Yes, sometimes you want to delete methods.
Functions are first class objects in Python.) Which has a del method.
Which has a del method.

What should obj.del.del.del.del.del.del.del.del.del() do?

and i'm not convinced that deleting variables is
something we really need to be able to do (most other languages manage
without it).


Most other languages don't have namespaces that can get polluted, or
on-the-fly creation of variables. Most other languages don't consider
variables to be simply attributes of a module object. And most other
languages don't allow you to run interactive sessions where it is easy to
mistakenly make variables you don't want.

py> x = 1
py> u = x+2 # oops, typo, meant y not u
py> del u # prevent confusion in the programmer's mind

It is also useful sometimes to delete a module object from the top level
namespace before re-importing it, rather than merely reloading it. That
requires being able to delete a variable.

In summary: del being a keyword works. del() being an object method is
unclear, confusing and complicated.
--
Steven.
Jul 21 '05 #121
Dan Sommers wrote:
On Wed, 06 Jul 2005 14:33:47 GMT,
Ron Adam <rr*@ronadam.com> wrote:

Since this is a Python 3k item... What would be the consequence of
making None the default value of an undefined name? And then assigning
a name to None as a way to delete it?

[ ... ]

Any drawbacks?

Lots more hard-to-find errors from code like this:

filehandle = open( 'somefile' )
do_something_with_an_open_file( file_handle )
filehandle.close( )

Regards,
Dan

If do_something_with_an_open_file() is not defined. Then you will get:

TypeError: 'NoneType' object is not callable
If "file_handle" (vs "filehandle") is None. Then you will still get an
error as soon as you tried to use the invalid file handle.

AttributeError: 'NoneType' object has no attribute 'read'
If the error was filehundle.close() you will get:

AttributeError: 'NoneType' object has no attribute 'close'
I don't think any of those would be hard to find.
Cheers,
Ron

Jul 21 '05 #122
> Here's a couple of examples from my own code:

# from a Banzhaf Power Index calculator
# adds things that aren't numbers
return reduce(operator.add,
(VoteDistributionTable({0: 1, v: 1}) for v in electoral_votes))
return sum([VoteDistributionTable({0:1, v:1} for v in
electoral_votes],VoteDistributionTable({}))
Any time you use operator.add, you can probably use
sum(sequence,initialvalue)
# from a custom numeric class
# converts a tuple of digits into a number
mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa)


I'll admit I can't figure out a way to replace reduce without writing
some ugly code here, but I doubt these sorts of things appear often.

Jul 21 '05 #123
Devan L wrote:
# from a custom numeric class
# converts a tuple of digits into a number
mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa)

I'll admit I can't figure out a way to replace reduce without writing
some ugly code here, but I doubt these sorts of things appear often.


It's not ugly or difficult to define a named function.

def digits_to_value(seq):
v = 0
for d in seq:
v = v*10+d
return v
Then where you need it.

mantissa = sign * digits_to_value(mantissa)
One of the motivations is the reduce-lambda expressions are a lot harder
to read than a properly named function.

And a function will often work faster than the reduce-lambda version as
well.

Cheers,
Ron
Jul 21 '05 #124
Devan L wrote:
Here's a couple of examples from my own code:

# from a Banzhaf Power Index calculator
# adds things that aren't numbers
return reduce(operator.add,
(VoteDistributionTable({0: 1, v: 1}) for v in electoral_votes))


return sum([VoteDistributionTable({0:1, v:1} for v in
electoral_votes],VoteDistributionTable({}))
Any time you use operator.add, you can probably use
sum(sequence,initialvalue)


Actually, it's

sum([VoteDistributionTable({0:1, v:1}) for v in electoral_votes],
VoteDistributionTable({0: 1}))

but you're right about being able to use sum here.
# from a custom numeric class
# converts a tuple of digits into a number
mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa)


I'll admit I can't figure out a way to replace reduce without writing
some ugly code here, but I doubt these sorts of things appear often.


Of the quarter-megabyte of my Python code currently on my hard drive, I
can find two reduces that can't be replaced by sum, product, any, or
all. The other one is

return reduce(lambda x, y: x << 1 | y, bits)

Jul 21 '05 #125
Ron Adam wrote:
Dan Sommers wrote:
Lots more hard-to-find errors from code like this:
filehandle = open( 'somefile' )
do_something_with_an_open_file( file_handle )
filehandle.close( )


If do_something_with_an_open_file() is not defined. Then you will get:
TypeError: 'NoneType' object is not callable
If "file_handle" (vs "filehandle") is None. Then you will still get an
error as soon as you tried to use the invalid file handle.

Ah, but where you use it can now far from the error in the source. The
None could get packed up in a tuple, stored in a dictionary, all manner
of strange things before discovering it was an unavailable value. I
would love the time back that I spent chasing bugs when Smalltalk told
me (I forget the exact phrasing) "nil does not respond to message abc."
My first reaction was always, "of course it doesn't, this message is
useless." You really want the error to happen as close to the problem
as possible.

--Scott David Daniels
Sc***********@Acm.Org
Jul 21 '05 #126
On Wed, 06 Jul 2005 15:18:31 GMT,
Ron Adam <rr*@ronadam.com> wrote:
Dan Sommers wrote:
On Wed, 06 Jul 2005 14:33:47 GMT,
Ron Adam <rr*@ronadam.com> wrote:
Since this is a Python 3k item... What would be the consequence of
making None the default value of an undefined name? And then assigning
a name to None as a way to delete it? [ ... ]
Any drawbacks?

Lots more hard-to-find errors from code like this:
filehandle = open( 'somefile' )
do_something_with_an_open_file( file_handle )
filehandle.close( )
Regards,
Dan


[ ... ]
If "file_handle" (vs "filehandle") is None. Then you will still get an
error as soon as you tried to use the invalid file handle. AttributeError: 'NoneType' object has no attribute 'read'
This is the one of which I was thinking. So you see this error at the
end of a (long) traceback, and try to figure out where along the (long)
line of function calls I typed the wrong name. Currently, the very end
of the traceback points you right at the bad code and says "NameError:
name 'filehandle' is not defined," which tells me (very nearly) exactly
what I did wrong.
If the error was filehundle.close() you will get:
s/u/a/

;-)
I don't think any of those would be hard to find.


I guess it depends on how long your traceback is and how big those
functions are. Also, from the Zen:

Explicit is better than implicit.

although from previous threads, we know that every pythonista has his or
her own definitions of "explicit" and "implicit."

Regards,
Dan

--
Dan Sommers
<http://www.tombstonezero.net/dan/>
Jul 21 '05 #127
On 2005-07-06 02:46:27, George Sakkis wrote:
So, who would object the full-word versions for python 3K ?
def -> define
del -> delete
exec -> execute
elif -> else if


I'm all for it. I would even be tempted of changing def to function, but
it would look stupid in:

class A:
function make_my_day(self):
return "Your day"
a = A()


since a.make_my_day() is really a method, not a standalone function.
We could use "function" instead of "lambda" though =)

Objections for the "else if" might be that it sounds like you can
replace "else if" with "else x=94" if you want. Thumbs up for "else if"
because it explains what it is much better than "elif". "elseif" ?

--
Stian Søiland Work toward win-win situation. Win-lose
Trondheim, Norway is where you win and the other lose.
http://soiland.no/ Lose-lose and lose-win are left as an
exercise to the reader. [Limoncelli/Hogan]
Jul 21 '05 #128
On 2005-07-06 01:46:05, Steven D'Aprano wrote:
I had NEVER even heard the word "tuple" before learning Python. I spent
weeks mispelling it as "turple", and I finally had to look it up in a
dictionary to see if it was a real English word. Out of the four English
dictionaries in my house, none of them have the word.
Agree, I have the problem of writing "tupple" in all comments and
documentations. It's a weird word indeed =)
t = immutable_list(L)
map(anonymous_function x: x+1, L)


Hey, I know!

t = python.util.ImmutableArrayList.fromCollection(L.ge tAbstractCollection())

python.util.functional.applyFunctionOnCollection(
(class implements python.util.functional.AnonymousFunction:
def anonymousFunction(x):
return x+1
), L)

--
Stian Søiland Work toward win-win situation. Win-lose
Trondheim, Norway is where you win and the other lose.
http://soiland.no/ Lose-lose and lose-win are left as an
exercise to the reader. [Limoncelli/Hogan]
Jul 21 '05 #129
On 2005-07-06 16:33:47, Ron Adam wrote:
*No more NamesError exceptions!
print value
>> None

So you could do lot's of funny things like:

def my_fun(extra_args=None):
if not extraargs:
print "Behave normally"
extra_args = 1337

if extraargs:
asdkjaskdj
..
if extra_args:
kajsdkasjd

and get no errors at all, but switching back and forth between the
different behavours because you actually did expect None, but from an
EXISTING variable.
*No initialization needed for a while loop!

while not something:
if <condition>:
something = True
This is the only "good" case I could find, but opening for a lots of
errors when you get used to that kind of coding:

while not finished:
foo()
finished = calculate_something()

(..)
(..) # Added another loop
while not finished:
bar()
finished = other_calculation()

Guess the amount of fun trying to find out the different errors that
could occur when bar() does not run as it should because the previous
"finished" variable changes the logic.

If you want to experiment with such designs, all you need to do is to
start your code with <?php

*Test if name exists without using a try-except!
if something == None:
something = value


Now this is a question from newcomers on #python each day.. "How do I
check if a variable is set?".

Why do you want to check if a variable is set at all? If you have so
many places the variable could or could not be set, your program design
is basically flawed and must be refactored.

--
Stian Søiland Work toward win-win situation. Win-lose
Trondheim, Norway is where you win and the other lose.
http://soiland.no/ Lose-lose and lose-win are left as an
exercise to the reader. [Limoncelli/Hogan]
Jul 21 '05 #130
On 2005-07-06 07:00:04, Steven D'Aprano wrote:
map(lambda x: if x == 0: 1; else: math.sin(x)/x,
myList)


And now for the "readable" list comprehension version:

[x==0 and 1 or math.sin(x)/x for x in myList]

Now even though I'm into the short-circuiting of and-or and even
occasionally have used such masturbation techniques as this, I don't
think it qualifies as pythonic.

If it was me, I would probably even have written:

[x and math.sin(x)/x or 1 for x in myList]

--
Stian Søiland Work toward win-win situation. Win-lose
Trondheim, Norway is where you win and the other lose.
http://soiland.no/ Lose-lose and lose-win are left as an
exercise to the reader. [Limoncelli/Hogan]
Jul 21 '05 #131
Dan Sommers wrote:
AttributeError: 'NoneType' object has no attribute 'read'

This is the one of which I was thinking. So you see this error at the
end of a (long) traceback, and try to figure out where along the (long)
line of function calls I typed the wrong name. Currently, the very end
of the traceback points you right at the bad code and says "NameError:
name 'filehandle' is not defined," which tells me (very nearly) exactly
what I did wrong.


The actual error could be improved a bit to refer the the name of the
and line the error is in. Which would help some.

AttributeError: 'NoneType' object "file_handle" has no attribute
'read'

I guess it depends on how long your traceback is and how big those
functions are. Also, from the Zen:

Explicit is better than implicit.

although from previous threads, we know that every pythonista has his or
her own definitions of "explicit" and "implicit."
True, but this isn't any different than any other 'Type' error, or value
error. And considerably easier to find than one off errors.

There would be more restrictions on None than there are now so it
wouldn't be as bad as it seems. For example passing a None in a
function would give an error as the name would be deleted before the
function actually gets it.

So doing this would give an error for functions that require an argument.

def foo(x):
return x

a = None
b = foo(a) # error because a dissapears before foo gets it.
TypeError: foo() takes exactly 1 argument(0 given)

So they wouldn't propagate like you would expect.

Hmmm.... interesting that would mean... lets see.
1. var = None # removes ref var, this is ok

2. None = var # give an error of course

3. var = undefined_var # same as "var = None", that's a problem!

Ok... this must give an error because it would delete var silently!
Definitely not good. So going on, on that basis.

4. undefined == None # Special case, evaluates to True.

5. def foo():return None # same as return without args

6. x = foo() # Would give an error if foo returns None

This might be an improvement over current behavior. Breaks a lot of
current code though.

7. if undefined: # error

8. if undefined==None # Special case -> True

Good for checking if vars exist.

9. if undefined==False # Error, None!=False (or True)

9. while undefined: # error

10 while undefined==None:

Possible loop till defined behavior.
Ok... and undefined var returning None is a bad idea, but using None to
del names could still work. And (undefined==None) could be a special
case for checking if a variable is defined. Otherwise using an
undefined name should give an error as it currently does.

Cheers,
Ron

Regards,
Dan


Jul 21 '05 #132
Scott David Daniels wrote:
Ron Adam wrote:
Dan Sommers wrote:
Lots more hard-to-find errors from code like this:
filehandle = open( 'somefile' )
do_something_with_an_open_file( file_handle )
filehandle.close( )

If do_something_with_an_open_file() is not defined. Then you will get:
TypeError: 'NoneType' object is not callable
If "file_handle" (vs "filehandle") is None. Then you will still get
an error as soon as you tried to use the invalid file handle.


Ah, but where you use it can now far from the error in the source. The
None could get packed up in a tuple, stored in a dictionary, all manner
of strange things before discovering it was an unavailable value. I
would love the time back that I spent chasing bugs when Smalltalk told
me (I forget the exact phrasing) "nil does not respond to message abc."
My first reaction was always, "of course it doesn't, this message is
useless." You really want the error to happen as close to the problem
as possible.

--Scott David Daniels
Sc***********@Acm.Org

Yep, I concede. The problem is if undefined names return None, and None
deletes a name, then assigning a undefined name to an existing name,
will delete it silently.

Definitely Not good!

So it should give an error as it currently does if an undefined name is
used on the right side of an =.

It could still work otherwise to unbind names, and (undefined_name ==
None) could still be a valid way to check if a name is defined without
using a try-except.

But it would definitely be a Python 3000 change as all the functions
that return None would then cause errors.

Cheers,
Ron

Jul 21 '05 #133

"George Sakkis" <gs*****@rutgers.edu> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
"Terry Reedy" <tj*****@udel.edu> wrote:
"George Sakkis" <gs*****@rutgers.edu> wrote in message
news:11*********************@g43g2000cwa.googlegro ups.com...
> Still it's hard to explain why four specific python keywords - def,
> del, exec and elif - were chosen to be abbreviated,


Precedence in other languages and CS usage?


What precedence ? I don't know of another language that uses def or del


DOS used DEL, BASIC used DEF.

tjr

Jul 21 '05 #134
On 2005-07-06 00:50:30, Ron Adam wrote:
This is probably the more correct way to do it. :-)

def flatten(seq):
i = 0
while i!=len(seq):
while isinstance(seq[i],list):
seq[i:i+1]=seq[i]
i+=1
return seq


Or what about a recursive generator?

a = [1,2,[[3,4],5,6],7,8,[9],[],]

def flatten(item):
try:
iterable = iter(item)
except TypeError:
yield item # inner/final clause
else:
for elem in iterable:
# yield_return flatten(elem)
for x in flatten(elem):
yield x

print list(flatten(a))
Of course, one of the problems here is that there is no way to
yield_return except to create yet another stupid-looking for-loop. This
is one of the flaws in the current generator functionallity of Python.

Using yield_return could also make it more obvious that the result is in
fact a generator in functions that wrap generators.

--
Stian Søiland Work toward win-win situation. Win-lose
Trondheim, Norway is where you win and the other lose.
http://soiland.no/ Lose-lose and lose-win are left as an
exercise to the reader. [Limoncelli/Hogan]
Jul 21 '05 #135
Stian Søiland wrote:
On 2005-07-06 16:33:47, Ron Adam wrote:

*No more NamesError exceptions!
print value
>> None

So you could do lot's of funny things like:

def my_fun(extra_args=None):
if not extraargs:
print "Behave normally"
extra_args = 1337

if extraargs:
asdkjaskdj
..
if extra_args:
kajsdkasjd
Yes, returning None from an undefined name is DOA.

In the above case you would get an error by the way.

"if extraargs:" would evaluate to "if None:", which would evaluate to
"if:" which would give you an error.

*No initialization needed for a while loop!

while not something:
if <condition>:
something = True

This is the only "good" case I could find, but opening for a lots of
errors when you get used to that kind of coding:


It would need to be.. while not (something==None): and the compiler
would need to handle it as a special case. But this one could still
work without allowing something=undefined to be valid.
while not finished:
foo()
finished = calculate_something()

(..)
(..) # Added another loop
while not finished:
bar()
finished = other_calculation()

Guess the amount of fun trying to find out the different errors that
could occur when bar() does not run as it should because the previous
"finished" variable changes the logic.


It's not really differnt than any other value test we currently use.

notfinished = True
while notfinished:
notfinished = (condition)

# Need to set notfinished back to True here.
while notfinished:
<morestuff>

*Test if name exists without using a try-except!
if something == None:
something = value


Now this is a question from newcomers on #python each day.. "How do I
check if a variable is set?".

Why do you want to check if a variable is set at all? If you have so
many places the variable could or could not be set, your program design
is basically flawed and must be refactored.


There's a few places the Python library that do exactly that.

try:
value
except:
value = something

I admit it's something that should be avoided if possible because if
there's doubt that a name exists, then there would also be doubt
concerning where it came from and weather or not it's value/object is valid.

Anyway, it was an interesting but flawed idea, I should of thought more
about it before posting it.

Cheers,
Ron



Jul 21 '05 #136
On Wed, 6 Jul 2005 20:42:51 +0200,
Stian Søiland <st***@soiland.no> wrote:
I'm all for it. I would even be tempted of changing def to function,
but it would look stupid in: class A:
function make_my_day(self):
return "Your day"
a = A()
since a.make_my_day() is really a method, not a standalone function.
We could use "function" instead of "lambda" though =)


So use "method" instead, which has the added advantage of implicity
declaring an extra argument named "this":

class A:
method __init__():
this.x = 0
method make_my_day(foo):
this.x += foo

there-aren't-enough-winks-in-the-universe'ly yours,
Dan

--
Dan Sommers
<http://www.tombstonezero.net/dan/>
Jul 21 '05 #137
Tom Anderson a écrit :
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.

What really struck me, though, is the last line of the abstract:

"I expect tons of disagreement in the feedback, all from
ex-Lisp-or-Scheme folks. :-)"

I disagree strongly with Guido's proposals, and i am not an ex-Lisp,
-Scheme or -any-other-functional-language programmer; my only other real
language is Java. I wonder if i'm an outlier.

So, if you're a pythonista who loves map and lambda, and disagrees with
Guido, what's your background? Functional or not?


I discovered FP with David Mertz's papers about FP in Python. I had
never read nor write a line of lisp, scheme, haskell, caml etc before.
And I'd certainly start thinking of choosing another MYFL if anonymous
functions where to disappear from Python. Note that I said "anonymous
functions", not "lambda". Concerning map, filter, reduce etc, these
functions can live in a separate module, and this wouldn't bother me.
But anonymous functions are part of the language syntax, so there is no
work-around.

My 2 (euro) cents
Jul 21 '05 #138
Stian Søiland a écrit :
(snip) Hey, I know!

t = python.util.ImmutableArrayList.fromCollection(L.ge tAbstractCollection())

python.util.functional.applyFunctionOnCollection(
(class implements python.util.functional.AnonymousFunction:
def anonymousFunction(x):
return x+1
), L)

Reminds me of something, but what ?-)
Jul 21 '05 #139
Ron Adam wrote:
"if extraargs:" would evaluate to "if None:", which would evaluate to
"if:" which would give you an error.


In what way is "if None:" equivalent to "if:"?
--
Benji York
Jul 21 '05 #140
I think in some contextes map is more readable than [f() for i in S]
because it's more verbatim
Removing lamdba would be reduce readability of Python, I think here
for examble of code like

class App:
....
....
def drawLines(self, event):
from random import randint
r = lambda : randint(1, 100)
self.canvas.create_line(r(), r(), r(), r())

defining one extra function would only confuse and
self.canvas.create_line(r(1, 100), r(1, 100), r(1, 100), r(1, 100))
is not very nice to look at

and what about creating one liner factories like
from math import log10
log = lambda basis: lambda x: log10(x) / log10(basis)
log2 = log(2)
log2(2**10) -> 10.0

I would consider it as a great loss for Python
if lambda will disappear

Jul 21 '05 #141
Daniel Schüle wrote:
Removing lamdba would be reduce readability of Python, I think here
for examble of code like

class App:
....
....
def drawLines(self, event):
from random import randint
r = lambda : randint(1, 100)
self.canvas.create_line(r(), r(), r(), r())

defining one extra function would only confuse and
But you just did define one extra function!!

If you're really afraid of two lines, write it as:

def r(): randint(1, 100)

This is definitely a bad case for an anonymous function because it's not
anonymous! You give it a name, r.
and what about creating one liner factories like
from math import log10
log = lambda basis: lambda x: log10(x) / log10(basis)
log2 = log(2)
log2(2**10) -> 10.0


This is slightly better, because at least one of your functions really
is anonymous. I'm not really sure I'm convinced that it's any better
than this though:

def log(base):
def log_in_base(x):
return log10(x)/log10(base)
return log_in_base

because when I first read the code, I didn't catch the second, nested
lambda. Of course, with a syntax-highlighting editor, I probably would
have.

Again though, to fix your abuse of anonymous function syntax for
non-anonymous functions, you should write this as:

def log(basis):
return lambda x: log10(x) / log10(basis)

Or if you're afraid of multiple lines:

def log(basis): return lambda x: log10(x) / log10(basis)

STeVe
Jul 21 '05 #142
Tom Anderson <tw**@urchin.earth.li> writes:
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.

What really struck me, though, is the last line of the abstract:

"I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme
folks. :-)"

I disagree strongly with Guido's proposals, and i am not an ex-Lisp,
-Scheme or -any-other-functional-language programmer; my only other real
language is Java. I wonder if i'm an outlier.

So, if you're a pythonista who loves map and lambda, and disagrees with
Guido, what's your background? Functional or not?


Not. But I've gained a real appreciation for functional programming
from my use of both C++ and Python.

--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
Jul 21 '05 #143
Bruno Desthuilliers <bd*****************@free.quelquepart.fr> writes:
I discovered FP with David Mertz's papers about FP in Python. I had
never read nor write a line of lisp, scheme, haskell, caml etc before.
And I'd certainly start thinking of choosing another MYFL if anonymous
functions where to disappear from Python. Note that I said "anonymous
functions", not "lambda". Concerning map, filter, reduce etc, these
functions can live in a separate module, and this wouldn't bother me.
But anonymous functions are part of the language syntax, so there is no
work-around.


Actually I'm pretty sure there is. It should be possible to
re-implement the Boost Lambda library in Python:

http://www.boost.org/libs/lambda

Compared with in-language lambda support it would have the advantage
of brevity and clarity for very small functions, but there are lots of
disadvantages, too. I wonder how Guido would feel if people started
using a (relatively) slow library solution with odd warts as a
consequence of dropping real lambdas.

--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
Jul 21 '05 #144
Benji York wrote:
Ron Adam wrote:
"if extraargs:" would evaluate to "if None:", which would evaluate to
"if:" which would give you an error.

In what way is "if None:" equivalent to "if:"?
--
Benji York


It's not now.. but if None where to really represent the concept None,
as in not bound to anything, it would evaluate to nothing.

Given the statement:

a = None

And the following are all true:

a == None
(a) == (None)
(a) == ()
(None) == ()

Then this "conceptual" comparison should also be true:

if (None): == if ():
if (): == if:
Comparing if's like that wouldn't be a valid code of course, but it
demonstrates the consistency in which the comparison is made.

I think. ;-)

Of course this is all hypothetical anyways, so it could be what ever we
decide makes the most since, include not changing anything.

Cheers,
Ron
Jul 21 '05 #145
Ron Adam <rr*@ronadam.com> writes:
So doing this would give an error for functions that require an argument.

def foo(x):
return x

a = None
b = foo(a) # error because a dissapears before foo gets it.
So how do I pass None to a function?
>>TypeError: foo() takes exactly 1 argument(0 given)

So they wouldn't propagate like you would expect.

Hmmm.... interesting that would mean... lets see.
1. var = None # removes ref var, this is ok

2. None = var # give an error of course

3. var = undefined_var # same as "var = None", that's a problem!

Ok... this must give an error because it would delete var silently!
Definitely not good. So going on, on that basis.

4. undefined == None # Special case, evaluates to True.

5. def foo():return None # same as return without args

6. x = foo() # Would give an error if foo returns None


Why? Shouldn't it delete x?
This might be an improvement over current behavior. Breaks a lot of
current code though.


I don't think so. I've programmed in langauges that gave undefined
variables a value rather than an exception. It almost inevitabley led
to hard-to-find bugs.

FORTRAN used to give all variables a type, so that a typo in a
variable name could well lead to a valid expression. The technic for
disabling this was baroque ("IMPLICIT BOOLEAN*1 A-Z"), but so common
they invented a syntax for it in later versions of FORTRAN ("IMPLICIT
NONE").

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 21 '05 #146
Stian Søiland wrote:
Or what about a recursive generator?

a = [1,2,[[3,4],5,6],7,8,[9],[],]

def flatten(item):
try:
iterable = iter(item)
except TypeError:
yield item # inner/final clause
else:
for elem in iterable:
# yield_return flatten(elem)
for x in flatten(elem):
yield x

print list(flatten(a))

Ok, lets see... I found a few problems with the testing (and corrected
it) so the scores have changed. My sort in place routines were
cheating because the lists weren't reset between runs so it had the
advantage after the first time though of sorting already sorted list.
And Tom's recursive no copy had a bug which kept a reference to one of
it's arguments so it's output was doubling the list. And the hasattr
function was slowing everyone down, so I inlined it for everyone who
used it.

Using a 1000 item list and starting with a flat list and increasing the
depth (unflatten) to shallow, medium, and deep. (but not so deep to
cause recursion errors.)

And the winners are...

Python 2.3.5 (#62, Feb 8 2005, 16:23:02)
[MSC v.1200 32 bit (Intel)] on win32
IDLE 1.0.5

Size: 1000 Depth: 0
georges_recursive_flatten: 0.00212513042834
rons_nonrecursive_flatten: 0.00394323859609
toms_recursive_zerocopy_flatten: 0.00254557492644
toms_iterative_zerocopy_flatten: 0.0024332701505
devans_smallest_recursive_flatten: 0.011406198274
rons_nonrecursive_inplace_flatten: 0.00149963193644
stians_flatten_generator: 0.00798257879114

Size: 1000 Depth: 25
georges_recursive_flatten: 0.0639824335217
rons_nonrecursive_flatten: 0.0853463219487
toms_recursive_zerocopy_flatten: 0.0471856059917
toms_iterative_zerocopy_flatten: 0.188437915992
devans_smallest_recursive_flatten: 0.0844073757976
rons_nonrecursive_inplace_flatten: 0.0847048996452
stians_flatten_generator: 0.0495694285169

Size: 1000 Depth: 50
georges_recursive_flatten: 0.134300309118
rons_nonrecursive_flatten: 0.183646245542
toms_recursive_zerocopy_flatten: 0.0886252303017
toms_iterative_zerocopy_flatten: 0.371141304272
devans_smallest_recursive_flatten: 0.185467985456
rons_nonrecursive_inplace_flatten: 0.188668392212
stians_flatten_generator: 0.090114246364

Size: 1000 Depth: 100
georges_recursive_flatten: 0.248168133101
rons_nonrecursive_flatten: 0.380992276951
toms_recursive_zerocopy_flatten: 0.177362486014
toms_iterative_zerocopy_flatten: 0.741958265645
devans_smallest_recursive_flatten: 0.306604051632
rons_nonrecursive_inplace_flatten: 0.393641091256
stians_flatten_generator: 0.177185368532

Stians flatten generator is nearly tied with Tom's recursive zerocopy.
My nonrecursive inplace is faster for very shallow lists, but Tom's
quickly over takes it. I was able to improve my nonrecursive copy
flatten a bit, but not enough to matter. So Tom's recursive zerocopy is
the overall winner with Stian's flatten generator close behind and just
barely winning out in the very deep catagory. But they're all
respectable times so everyone wins. ;-)

And here's the source code.

Cheers, :-)
Ron

# -------------------------------

import sys
import time

TIMERS = {"win32": time.clock}
timer = TIMERS.get(sys.platform, time.time)

def timeit(fn,*arg):
t0 = timer()
r = fn(*arg)
t1 = timer()
return float(t1-t0), r

# --------------------------------

def georges_recursive_flatten(seq):
return reduce(_accum, seq, [])

def _accum(a, item):
if hasattr(item, "__iter__"):
a.extend(georges_recursive_flatten(item))
else:
a.append(item)
return a
def rons_nonrecursive_flatten(seq):
a = []
while seq:
if hasattr(seq[0], "__iter__"):
seq[0:1] = seq[0]
else:
a.append(seq.pop(0))
return a
def toms_recursive_zerocopy_flatten(seq, a=None): #a=[] kept a
reference to a?
if a==None:
a = []
if hasattr(seq,"__iter__"):
for item in seq:
toms_recursive_zerocopy_flatten(item, a)
else:
a.append(seq)
return a
def toms_iterative_zerocopy_flatten(seq):
stack = [None]
cur = iter(seq)
a = []
while (cur != None):
try:
item = cur.next()
if hasattr(item,"__iter__"):
stack.append(cur)
cur = iter(item)
else:
a.append(item)
except StopIteration:
cur = stack.pop()
return a
def devans_smallest_recursive_flatten(seq):
if hasattr(seq,"__iter__"):
return sum([devans_smallest_recursive_flatten(item) for item in
seq], [])
else:
return [seq]
def rons_nonrecursive_inplace_flatten(seq):
i = 0
while i != len(seq):
if hasattr(seq[i],"__iter__"):
seq[i:(i + 1)] = seq[i] # setslice takes iterators!
else:
i = i + 1
return seq
def flatten_generator(item):
try:
iterable = iter(item)
except TypeError:
yield item # inner/final clause
else:
for elem in iterable:
# yield_return flatten(elem)
for x in flatten_generator(elem):
yield x

def stians_flatten_generator(seq):
return list(flatten_generator(seq))

# ------------------------------------------

flattens = [
georges_recursive_flatten,
rons_nonrecursive_flatten,
toms_recursive_zerocopy_flatten,
toms_iterative_zerocopy_flatten,
devans_smallest_recursive_flatten,
rons_nonrecursive_inplace_flatten,
stians_flatten_generator
]
import random
import time
random.seed(time.time())
def rand_depth_sequence(seq,depth):
n = len(seq)*depth
nn = 0
while nn<n:
try:
step = random.randint(1,3)
start = random.randint(0,(len(seq)-step))
end = random.randint(start,start+step)
seq[start:end]=[seq[start:end]]
nn += 1
except:
pass
return seq
#print sequence

size = 1000
original = range(size)
for depth in [0,25,50,100]:
sequence = rand_depth_sequence(original[:],depth)
print "\nSize:",size," Depth:",depth
for flatten in flattens:
s = sequence[:] # make new copy!
tm, result = timeit(flatten,s)
if result != original: # check for valid output!
print "Result Error from", flatten
print original
print result
print sequence
print s
break
f_name = flatten.func_name
print "%s: %s%s" % (f_name, ' '*(35-len(f_name)),tm)
# clear values for next test
del result
del s
# ----



Jul 21 '05 #147
Mike Meyer wrote:
Ron Adam <rr*@ronadam.com> writes:
So doing this would give an error for functions that require an argument.

def foo(x):
return x

a = None
b = foo(a) # error because a dissapears before foo gets it.

So how do I pass None to a function?


You wouldn't. What would a function do with it anyway? If you wanted
to pass a neutral value of some sort, then you'd just have to pick
something else and test for it. Maybe we could use Nil as an
alternative to None for that purpose?

6. x = foo() # Would give an error if foo returns None


Why? Shouldn't it delete x?


That was my first thought as well.

It would cause all sorts of problems. One way to avoid those is to
insist that the only way to assign (delete) a name to None is by
literally using "None" and only "None" on the right side of the = sign.

Any undefined name on the right side would give an error except for None
itself.
This might be an improvement over current behavior. Breaks a lot of
current code though.


I don't think so. I've programmed in langauges that gave undefined
variables a value rather than an exception. It almost inevitabley led
to hard-to-find bugs.


That is why the above should give an error I believe. ;)

FORTRAN used to give all variables a type, so that a typo in a
variable name could well lead to a valid expression. The technic for
disabling this was baroque ("IMPLICIT BOOLEAN*1 A-Z"), but so common
they invented a syntax for it in later versions of FORTRAN ("IMPLICIT
NONE").


It's been so long since I did anything if Fortran I've actual don't
recall any of it. :) '83-'84

I went from that to pascal, which I thought was a big improvement at the
time.

Cheers,
Ron

Jul 21 '05 #148
Ron Adam wrote:
Given the statement:

a = None

And the following are all true:

a == None
Okay.
(a) == (None)
Okay.
(a) == ()
Whoops! a (which is None) is equal to the empty tuple (which is not None)?
(None) == ()

Then this "conceptual" comparison should also be true:

if (None): == if ():
if (): == if:


I can't really see any coherent concept here.

Reinhold
Jul 21 '05 #149
Steven Bethard wrote:
If you're really afraid of two lines, write it as:

def r(): randint(1, 100)

This is definitely a bad case for an anonymous function because it's not
anonymous! You give it a name, r.


This is something I've never understood. Why is it bad
form to assign an "anonymous function" (an object) to a
name?

It isn't just that lambda _can_ create functions that
aren't bound to any name. That I get. But why is it
suppose to be wrong to bind such a function to a name?

Sure, if the lambda is so complicated that it becomes
unreadable, the usage case is wrong and a def should be
used instead. But I see nothing wrong with doing this:

func = lambda x: x**3 - 3*x**2

Why is it considered abuse of lambda to assign the
functions to a name? Is it an abuse of lambda to do this?

D = {"one": lambda noun: noun,
"two": lambda noun: noun + 's',
"many": lambda noun: 'lots of ' + noun + 's' }

assert D["two"]("python") == "pythons"
--
Steven.

Jul 21 '05 #150

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

Similar topics

226
by: Stephen C. Waterbury | last post by:
This seems like it ought to work, according to the description of reduce(), but it doesn't. Is this a bug, or am I missing something? Python 2.3.2 (#1, Oct 20 2003, 01:04:35) on linux2 Type...
4
by: Ben | last post by:
Hi all, I'm trying to figure out how how complex map, filter and reduce work based on the following piece of code from http://www-106.ibm.com/developerworks/linux/library/l-prog.html : ...
5
by: Logan | last post by:
I read in PEP 279 the following comment by GvR: "filter and map should die and be subsumed into list comprehensions, not grow more variants." Actually, I am using 'filter' and 'map' a lot in...
2
by: Thomas Philips | last post by:
To experiment with filtering, I define a function f(x,k) as follows >>> def f(x,k=2): return x%k==0 I can check that it works by typing >>> f(10,3) False Now, I try to filter a range using...
4
by: Charlie Taylor | last post by:
I find that I use lambda functions mainly for callbacks to things like integration or root finding routines as follows. flow = integrate(lambda x: 2.0*pi * d(x)* v(x) * sin(a(x)),xBeg, xEnd) ...
22
by: Cameron Laird | last post by:
QOTW: "... and to my utter surprise it worked." - Andrew Nagel on his move from wxPython to programming Tkinter in desperation "Python has more web application frameworks than keywords." - Skip...
9
by: lars_woetmann | last post by:
I have a list I filter using another list and I would like this to be as fast as possible right now I do like this: i tried using the method filter: filter(lambda x: x not in list2, list1)
10
by: charles.hebert | last post by:
Hi, Can anybody tell me how to to find the nearest value to zero in a list ? To do that, i'm using list comprenhension : Something simpler ?
7
by: cnb | last post by:
This must be because of implementation right? Shouldn't reduce be faster since it iterates once over the list? doesnt sum first construct the list then sum it? ----------------------- reduce...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...

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.