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 "import inspect, mymodule; print(inspect.getfile(mymodule))"
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.
Python does let you use a semicolon to denote the end of a statement if you are including more than one statement on a line. Save this answer. Show activity on this post. Multiple statements on one line may include semicolons as separators.
In computer programming, the semicolon is often used to separate multiple statements (for example, in Perl, Pascal, and SQL; see Pascal: Semicolons as statement separators). In other languages, semicolons are called terminators and are required after every statement (such as in PL/I, Java, and the C family).
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With