Black: If statements with parallel conditions should be kept parallel

Created on 11 Nov 2019  路  3Comments  路  Source: psf/black

Describe the style change A clear and concise description of how the style can be
improved.

If statements with multiple parallel conditions should be kept
parallel if they don't fit on one line. "Parallel conditions" are
conditions that only have a few characters that are different, as
bellow.

Examples in the current _Black_ style Think of some short code snippets that show
how the current _Black_ style is not great:

def on_segment(p_i, p_j, p_k):
    if min(p_i[0], p_j[0]) <= p_k[0] <= max(p_i[0], p_j[0]) and min(
        p_i[1], p_j[1]
    ) <= p_k[1] <= max(p_i[1], p_j[1]):
        return True
    else:
        return false

Desired style How do you think _Black_ should format the above snippets:

def on_segment(p_i, p_j, p_k):
    if (min(p_i[0], p_j[0]) <= p_k[0] <= max(p_i[0], p_j[0])
    and min(p_i[1], p_j[1]) <= p_k[1] <= max(p_i[1], p_j[1])
    ):
        return True
    else:
        return false

Additional context Add any other context about the problem here.

Please feel free to ask any clarifying questions, or critique the desired style above.

design

Most helpful comment

I don't necessarily agree with the desired style.

I think the following might be a bit better:

def on_segment(p_i, p_j, p_k):
    if (
      min(p_i[0], p_j[0]) <= p_k[0] <= max(p_i[0], p_j[0]) and 
      min(p_i[1], p_j[1]) <= p_k[1] <= max(p_i[1], p_j[1])
    ):
        return True
    else:
        return false

All 3 comments

I don't necessarily agree with the desired style.

I think the following might be a bit better:

def on_segment(p_i, p_j, p_k):
    if (
      min(p_i[0], p_j[0]) <= p_k[0] <= max(p_i[0], p_j[0]) and 
      min(p_i[1], p_j[1]) <= p_k[1] <= max(p_i[1], p_j[1])
    ):
        return True
    else:
        return false

@Jma353 I think that looks good too.

axes = [0, 1]
minimums = [min(end_point_1[axis], end_point_2[axis]) for axis in axes]
maximums = [max(end_point_1[axis], end_point_2[axis]) for axis in axes]
return all(minimums[axis] <= test_point[axis] <= maximums[axis] for axis in axes)

In general, Black helps find code that is not trivial to parametrize or extend (adding a third axis and excluding the segment endpoints should not be multi-line changes) or not trivial to debug (lack of intermediate variables to print).

Black cannot change readability (as in being "correct by design", pythonic, natural-language-looking), it decreases the eye movements needed to parse.

Was this page helpful?
0 / 5 - 0 ratings