Indentation of closing parenthesis

2019-07-02 06:49发布

I believe the PEP8 style guide says that both

some_kind_of_list = [
    1, 2, 3,
    4, 5, 6
    ]

def function_that_takes_long_arguments(
    long_argument_1,
    long_argument_2
    ):
    return long_argument_1

and

some_kind_of_list = [
    1, 2, 3,
    4, 5, 6
]

def function_that_takes_long_arguments(
    long_argument_1,
    long_argument_2
):
    return long_argument_1

are acceptable, but does it make sense to use one or the other, e.g., if I move onto C++ later on in my life?

EDIT

Apologies, for a function, the PEP8 style guide actually says something like:

something = function_that_takes_long_arguments(
    long_argument_1,
    long_argument_2
)

3条回答
干净又极端
2楼-- · 2019-07-02 07:28

pep8 python style guide checker doesn't think both snippets are acceptable.

First option:

$ pep8 test_pep.py 
test_pep.py:10:5: E125 continuation line with same indent as next logical line

Second option (no warnings):

$ pep8 test_pep.py 
$

As you see, for the list it is okay to use both. But for the function, the second approach is preferred since in the first snippet the function body is indented as the previous line and it makes a negative impact on the readability.

查看更多
爷、活的狠高调
3楼-- · 2019-07-02 07:37

I don't particularly care for this style, and I just checked, it's not in PEP 8, and it may interfere with any given IDE's ability to collapse code blocks (it does with the one I use at work for Python):

def function_that_takes_long_arguments(
    long_argument_1,
    long_argument_2
):
    return long_argument_1

I'd rather you avoid it and do the following instead:

def function_that_takes_long_arguments(
  long_argument_1,
  long_argument_2):
    return long_argument_1

or

def function_that_takes_long_arguments(long_argument_1,
                                       long_argument_2):
    return long_argument_1

The list style is probably fine either way, though.

查看更多
Juvenile、少年°
4楼-- · 2019-07-02 07:53

I'd usually use

some_kind_of_list = [
    1, 2, 3,
    4, 5, 6,
]

def function_that_takes_long_arguments(
    long_argument_1,
    long_argument_2,
):
    return long_argument_1

This way indentation will be distinguishable. Also having a comma at the end of the last argument makes it possible to add new args later without changing other lines which is usually a good thing for git-blaming purposes and makes less clutter in diffs.

查看更多
登录 后发表回答