Reputation: 4000
I understand the indention rules in Python until you start having lines that don't fit within the line length limits and need to be continued.
What is the official and cleanest way to indent the following code, if I am not permitted to have more than 100 chars on a line?
def OnKeyDownEvent(self, event):
if (event.Message == HookConstants.WM_KEYDOWN or event.Message == HookConstants.WM_KEYDOWN):
self.count_key_down += 1
I would try:
def OnKeyDownEvent(self, event):
if (event.Message == HookConstants.WM_KEYDOWN
or event.Message == HookConstants.WM_KEYDOWN):
self.count_key_down += 1
but then you get an error where the body and the condition are at the same indention levels.
Upvotes: 1
Views: 161
Reputation: 36013
There is no single official way, it must just follow PEP8 guidelines.
There's a code formatter called Black which is becoming quite popular, you can try it here. It formats your code like this:
def OnKeyDownEvent(self, event):
if (
event.Message == HookConstants.WM_KEYDOWN
or event.Message == HookConstants.WM_KEYDOWN
):
self.count_key_down += 1
probably because if you add another clause to your condition, the resulting diff will be minimal, i.e. just adding a line, no removals or changes.
Upvotes: 1
Reputation: 24681
My usual solution to this is, if I'm continuing a line right before starting a new level of indentation, to put the continuation two indents inwards instead of just one:
def OnKeyDownEvent(self, event):
if (event.Message == HookConstants.WM_KEYDOWN or
event.Message == HookConstants.WM_KEYDOWN):
self.count_key_down += 1
or, if I'm enumerating a list of something, wherever that list starts - whichever is further right on the page. I also put the operator on the initial line, rather than on the continuing line, to make it clear to both the reader and the interpreter that the expression isn't over yet. In your code you're enclosing the entire expression in parentheses, which serves that same purpose.
You can notate your code however you feel like is most clear, and then run it through a linter that'll reformat your code to be in line with PEP8 standards after the fact.
In your specific situation, a more concise way to write this condition is
def onKeyDownEvent(self, event):
if event.Message in [HookConstants.WM_KEYDOWN, HookConstants.WM_KEYDOWN]:
self.count_key_down += 1
which tends to be a good solution in general for the "if x == this or this or this" condition, and is more concise than writing multiple if
statements. This is more specific, though.
Upvotes: 3