开发者

Why not python implicit line continuation on period?

Is there any reason Python does not allow implicit line continuations after (or before) periods? That is

data.where(lambda d: e.name开发者_Python百科 == 'Obama').
    count()


data.where(lambda d: e.name == 'Obama')
    .count()

Does this conflict with some feature of Python? With the rise of method chaining APIs this seems like a nice feature.


Both of those situations can lead to valid, complete constructs, so continuing on them would complicate the parser.

print 3.
  1415926

print 'Hello, world'
  .lower()


Python allow line continuations within parentheticals (), so you might try:

(data.where(lambda d: e.name == 'Obama').
    count())

I know that's not answering your question ("why?"), but maybe it's helpful.


Use a '\' at the end. (looks ugly though)

data.where(lambda d: e.name == 'Obama').\
    count()


Not sure about after periods, but in your example the newline before a period leads to the first line being a valid statement on its own. Then Python would have to look ahead to the second line to know whether the first line was a statement or not.

One of the goals when defining the language syntax was to be able to parse it without having ambiguities that require looking ahead like that.

It'd get annoying in the interactive interpreter if you had to press enter twice after every single line just so Python knew you'd finished your statement and weren't going to put a .foo() after it.


In the cases where a period could be leading in to a method call, it will always(?) be a syntax error for it to just occur at the end of a line by itself. So it would be unambiguous to read it as starting a continuation.

However, Python generally speaking doesn't continue a line just because there's an incomplete binary operator there. For instance, the following is not valid:

2 + 
    4

In the second example, the first line is valid by itself and it would be really inconsistent for Python to look for a following line "just in case" there is one.

I would just break after the opening paren of the method call.


{Because python uses line breaks to end statements, not depending on braces or semi-colins;}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜