简体   繁体   中英

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?

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.

An alternative to trailing \\ is to use parenthesis:

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

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 ie < 79 characters.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM