yapf icon indicating copy to clipboard operation
yapf copied to clipboard

Add parentheisis and prefer splitting on long function chaining

Open hayd opened this issue 8 years ago • 4 comments

Often when chaining functions, e.g. long queries/maps/reduce, it's easy to get ugly code... see for example this SO question!

a.this_is_looooooooooooooooooooooooooong_identifier.something_even_looooooooooonger_potentially.and_a_final_pretty_looooong_one

I think the preferred formatting is to insert parenthesis:

(a.this_is_looooooooooooooooooooooooooong_identifier
  .something_even_looooooooooonger_potentially
  .and_a_final_pretty_looooong_one
)

Indeed, even if you have already inserted the paren as above yapf "fixes" to:

(a.this_is_looooooooooooooooooooooooooong_identifier.something_even_looooooooooonger_potentially.and_a_final_pretty_looooong_one)

*Note: I suspect this is pretty speculative :)

hayd avatar Dec 04 '15 02:12 hayd

Any updates on this? Sorry for bumping!

MrSaints avatar Sep 08 '17 10:09 MrSaints

Started using yapf a couple of weeks ago, loving it so far but I'd love it even more if there was a knob for that.

If there is demand and somebody could point me to the right direction, I can give it a try.

sawidis avatar Sep 12 '17 14:09 sawidis

a similar place that could use parens:

if some_var.check_thing() and some_long_boolean_var and another_long_boolean_var:
    pass

currently that formats to this oddity:

if some_var.check_thing(
) and some_long_boolean_var and another_long_boolean_var:
    pass

if the author adds the parens manually, it produces visually desirable code.

gpshead avatar Jul 09 '21 23:07 gpshead

You could always use "Black" (see https://github.com/google/yapf/issues/794) to make those changes and then running yapf to get the formatting in the style you want. ;)

Yapf has a policy of making only white-space changes to code and not inserting or deleting parentheses. In the README:

YAPF tries very hard to be fully PEP 8 compliant. However, it is paramount to not risk altering the semantics of your code. Thus, YAPF tries to be as safe as possible and does not change the token stream (e.g., by adding parentheses). All these cases however, can be easily fixed manually. For instance,

kamahen avatar Jul 09 '21 23:07 kamahen