Python style for `chained` function calls

Question:

More and more we use chained function calls:

value = get_row_data(original_parameters).refine_data(leval=3).transfer_to_style_c()

It can be long. To save long line in code, which is prefered?

value = get_row_data(
    original_parameters).refine_data(
    leval=3).transfer_to_style_c()

or:

value = get_row_data(original_parameters)
       .refine_data(leval=3)
       .transfer_to_style_c()

I feel it good to use backslash , and put .function to new line. This makes each function call has it own line, it’s easy to read. But this sounds not preferred by many. And when code makes subtle errors, when it’s hard to debug, I always start to worry it might be a space or something after the backslash ().

To quote from the Python style guide:

Long lines can be broken over multiple lines by wrapping expressions
in parentheses. These should be used in preference to using a
backslash for line continuation. Make sure to indent the continued
line appropriately. The preferred place to break around a binary
operator is after the operator, not before it.

Asked By: Andrew_1510

||

Answers:

What about this option:

value = get_row_data(original_parameters,
            ).refine_data(leval=3,
                ).transfer_to_style_c()

Note that commas are redundant if there are no other parameters but I keep them to maintain consistency.

Answered By: Mohammad Alhashash

I tend to prefer the following, which eschews the non-recommended at the end of a line, thanks to an opening parenthesis:

value = (get_row_data(original_parameters)
         .refine_data(level=3)
         .transfer_to_style_c())

One advantage of this syntax is that each method call is on its own line.

A similar kind of -less structure is also often useful with string literals, so that they don’t go beyond the recommended 79 character per line limit:

message = ("This is a very long"
           " one-line message put on many"
           " source lines.")

This is a single string literal, which is created efficiently by the Python interpreter (this is much better than summing strings, which creates multiple strings in memory and copies them multiple times until the final string is obtained).

Python’s code formatting is nice.

Answered By: Eric O Lebigot

The not quoting my own preference (although see comments on your question:)) or alternatives answer to this is:

Stick to the style guidelines on any project you have already – if not stated, then keep as consistent as you can with the rest of the code base in style.

Otherwise, pick a style you like and stick with that – and let others know somehow that’s how you’d appreciate chained function calls to be written if not reasonably readable on one-line (or however you wish to describe it).

Answered By: Jon Clements
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.