milancurcic milancurcic - 2 months ago 15
Python Question

Blank line rule at interactive prompt

I was wondering why is there a different rule for blank lines in Python between interactive prompt and when the program is run from shell as an executable.

Since blank lines are ignored, I enjoy using them abundantly. However, in the interactive prompt, a blank line is used to terminate a loop. Thus, I keep running into indentation errors when I paste a chunk of code into the interactive prompt as I would have blank lines throughout my loops. Consequently, this makes the interactive debugging/development process somewhat tedious. Putting a # instead of blank line helps, but I like my blank lines.

Even more annoying is different behavior between prompts (e.g. python and ipython). Where python interactive prompt would give me an error where I expect it, ipython would keep executing the indented code as if it was not part of loop without complaining.

I feel there is an easy solution out there, but I'm not aware of it. I am using vi for editting and python/ipython prompts. Thanks.

mac mac
Answer

PEP8 defines how blank lines should be used:

Blank Lines

Separate top-level function and class definitions with two blank lines. Method definitions inside a class are separated by a single blank line.

Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).

Use blank lines in functions, sparingly, to indicate logical sections.

Python accepts the control-L (i.e. ^L) form feed character as whitespace; Many tools treat these characters as page separators, so you may use them to separate pages of related sections of your file. Note, some editors and web-based code viewers may not recognize control-L as a form feed and will show another glyph in its place.

If you stick to the PEP, the only instance in which blank lines might generate problems in the interactive console are "blank lines in functions to indicate logical sections", I believe.

You can circumvent the problem like this though:

>>> def a():
...     print 'foo'\
... 
...     print 'bar'
... 
>>> a()
foo
bar

Edit: Note that using \ instead of # as you suggest in your question leaves the blank line... blank (as the \ goes on the previous line).

HTH!

Comments