'for every' and 'for any'
Oren Tirosh
oren-py-l at hishome.net
Tue May 28 02:33:11 EDT 2002
On Sun, May 26, 2002 at 09:17:47AM -0500, jepler at unpythonic.net wrote:
> On Sun, May 26, 2002 at 01:59:44PM +0300, Oren Tirosh wrote:
> > Here's an idea for a possible language enhancement. I'd like to hear your
> > comments about it. It's inspired by list comprehensions and I think the
> > examples are pretty self-explanatory:
> >
> > if not isinstance(x, str) for any x in args:
> > raise TypeError, "arguments must be of type str"
>
> this is equivalent to
> bool([None for x in args if not isinstance(x, str)])
Sure, and the list comprehension
[None for x in args if not isinstance(x, str)]
Is equivalent to
map(lambda x: None, filter(lambda x: isinstance(x, str), args))
But which one is more readable?
List comprehensions were introduced into the language because they make
the code much more readable and English-like. I consider this an important
feature of the language.
I often use Python to write specifications. Python is great for this task
because it can be written in a way that is very compact and very readable
even for someone who has never seen Python source before. Python list
comprehensions are one of the things that make this possible. I use Python
as a language for writing specifications that also happen to be an executable
reference implementation. The poor souls that later have to implement the
specification in C++ often write write 10-20 times as much code as the
Python implementation and have a much harder harder time debugging it :-)
Anyway, the common task of checking if all or any of the items of a list
match a certain predicate is implemented in a large variety of ways. Just
in the replies to my message I got implementations that use break
statements, exceptions to break of of the loop, flags, checking for empty
lists, comparing list length to the original list and reduce with lambdas.
I've also seen a lot of code that uses the return statement as a kind of
break to achieve this effect.
The fact that there is no simple, common idiom to express this operation
seems to suggest that this part of the language is not as natural as it
could be. Most common ways to express this operation make use control flow
statements rather than expressions which makes them more awkward to use.
An expression is easy to use in an if statement where you get an else
clause. Using combinations of break makes it harder to use both the positive
and negative case. I often find myself rearranging my code and sometimes
inverting tests just to get what I want. That's not what programming is all
about. I'd rather concentrate on the task at hand than on how to express it.
Oren
More information about the Python-list
mailing list