[Python-ideas] Extending expressions using ellipsis

Guido van Rossum guido at python.org
Wed Aug 31 21:25:28 EDT 2016


On Wed, Aug 31, 2016 at 2:46 PM, Shane Hathaway <shane at hathawaymix.org> wrote:
[...]
> I'd like to suggest a small change to the Python parser that would make long
> expressions read better:
>
> rows = dbsession.query(Table1) ...
>     .join(
>         Table2, Table2.y = Table1.y)
>     .filter(Table1.x = xx)
>     .all()
>
> The idea is to use an ellipsis at the end of a line to spread an expression
> over multiple indented lines, terminated by a return to an earlier
> indentation level.  You can still indent more deeply as needed, as shown
> above by the join() method call.
>
> This syntax has all the pros of the existing syntax and resolves all the
> cons:
>
> - No extra parentheses are required.
> - The indentation is enforced, so my mistakes are more likely to be caught
> early.
> - Without a closing parenthesis, there is no diff noise when I append to or
> reorder an expression.
>
> I've thought about using a colon instead of an ellipsis, but in Python, a
> colon starts a list of statements; that's not my goal. Instead, I'm looking
> for ways to use parser-enforced indentation to avoid mistakes and help my
> code read better without changing any semantics.

(And no, this isn't equivalent to using '\'.)

Would this be enforced in the grammar or by the lexer? Since you say
you expect the indentation to be enforced, that suggests it would be
done by the grammar, but then the question is how you would modify the
grammar? You could take the rule that says an expression can be
followed by ".NAME" and extended it to also allow "... INDENT xxxxx
DEDENT" where the xxxxx is whatever's allowed at ".NAME" (i.e. ".NAME"
followed by other tails like "(......)" or "[.......]".

But then you could only use this new idea for chaining method calls,
and not for spreading other large expressions across multiple lines.

-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-ideas mailing list