2

What is the recommended standard indentation for the second line of a multiline Python code with parentheses/commas?

  1. No indentation:

    plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet',
    vmin=-100, vmax=0, origin='lowest', aspect='auto')
    
  2. 4 spaces indentation:

    plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet',
        vmin=-100, vmax=0, origin='lowest', aspect='auto')
    
  3. Identation up to the (:

    plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet',
               vmin=-100, vmax=0, origin='lowest', aspect='auto')
    
  4. Another solution?

This is linked: Proper indentation for Python multiline strings but here the question is specific to multiline with parentheses / commas, and not strings.

Basj
  • 41,386
  • 99
  • 383
  • 673

2 Answers2

3

If you follow PEP8, Indentation then I would go with option 3:

# Aligned with opening delimiter.
foo = long_function_name(var_one, var_two,
                         var_three, var_four)

I personally really like this option as it makes things clearer to read for myself and others. But if you are working at a company make sure to check with the company standards (each company might have their preference).

Basj
  • 41,386
  • 99
  • 383
  • 673
Ely Fialkoff
  • 642
  • 1
  • 5
  • 12
  • 1
    Go to the code layout part on this link: https://legacy.python.org/dev/peps/pep-0008/ and check `# Aligned with opening delimiter.` – Sheldore Aug 03 '18 at 15:50
  • @Bazingaa you're right! I included it in the answer for completeness. – Basj Aug 03 '18 at 18:07
3

I would never use options 1 or 2, they can be misleading. 3 is good if you have enough room.

There is one more option which can be used when option 3 leaves too little room or when splitting lines using a backslash (PyCharm defaults to this in the latter situation), two indentation levels (8 spaces):

plt.imshow(np.transpose(Z), extent=[0,4.2,0,48000], cmap='jet',
        vmin=-100, vmax=0, origin='lowest', aspect='auto')

def grouper_with_prev(iterable: _Iin[_T], n: int, include_first: bool = False) \
        -> _Iout[_t.Tuple[_T, ...]]:
    """
    Returns n size chuncks of iterable with the previous n-1 elements

    """
    ...

This doesn't have the confusion of options 1 and 2, making it obvious what you're doing.

FHTMitchell
  • 11,793
  • 2
  • 35
  • 47