I’m trying to adhere to PEP 8, with a 78 character limit on the length of my lines.
I have the following statement:
startTime = time.strptime(request.GET.get('st', (dt.datetime.now() - dt.timedelta(days=1)).strftime("%d/%b/%Y:%H:%M:%S")), "%d/%b/%Y:%H:%M:%S")
How should I format it so that it adheres to PEP8 (where should I break it into new lines?)
3
You shouldn’t break it into new lines, since the code itself is wrong.
First, you have code duplication. The compiler won’t blame you and won’t qualify it as an error, but programmers who will have to maintain your code later surely will.
By removing code duplication, instead of:
startTime = time.strptime(request.GET.get('st', (dt.datetime.now() - dt.timedelta(days = 1)).strftime("%d/%b/%Y:%H:%M:%S")), "%d/%b/%Y:%H:%M:%S")
you get:
const dateFormat = "%d/%b/%Y:%H:%M:%S"
startTime = time.strptime(request.GET.get('st', (dt.datetime.now() - dt.timedelta(days = 1)).strftime(dateFormat)), dateFormat)
Another error is that you’re doing too much in a single line. Who are you writing for? The compiler, or other developers (including yourself in six months)?
-
If you’re writing for a compiler, indeed, collapsing everything into a big mess may give you a few microseconds advantage of compile time and a few microseconds of advantage every time the app is running. Or maybe there is no gain. Or maybe such code is slower. You have to profile it to know.
-
If you’re writing for humans, and you should, then don’t be greedy with whitespace, newlines, intermediary variables and functions. For example, all those parentheses together are a maintenance nightmare. I could hardly find what is closed where. It’s also hard to understand what the code is doing just by looking at it.
What about:
const dateFormat = "%d/%b/%Y:%H:%M:%S"
dayAgo = (dt.datetime.now() - dt.timedelta(days = 1)).strftime(dateFormat)
webResponse = request.GET.get('st', dayAgo)
startTime = time.strptime(webResponse, , dateFormat)
Note that standards are good for they are. They are here for you, not the opposite. They should help you, not force you to spend hours doing meaningless changes.
If a standard tells that the line should be 80 characters long, but you have a perfectly valid case of a readable line with 81 characters in it, screw the standard.
In this particular case, the original line was indeed badly written, and it was a case where the standard gave you a hint that something was wrong. This is not always the case.
7