Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to understand Python generator object

In the following:

name = 'TODD'
chars = set('AEIOU')
for ii in range(-1, int(math.copysign(len(name) + 1, -1)), -1):
    if any((cc in chars) for cc in name[ii]):
        print 'Found'
    else:
        print 'Not Found'

I understand that what's inside any(...) is a generator object. What I don't understand is the lack of parentheses - if the parentheses belong to the any() function, shouldn't there be another set of parentheses around the generator expression?

Thanks.

like image 252
Sabuncu Avatar asked Jul 26 '12 15:07

Sabuncu


4 Answers

The parenthesis can be omitted when used in function calls with only one argument, the generator expression syntax specifically allows for it.

The parentheses can be omitted on calls with only one argument. See section Calls for the detail.

like image 177
Martijn Pieters Avatar answered Oct 31 '22 16:10

Martijn Pieters


You can leave out the parentheses of a generator expression if the expression is the only thing in parentheses already.

From the documentation:

The parentheses can be omitted on calls with only one argument.

like image 29
phihag Avatar answered Oct 31 '22 16:10

phihag


No, the extra parens are not needed, nor in fact are parens always necessary for the "Boolean expression" you are testing, see these two simple examples:

In [37]: any(i > 10 for i in range(19))
Out[37]: True

In [38]: all(i > 10 for i in range(19))
Out[38]: False

What you have is a function call with a single argument (your generator expression) so no parens are required. See the generator expressions docs for more information.

like image 2
Levon Avatar answered Oct 31 '22 17:10

Levon


For function calls with just one argument (that generator expression), they aren't required per the docs

The parentheses can be omitted on calls with only one argument. See section Calls for the detail.

like image 1
Daniel DiPaolo Avatar answered Oct 31 '22 15:10

Daniel DiPaolo