SethMMorton SethMMorton - 12 days ago 7
Python Question

When is semicolon use in Python considered "good" or "acceptable"?

Python is a "whitespace delimited" language. However, the use of semicolons are allowed. For example, the following works but is frowned upon:

print("Hello!");
print("This is valid");


I've been using python for several years now, and the only time I have ever used semicolons is in generating one-time command-line scripts with python:

python -c "fmt = 'file{0}.txt'; for i in range(10): print(fmt.format(i))"


or adding code in comments on SO (i.e. "you should try
import os; print os.path.join(a,b)
")

I also noticed in this answer to a similar question that the semicolon can also be used to make one line
if
blocks, as in

if x < y < z: print(x); print(y); print(z)


which is convenient for the two usage examples I gave (command-line scripts and comments).




The above examples are for communicating code in paragraph form or making short snippets, but not something I would expect in a production codebase.

Here is my question: in python, is there ever a reason to use the semicolon in a production code? I imagine that they were added to the language solely for the reasons I have cited, but its always possible that Guido had a grander scheme in mind. No opinions please; I'm looking either for examples from existing code where the semicolon was useful, or some kind of statement from the python docs or from Guido about the use of the semicolon.

Answer

PEP 8 is the official style guide and says:

Compound statements (multiple statements on the same line) are generally discouraged.

(See also the examples just after this in the PEP.)

While I don't agree with everything PEP 8 says, if you're looking for an authoritative source, that's it. You should use multi-statement lines only as a last resort. (python -c is a good example of such a last resort, because you have no way to use actual linebreaks in that case.)