<p>I came across <a href="https://stackoverflow.com/questions/77746742/what-is-the-term-for-a-colon-before-a-suite-in-python-syntax">this question on Stack Overflow</a> and it got me wondering... why did Python choose to allow single line compound statements? Python has significant whitespace, and it seems like the parser could easily differentiate structure based on newlines and indentation levels.</p>
<p>Looking at the <a href="https://docs.python.org/3/reference/grammar.html" rel="nofollow noreferrer">Python grammar</a> it appears that anything that has the structure <code>KEYWORD named_expression ':' block</code> uses the colon to delineate the end of the expression and the start of the following block, presumably so that parser can tell which is which when the statement is crammed on to one line but that has been considered &quot;bad style&quot; and all but unused since before I started programming well over a decade ago. Is this just a vestigial remnant of the early days? If so why wasn't it dropped in the 2/3 rewrite? Is there some benefit or grammatical complication that I'm missing here that makes this necessary?</p>
<p>For example:</p>
<pre class="lang-python prettyprint-override"><code># current Python syntactic options
if True: print('hello world')
if True:
    print('hello world')

# vs a hypothetical Python that disallows the first form above
# and instead uses NEWLINE/INDENT to delimit the expression vs 
# the following block:
if True
    print('hello world')
<span class="math-container">```</span>
</code></pre>

<syntax><python>
Why does python allow single-line compound statements?
CC BY-SA 4.0
2024-01-02T15:09:04.387Z
To be clear, by "single-line compound statements" you mean like `if x: f()` without a newline, not like `f(); g()` with a semicolon?
kaya3
CC BY-SA 4.0
2024-01-02T15:09:39.940Z
@kaya3 correct, I'll edit the question with an example
Jared Smith
CC BY-SA 4.0
2024-01-02T17:11:52.163Z
Not necessarily the motivation for the language itself, but single-line programs are very handy when using Python in place of awk and friends in the shell.
MisterMiyagi
CC BY-SA 4.0
2024-01-02T17:14:15.740Z
Note: the colon has been motivated in an old blog post by GvR as punctuation aimed at humans, not the parser. It exists to visually denote that the following belongs to the preceding statement, just like a colon in prose would indicate a list of examples belongs to its preceding sentence naming the category. Since Python generally has no `a b` expression syntax, there is little or even no ambiguity in omitting the colon.
MisterMiyagi
CC BY-SA 4.0
2024-01-02T17:19:35.567Z
In fact the colon is motivated as such in [the Python FAQ](https://docs.python.org/3/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements). The FAQ notes this simplifies parsing but implies it is not necessary.
MisterMiyagi
CC BY-SA 4.0
2024-01-02T17:52:42.137Z
Once they decided to require `:` at the end of the statement that starts a block, it was probably an easy addition to allow a single-line body on the same line. This allows for simple `if condition: break/return` statements.
Barmar
CC BY-SA 4.0
2024-01-02T18:09:05.033Z
Previously asked on SO: https://stackoverflow.com/questions/61186871/what-is-the-purpose-of-single-line-statements-in-python
dan04
CC BY-SA 4.0
2024-01-02T18:09:55.500Z
Also: https://softwareengineering.stackexchange.com/questions/104066/single-line-statements-good-practices
dan04
CC BY-SA 4.0
2024-01-02T18:11:49.780Z
@MisterMiyagi I don't think the FAQ implies the colon is not necessary, but rather that its necessity isn't the main reason for including it (as opposed to designing the syntax to make it not necessary). Consider examples like `if something: (foo if bar else baz).qux()`, which would have a different meaning without the colon and couldn't be disambiguated without changing its meaning.
kaya3
CC BY-SA 4.0
2024-01-02T19:43:52.773Z
@kaya3 The colon is not necessary because committing it or including it is always forced, using the wrong one is never ambiguous but always an error. (At least assuming a line break and indent afterwards)
mousetail 'he-him'
CC BY-SA 4.0
2024-01-02T19:49:37.900Z
Also ["Does Python's semicolon statement ending feature have any unique use?"](https://langdev.stackexchange.com/questions/3030/does-pythons-semicolon-statement-ending-feature-have-any-unique-use). Most (but not all) answers are the same here (convenience in some cases, like executing from `bash`).
tarzh
CC BY-SA 4.0
2024-01-02T20:55:08.483Z
@mousetail I can make no sense of your comment; what does it mean to commit a colon, or to use the wrong colon? Anyway, I gave an example which shows why the colon is necessary ─ and your assumption of a line break and an indent is not valid, since that isn't required in my example.
kaya3
CC BY-SA 4.0
2024-01-02T22:51:52.793Z
AFAICT, the reason is just "brevity", but I haven't been able to find any "official" comment from GvR or other Python developers.
dan04
CC BY-SA 4.0
2024-01-03T09:08:01.593Z
Anyways, unless you actually care about the colon instead of or in addition to the single-line capabilities, I recommend to [edit] the question to remove this ambiguity. Simply having the colon in all examples should be sufficient.
MisterMiyagi
CC BY-SA 4.0
2024-01-04T18:35:20.083Z
@kaya3 I don't understand your example. Are you trying to say that it would be interpreted as a conditional expression without the colon? But `if` can't be at the beginning of a conditional expression, it has to be `<expr1> if <expr2> else <expr3>`. So the two cases can be distinguished by whether `if` is at the beginning of the statement, the colon is not necessary.
Barmar
CC BY-SA 4.0
2024-01-04T19:48:27.287Z
@Barmar The problem is that both the single expression `a(…)` and the two expressions `a` and `(…)` are valid Python. So dropping the colon makes `if a:(…)` is ambiguous. The ternary is just some expression that could take the place of `…` and still be sensible in both cases (as opposed to something like a tuple display, which isn’t helpful on its own and could thus just be forbidden in isolation).
MisterMiyagi
CC BY-SA 4.0
2024-01-04T22:38:11.773Z
@Barmar Without the colon, it would be parsed as a function call.
kaya3
CC BY-SA 4.0
2024-01-04T22:46:11.643Z
@kaya3 Yes, I got that from MisterMiyagi's comment. It would be nice if you'd said that originally, and didn't include the irrelevant conditional expression. It seems like you deliberately made it a challenge to get your point.
Barmar
CC BY-SA 4.0
2024-01-04T22:54:39.120Z
@Barmar I would hope that everyone on this site recognises that it would be parsed as a function call otherwise. The conditional expression as the subject of a method call is not irrelevant, since it is one of the few cases where an expression-statement might reasonably begin with an open-parenthesis.
kaya3
<p><a href="https://docs.python.org/3/reference/compound_stmts.html" rel="nofollow noreferrer">Compound statements</a> are produced by the parser as part of the &quot;suite&quot; production, which groups up nested scopes into a syntax tree. One-line compound statements are allowed by not requiring an &quot;INDENT&quot; token. The linked documentation states that one-line compound statements are as legal as multi-line compound statements.</p>
<p>The only recommendation against one-line compound statements is in <a href="https://peps.python.org/pep-0008/" rel="nofollow noreferrer">PEP 8</a>, which is an optional guide that does not apply to all codebases. One-line compound statements save vertical space and overall whitespace, and this is the main attraction towards including them as a feature in non-Python grammars.</p>

CC BY-SA 4.0
2024-01-03T17:00:08.033Z
2024-01-04T20:18:22.370Z
2024-01-04T20:18:22.370Z
Corbin
CC BY-SA 4.0
2024-01-03T17:01:26.833Z
Let me know if you want more words. I think that the points about style are important to the history of Python and the Python ecosystem, but almost totally irrelevant to PLT/PLDI; if you want your grammar to accommodate one-liners, then something like this is worth considering.
Corbin
CC BY-SA 4.0
2024-01-04T09:44:10.497Z
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/1545)
чистов_n
CC BY-SA 4.0
2024-01-04T20:19:34.680Z
@nchistov: How about now? Note that the original question is three questions, with the latter two begging the first. It happens to be the case that the first question's answer is a resounding "no, one-liners are completely allowed in Python, and only style guides say otherwise."
Corbin
CC BY-SA 4.0
2024-01-05T11:04:25.727Z
Now I think is ok.
чистов_n
<p>Mostly to make it easy to write one-liners like <code>python -c &quot;for i in range(0,10): print(i)&quot;</code></p>

CC BY-SA 4.0
2024-01-03T04:19:43.477Z
2024-01-03T04:19:43.477Z
Chris Dodd
CC BY-SA 4.0
2024-01-04T10:49:25.043Z
Do you have any citations that support this as the main motivation?
Toby Speight
# Why does python allow single-line compound statements?
Posted by: username_0 on 2024-01-02
I came across this question on Stack Overflow and it got me wondering... why did Python choose to allow single line compound statements? Python has significant whitespace, and it seems like the parser could easily differentiate structure based on newlines and indentation levels.
Looking at the Python grammar it appears that anything that has the structure KEYWORD named_expression ':' block uses the colon to delineate the end of the expression and the start of the following block, presumably so that parser can tell which is which when the statement is crammed on to one line but that has been considered "bad style" and all but unused since before I started programming well over a decade ago. Is this just a vestigial remnant of the early days? If so why wasn't it dropped in the 2/3 rewrite? Is there some benefit or grammatical complication that I'm missing here that makes this necessary?
For example:
# current Python syntactic options
if True: print('hello world')
if True:
    print('hello world')

# vs a hypothetical Python that disallows the first form above
# and instead uses NEWLINE/INDENT to delimit the expression vs 
# the following block:
if True
    print('hello world')
```
**Tags:** syntax python
> **Comments:**
> **username_1**: To be clear, by "single-line compound statements" you mean like `if x: f()` without a newline, not like `f(); g()` with a semicolon?  
> **username_0**: @kaya3 correct, I'll edit the question with an example  
> **username_2**: Not necessarily the motivation for the language itself, but single-line programs are very handy when using Python in place of awk and friends in the shell.  
> **username_2**: Note: the colon has been motivated in an old blog post by GvR as punctuation aimed at humans, not the parser. It exists to visually denote that the following belongs to the preceding statement, just like a colon in prose would indicate a list of examples belongs to its preceding sentence naming the category. Since Python generally has no `a b` expression syntax, there is little or even no ambiguity in omitting the colon.  
> **username_2**: In fact the colon is motivated as such in [the Python FAQ](https://docs.python.org/3/faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements). The FAQ notes this simplifies parsing but implies it is not necessary.  
> **username_3**: Once they decided to require `:` at the end of the statement that starts a block, it was probably an easy addition to allow a single-line body on the same line. This allows for simple `if condition: break/return` statements.  
> **username_4**: Previously asked on SO: https://stackoverflow.com/questions/61186871/what-is-the-purpose-of-single-line-statements-in-python  
> **username_4**: Also: https://softwareengineering.stackexchange.com/questions/104066/single-line-statements-good-practices  
> **username_1**: @MisterMiyagi I don't think the FAQ implies the colon is not necessary, but rather that its necessity isn't the main reason for including it (as opposed to designing the syntax to make it not necessary). Consider examples like `if something: (foo if bar else baz).qux()`, which would have a different meaning without the colon and couldn't be disambiguated without changing its meaning.  
> **username_5**: @kaya3 The colon is not necessary because committing it or including it is always forced, using the wrong one is never ambiguous but always an error. (At least assuming a line break and indent afterwards)  
> **username_6**: Also ["Does Python's semicolon statement ending feature have any unique use?"](https://langdev.stackexchange.com/questions/3030/does-pythons-semicolon-statement-ending-feature-have-any-unique-use). Most (but not all) answers are the same here (convenience in some cases, like executing from `bash`).  
> **username_1**: @mousetail I can make no sense of your comment; what does it mean to commit a colon, or to use the wrong colon? Anyway, I gave an example which shows why the colon is necessary ─ and your assumption of a line break and an indent is not valid, since that isn't required in my example.  
> **username_4**: AFAICT, the reason is just "brevity", but I haven't been able to find any "official" comment from GvR or other Python developers.  
> **username_2**: Anyways, unless you actually care about the colon instead of or in addition to the single-line capabilities, I recommend to [edit] the question to remove this ambiguity. Simply having the colon in all examples should be sufficient.  
> **username_3**: @kaya3 I don't understand your example. Are you trying to say that it would be interpreted as a conditional expression without the colon? But `if` can't be at the beginning of a conditional expression, it has to be `<expr1> if <expr2> else <expr3>`. So the two cases can be distinguished by whether `if` is at the beginning of the statement, the colon is not necessary.  
> **username_2**: @Barmar The problem is that both the single expression `a(…)` and the two expressions `a` and `(…)` are valid Python. So dropping the colon makes `if a:(…)` is ambiguous. The ternary is just some expression that could take the place of `…` and still be sensible in both cases (as opposed to something like a tuple display, which isn’t helpful on its own and could thus just be forbidden in isolation).  
> **username_1**: @Barmar Without the colon, it would be parsed as a function call.  
> **username_3**: @kaya3 Yes, I got that from MisterMiyagi's comment. It would be nice if you'd said that originally, and didn't include the irrelevant conditional expression. It seems like you deliberately made it a challenge to get your point.  
> **username_1**: @Barmar I would hope that everyone on this site recognises that it would be parsed as a function call otherwise. The conditional expression as the subject of a method call is not irrelevant, since it is one of the few cases where an expression-statement might reasonably begin with an open-parenthesis.  
---
## 2 answers
### Answer by username_7 on 2024-01-03. Score: 1 | Accepted answer
[Compound statements](https://docs.python.org/3/reference/compound_stmts.html) are produced by the parser as part of the "suite" production, which groups up nested scopes into a syntax tree. One-line compound statements are allowed by not requiring an "INDENT" token. The linked documentation states that one-line compound statements are as legal as multi-line compound statements.

The only recommendation against one-line compound statements is in [PEP 8](https://peps.python.org/pep-0008/), which is an optional guide that does not apply to all codebases. One-line compound statements save vertical space and overall whitespace, and this is the main attraction towards including them as a feature in non-Python grammars.
> **Comments:**
> **username_7** (2024-01-03): Let me know if you want more words. I think that the points about style are important to the history of Python and the Python ecosystem, but almost totally irrelevant to PLT/PLDI; if you want your grammar to accommodate one-liners, then something like this is worth considering.  
> **username_8** (2024-01-04): This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/1545)  
> **username_7** (2024-01-04): @nchistov: How about now? Note that the original question is three questions, with the latter two begging the first. It happens to be the case that the first question's answer is a resounding "no, one-liners are completely allowed in Python, and only style guides say otherwise."  
> **username_8** (2024-01-05): Now I think is ok.  
---
### Answer by username_9 on 2024-01-03. Score: 1
Mostly to make it easy to write one-liners like `python -c "for i in range(0,10): print(i)"`
> **Comments:**
> **username_10** (2024-01-04): Do you have any citations that support this as the main motivation?  
---
