Hi,

I write a lot of SQLAlchemy code that looks more or less like this:

rows = (
    dbsession.query(Table1)
    .join(
        Table2, Table2.y = Table1.y)
    .filter(Table1.x = xx)
    .all())

The expressions get very long and nearly always need to be spread to multiple lines. I've tried various styles and have chosen the style above as the most tasteful available.

Pros of the existing syntax:

- It's possible to indent clearly and consistently.
- Nested indentation works out OK.
- It's flexible; I can combine lines or separate them for emphasis.

Cons:

- Extra parentheses are required.
- The indentation is not enforced by the parser, so I have unnecessary freedom that could let various mistakes slip through. - The closing parenthesis has to move every time I append to or reorder the expression, leading to diff noise in version control. (Alternatively, I could put the closing parenthesis on its own line, but that consumes precious vertical reading space.)

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.

Feedback is welcome!

Shane
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to