How can I do a line break (line continuation) in Python?

后端 未结 11 1520
囚心锁ツ
囚心锁ツ 2020-11-21 22:56

I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?

For example, adding a bunch of strings,



        
11条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 23:51

    Taken from The Hitchhiker's Guide to Python (Line Continuation):

    When a logical line of code is longer than the accepted limit, you need to split it over multiple physical lines. The Python interpreter will join consecutive lines if the last character of the line is a backslash. This is helpful in some cases, but should usually be avoided because of its fragility: a white space added to the end of the line, after the backslash, will break the code and may have unexpected results.

    A better solution is to use parentheses around your elements. Left with an unclosed parenthesis on an end-of-line the Python interpreter will join the next line until the parentheses are closed. The same behaviour holds for curly and square braces.

    However, more often than not, having to split a long logical line is a sign that you are trying to do too many things at the same time, which may hinder readability.

    Having that said, here's an example considering multiple imports (when exceeding line limits, defined on PEP-8), also applied to strings in general:

    from app import (
        app, abort, make_response, redirect, render_template, request, session
    )
    

提交回复
热议问题