Search code examples
pythonword-wrap

How to line wrap a statement that uses a "true_value if condition else false_value" syntax


I want to wrap this next single line of Python code to < 80 char in accordance with PEP 8.

self.settings["bid"]["soloslim_plays_first"] = "True" if settings_pane.check_soloslim_plays_first.isChecked() else "False"

This line does not have any parenthesis, so this is what I came up with:

self.settings["deal"]["dealer_can_shuffle"] = "True" \
        if settings_pane.check_dealer_shuffle.isChecked() \
        else "False"

I don't really like this because true-value & false-value aren't aligned. Is there a better way of wrapping it (e.g. without the backslashes)? I prefer my verbose variable object names, so please don't suggest replacing check_soloslim_plays_first by cspf ;-)


Solution

  • If you add parentheses, around the contents of the if statement, then you can format it like this:

    self.settings["bid"]["soloslim_plays_first"] = "True" if (
        settings_pane.check_soloslim_plays_first.isChecked()) else "False"
    

    Another option is to wrap the whole conditional expression in parantheses:

    self.settings["bid"]["soloslim_plays_first"] = (
        "True" if settings_pane.check_soloslim_plays_first.isChecked()
        else "False")