Formatting multiple lines in Python with method calls
Asked Answered
L

3

12

What's the accepted style in Python to format multiple lines of code that are method calls?

my_obj.call(x,y).multiple(*args).methods([1,2,3])

With implicit line breaks after brackets/parentheses it would look like this:

my_obj.call(
  x, y).multiple(
  *args).methods(
  [1,2,3])

Which is a bit ugly and doesn't really fit with typical Python style.

  1. Is it acceptable to format multiple method calls with the back slash \?

    my_obj.call(x, y) \
      .multiple(*args) \
      .methods([1,2,3])
    
  2. If it is acceptable, is it then also acceptable to use two spaces in the line after for the method call or should there be no indentation?

Leiker answered 4/6, 2018 at 9:38 Comment(1)
Just my opinion, but I think using backslashes is cleanest, and you should definitely indent the following lines, rather with more than two spaces (again, just my opinion, but I'd probably use two "block"-widths or align the .)Shelley
A
11

I will format it like this:

my_obj.call(
    x, y
).multiple(
    *args
).methods(
    [1, 2, 3]
)

Or use \:

my_obj.call(x, y) \
    .multiple(*args) \
    .methods([1, 2, 3])

The indention should be the same as block indention which is usually 4 spaces.

Altigraph answered 4/6, 2018 at 9:50 Comment(2)
Can you back this up with a reference, or reasons why this should be preferred? PEP8 seems only to be about long parameter lists, not about method chaining. Not saying that it's wrong, but it seems to be just an opinion...Shelley
Um... It is the default action in Pycharm. It isn't a rule, but as Pycharm is widely used, it is long-tested.Altigraph
C
8

An alternative to trailing \ is to use parenthesis:

(my_obj.call(x, y)
  .multiple(*args)
  .methods([1,2,3]))
Commissioner answered 6/6, 2018 at 19:41 Comment(1)
interesting solution!Leiker
P
0

The pep8 way would be

temp_obj = my_obj.call(x,y)
temp_obj = temp_obj.multiple(*args)
temp_obj.methods([1,2,3])

Or if the first line fits in one line i.e < 79 characters.

temp_obj = my_obj.call(x,y).multiple(*args)
temp_obj.methods([1,2,3])
Psi answered 15/6, 2018 at 11:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.