Given this Python class, implementing a Django form, how would you properly break this to meet the PEP8 standards?
class MyForm(forms.Form):
categories = forms.CharField(required=False,
widget=forms.SelectMultiple(choices=CATEGORY_VALUE),
label="Categories")
additional_item_ship_cost = forms.CharField(required=False, max_length=10,
label="Additional Item Ship Cost")
Specifically, the widget= and label= parameters violate the PEP8 rules for line length.
What comes to mind immediately is that I could define the widget and label outside of the class and then use them in the class definition, but that feels very un-pythonic.
You already know that you can split a line inside parens at a comma. Did you know that you can always use the backslash-newline combination to split lines where you can't otherwise split them?:
In addition, you might not know that Python will concatenate adjacent literal strings, throwing away any whitespace between them, so the above could be rewritten as:
Finally, inside parens, you can split lines at a 'dot' just like you can at a comma, and you can use parens JUST to gain this ability:
Combine all of these with judicious de-indenting of subsequent split lines, and you should be able to avoid exceeding an 80-character line.
I agree with using double (8-column) indentation for continuation lines, since it easily distinguishes continuation from block indentation. I also want the indentation to be independent of the length of the first line; the length will change as the code is maintained, but that should not necessitate changing the continuation lines.
So don't line up continuation lines with anything on the first line; instead, use the same relative indentation for any continuation line.
Backslashes for continuation are problematic (invisible trailing whitespace can change the effect), and fortunately are almost never necessary, since Python automatically continues the statement within open bracketing syntax. Breaking function calls at the open-paren (and dicts at the open-brace, lists at the open-bracket, etc.) is what I reach for first.
So I'd do:
I don't think PEP8 says much about it, but I would simply go with double indentation for the parameters: