39

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SethMMorton
  • 45,752
  • 12
  • 65
  • 86
  • 15
    I'd say you pretty much answered the question. – user4815162342 Oct 14 '13 at 17:29
  • 1
    The one liner example throws `SyntaxError`. `;` can only be used to separate simple statements like `x=1;y=2`. Trying to separate a simple statement and compound statement like `x=1; for i in range(1): print(1)` will fail. – bain Nov 26 '16 at 12:20
  • @bain It does not give a `SyntaxError`, unless you are on Python3 and forgot to add the parenthesis on the `print` functions. I updated syntax in the question to Python3 to avoid confusions like this down the road. – SethMMorton Nov 26 '16 at 17:35
  • @SethMMorton [repl.it demo - python2](https://repl.it/E8hB/0), [repl.it demo - python3](https://repl.it/E8hD/0). Click run, both will raise SyntaxError. – bain Nov 27 '16 at 16:36
  • @bain The statement "The one liner example throws `SyntaxError`" implies that either the example I posted gives a `SyntaxError`, or all one-liners give a `SyntaxError`; neither are true. If you try the form I posted it works. Perhaps a better way to phrase your observation is "it appears there are cases where Python does not let you use a for loop with `;`, here is an example I found." – SethMMorton Nov 27 '16 at 17:46
  • @bain Check out https://docs.python.org/3/reference/compound_stmts.html: "Also note that the semicolon binds tighter than the colon in this context..." It is possible that because you have placed the `;` before the `:` in the statements you linked, Python is getting confused because of operator precedence. – SethMMorton Nov 27 '16 at 18:00
  • @SethMMorton I did use the example you posted for the first link, and used syntactically identical code for the second - [this](https://repl.it/E8hB/0) is an exact copy of your code `fmt = 'file{0}.txt'; for i in range(10): print(fmt.format(i))`. It throws a SyntaxError if you click Run. Same on Python 3 - [Screenshot](http://i.imgur.com/XdlkbBb.png]) – bain Nov 27 '16 at 22:21
  • @bain Well paint my face embarrassed! Of course you are right... I was looking at a different example in my post. Let me change the command-line one-liner to something that works. Sorry for disagreeing when you were clearly correct! – SethMMorton Nov 28 '16 at 03:52
  • I have asked a [new question](http://stackoverflow.com/questions/40837043/why-does-x-5-for-i-in-rangex-printi-result-in-a-syntaxerror) based on the fact that this raises a `SyntaxError`. – SethMMorton Nov 28 '16 at 04:09
  • 1
    [https://towardsdatascience.com/stop-using-semicolons-in-python-fd3ce4ff1086](https://towardsdatascience.com/stop-using-semicolons-in-python-fd3ce4ff1086) – Henke Oct 01 '20 at 06:50

2 Answers2

26

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

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • 7
    While you indeed have a way to actually use linebreaks with `python -c $'print 6\nprint 7'`, that holds only for UNIX-like OSes, and is not very neat as well. So using `;`s is better in this case. – glglgl Oct 16 '13 at 15:56
  • 3
    @glglgl That's actually a shell feature, `$'...'`. For example Bash supports it, Dash doesn't. – wjandrea Mar 07 '19 at 01:26
  • 1
    @wjandrea That's right, I should have mentionned that. Another reason to avoid it. – glglgl Mar 07 '19 at 06:53
1

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.

Ion Freeman
  • 512
  • 4
  • 19
  • 12
    Sorry I would have to disagree. The way you use semicolon is merely your personal preference. In fact, the next line following your code would have no indentation, which serves better (and more pythonic) as an assertion that "the previous line ends; a new line begins". Besides, your using leading comma is also very interesting. Read PEP8 and you will surely find some (more popular) styles for that. – RayLuo Sep 30 '16 at 21:19
  • 1
    @RayLuo I'm glad you find the comma-first syntax interesting! It'll change your life. [Here's some guy on GitHub promoting it](https://gist.github.com/357981). As some other guy in the comments section of that gist says, the [Haskell style guide uses it](https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md). And who's going to fault the Haskell style guide? – Ion Freeman Nov 04 '16 at 17:14
  • 3
    (1) I have to admit that the "interesting" in my first comment actually meaned "I never saw leading-comma in Python; I don't get it". Sorry I should have been more specific. (2) And then you shared that [promoting the leading-comma post](https://gist.github.com/isaacs/357981), which is really eye-opening, and reasonable - when using Javascript. (3) But I still think all those reasons do not apply to Python: Missing one trailing comma will give you a noisy syntax error (which is good) rather than a sneaky leaking global variable; and Python allows extra comma at last item already. – RayLuo Nov 13 '16 at 03:17
  • 11
    Keep in mind that Haskell is Haskell, JavaScript is JavaScript, and neither are Python. What may be a good style for one language may not be good for another. For example, Perl style emphasizes terse style and multiple commands on a line, much of which is literally not possible with Python because of the syntax limitations. – SethMMorton Nov 30 '16 at 00:21
  • 4
    A better trick to to add readability when a function splits over multiple lines is to move the close bracket to its own final line, un-indented to match the original function. If you do this here to both functions, move `argument_one_to_argument` to its own line (to match the other argument) and fix the commas (including adding trailing commas) you end up with significantly more readable code than this. https://pastebin.com/XSS93LpT – Arthur Tacca Nov 21 '17 at 10:31
  • 1
    The comma-first syntax is primarily intended for circumstances where a trailing comma is not permitted (so that arguments can be added or removed without treating the last one as a special case). However, Python allows a trailing comma for function calls (although it's ugly), so that's not applicable. – Karl Knechtel Feb 27 '23 at 06:01
  • 1
    @ArthurTacca that's exactly how I do it. – Karl Knechtel Feb 27 '23 at 06:02