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

Question:

Python is a "whitespace delimited" language. However, the use of semicolons are allowed. For example, the following works, but it 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 "import inspect, mymodule; print(inspect.getfile(mymodule))"

Or adding code in comments on Stack Overflow (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 it’s 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.

Asked By: SethMMorton

||

Answers:

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.)

Answered By: BrenBarn

I use semicolons in code all of the time. Our code folds across lines quite frequently, and a semicolon is a definitive assertion that a statement is ending.

output, errors, status = generate_output_with_errors_and_status(
    first_monstrous_functional_argument(argument_one_to_argument
        , argument_two_to_argument)
    , second_argument);

See? They’re quite helpful to readability.

Answered By: Ion Freeman
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.