Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this a syntax error in python?

Noticed a line in our codebase today which I thought surely would have failed the build with syntax error, but tests were passing so apparently it was actually valid python (in both 2.x and 3).

Whitespace is sometimes not required in the conditional expression:

>>> 1if True else 0 1 

It doesn't work if the LHS is a variable:

>>> x = 1 >>> xif True else 0   File "<stdin>", line 1     xif True else 0            ^ SyntaxError: invalid syntax 

But it does seem to still work with other types of literals:

>>> {'hello'}if False else 'potato' 'potato' 

What's going on here, is it intentionally part of the grammar for some reason? Is this odd quirk a known/documented behaviour?

like image 498
wim Avatar asked Jun 02 '14 15:06

wim


People also ask

How do I fix invalid syntax error in Python?

You can clear up this invalid syntax in Python by switching out the semicolon for a colon. Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.

How do you find the syntax error in Python?

Python error checker tool allows to find syntax errors (lint). You can test your Python code online directly in your browser. If a syntax error is detected, then the line in error is highlighted, and it jumps to it to save time (no need to search the line).


1 Answers

Whitespace between tokens

Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is needed between two tokens only if their concatenation could otherwise be interpreted as a different token (e.g., ab is one token, but a b is two tokens).

So in this case, 1if is not a valid token, so the whitespace is optional. The 1 is interpreted as an integer literal of which the if is not a part. So if is interpreted separately and recognized as a keyword.

In xif however, an identifier is recognized, so Python is not able to see that you wanted to do x if there.

like image 182
poke Avatar answered Sep 19 '22 17:09

poke