[Python-bugs-list] [ python-Feature Requests-449187 ] if x in 1,2,3: should work
SourceForge.net
noreply@sourceforge.net
Mon, 12 May 2003 18:38:02 -0700
Feature Requests item #449187, was opened at 2001-08-08 12:07
Message generated for change (Comment added) made by tim_one
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=355470&aid=449187&group_id=5470
Category: Parser/Compiler
Group: None
Status: Open
Resolution: None
Priority: 5
Submitted By: Alex Martelli (aleax)
Assigned to: Nobody/Anonymous (nobody)
Summary: if x in 1,2,3: should work
Initial Comment:
There is normally some symmetry between 'for x in
whatever' and 'if x in whatever'. However, the
symmetry is broken (for syntax reasons I do not
understand) in one case, a tuple-without-parentheses:
for x in 1, 2, 3: pass
works fine, but
if x in 1, 2, 3: pass
gives a syntax error. Can the syntax error be
removed? I think it violates the principle of least
astonishment, as one would expect that either both
forms would work or neither would.
(I'd offer a patch, but I don't think I really
understand the way Python syntax is implemented in the
Python compiler...!-).
----------------------------------------------------------------------
>Comment By: Tim Peters (tim_one)
Date: 2003-05-12 21:38
Message:
Logged In: YES
user_id=31435
The fundamental problem is that, as an expression, "x in 1,
2, 3" doesn't group as an if-statement would need it to
group:
>>> y = 'a' in 'a', 'b', 'c'
>>> y
(True, 'b', 'c')
>>>
>>> for y in 'a' in 'a', 'b', 'c':
... print y
...
True
b
c
>>>
So if Python did allow a testlist as the 'if' expression, it
would be parsed as:
if ((x in 1), 2, 3):
which is a surprising way of raising TypeError. The parens
are really needed to get the 1, 2, 3 part parsed as a tuple.
----------------------------------------------------------------------
Comment By: Brett Cannon (bcannon)
Date: 2003-05-12 21:11
Message:
Logged In: YES
user_id=357491
I didn't know Python accepted that 'for' structure!?! I agree with Alex that
this should be changed at some point.
As for why this is, it appears that the offending grammar definitions are:
for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
testlist: test (',' test)* [',']
test: and_test ('or' and_test)* | lambdef
So it looks like the difference is 'for' uses testlist while 'if' uses just test.
Probably can just swap out testlist for test and get the result you want.
----------------------------------------------------------------------
You can respond by visiting:
https://sourceforge.net/tracker/?func=detail&atid=355470&aid=449187&group_id=5470