[Tutor] Regex not working as desired

Steven D'Aprano steve at pearwood.info
Tue Mar 6 17:45:27 EST 2018


On Tue, Mar 06, 2018 at 10:17:20PM +0000, Albert-Jan Roskam wrote:

> > >>> all(c.isdigit() for c in '12c4')
> > False
> 
> I never understood why this is syntactically correct. It's like two parentheses are missing.
> 
> This I understand:
> all((c.isdigit() for c in '12c4'))
> Or this:
> all([c.isdigit() for c in '12c4'])
> Or this:
> all((True, False))
> 
> But the way you wrote it, the generator expression just "floats" in 
> between the parentheses that are part of the all() function. Is this 
> something special about all() and any()? 

No, it is something special about generator expressions. The syntax for 
them is theoretically:

    expression for x in iterable

but parentheses are required to make it unambiguous. If they are already 
inside parentheses, as in a function call:

   spam(expression for x in iterable)

the function call parens are sufficient to make it unambiguous and so 
there is no need to add an extra pair.

However, if you have two arguments, or some other compound expression, 
you need to use disambiguation parens:

    spam(999, (expression for x in iterable))


-- 
Steve


More information about the Tutor mailing list