Formatting Multiple Lines in Python with Method Calls

Formatting Multiple Lines in Python with Method Calls

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?

1

3 Answers

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.

2

An alternative to trailing \ is to use parenthesis:

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

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])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.