'for every' and 'for any'

jepler at unpythonic.net jepler at unpythonic.net
Sun May 26 10:17:47 EDT 2002


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)])
> 
> valid = i>0 for every i in vector

This is equivalent to
    not [None for i in vector if not i > 0]
(i>0 for every i in vector <==> not (not i > 0 for any i in vector))
.. a little more cumbersome.  You could also write
    [i for i in vector if i > 0] == vector
or
    len([i for i in vector if i > 0]) == len(vector)
depending how much like a sequence (i.e., not an iterator) vector is.

> if dict2.has_key(k) for any k in dict1:
>   ...
    bool([None for k in dict1 if k in dict2])

> The words 'any' and 'every' can be non-reserved keywords (like the word 'as' 
> in "import foo as bar").  They are valid only after the keyword 'for' when 
> it's used in a non-statement context. 

The other issues to work out would include the precedence of operators.  Is
it
    not (isinstance(x,str) for any x in args)
or
    (not isinstance(x,str)) for any x in args
?

I'm not 100% sure that you can even implement this in the Python parser.
After all, if just having 'for..in' later on in the expression could give
you a generator, then we wouldn't need the silly brackets ..
    l = x for x in range(1000) if isprime(x)

Jeff





More information about the Python-list mailing list