Search code examples
pythonstyles

Python style for `chained` function calls


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.


Solution

  • 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.