prettier / plugin-python

Prettier Python Plugin
MIT License
517 stars 41 forks source link

Multi-variable assignment is split over multiple lines #75

Open jleclanche opened 6 years ago

jleclanche commented 6 years ago

Found this issue in my codebase.

Input:

deck, created = Deck.objects.get_or_create_from_id_list(
    decklist,
    hero_id=player._hero.card_id,
    game_type=game_type,
    classify_archetype=True
)

Output:

(
    deck,
    created,
) = Deck.objects.get_or_create_from_id_list(decklist, hero_id=player._hero.card_id, game_type=game_type, classify_archetype=True)

This is wrong on two accounts: The multi-assignment should never be assigned to a tuple like that (even though it's syntactically correct, nobody does that). And the arguments to the method called on top of that shouldn't be rewrapped into a single line as that line ends up being too long. (Default params except tab, so 80 line length)

jleclanche commented 6 years ago

Looking at some other issues in my code it looks like prettier-python doesn't know how to intuitively split lines. For example:

influx_metric(
    "deck_prediction",
    fields,
    missing_cards=30 - deck_size,
    player_class=CardClass(int(player_class)).name,
    format=FormatType(int(global_game.format)).name,
    tree_depth=tree_depth,
    made_prediction=predicted_deck_id is not None
)

Gets converted to:

influx_metric("deck_prediction", fields, missing_cards=30 \
- \
 deck_size, player_class=CardClass(int(player_class)).name, format=FormatType(int(global_game.format)).name, tree_depth=tree_depth, made_prediction=predicted_deck_id is not None)

It knows that the line can be split before operators (which, although feasible, is almost never correct to do) and does it twice because that's how small it can get the line to be.

So I guess there's three issues but all boil down to the first one:

  1. prettier-python should learn how to split function arguments on newlines when necessary
  2. Multiline multi-assignment should be avoided
  3. Operator newline splitting should be avoided
FuegoFro commented 6 years ago

Yeah, there's a lot of formatting behavior that was roughed out just to get stuff printing, but it doesn't all wrap as one might expect. Two of the issues you highlighted here (wrapping function calls and how wrapping works after an equals sign) should both be improved by https://github.com/prettier/plugin-python/pull/52, and indeed both of your inputs remain unchanged when formatted by the code in that PR. I think the third point (operator newlines should be avoided) will come naturally as the other aspects are improved. The only reason it broke there was because nothing else offered to break farther up the print tree.