If your algorithm can notcannot find a date, it is easier to raise an Exception thenthan to return ''
. returningReturning sentinel values instead of exceptions can lead to unexpected behaviour if the user of this function does not test for this sentinel value.
CommenstComments should explain why you did something, not how. # Take the last four digits
tells you nothing more than the code itself. I would rather comment at field[-4 - i:n - i]
why you did n - i
instead of just -i
.
Instead of nesting a number of if-clauses, it can be better to test the negative of the condition, and continue
, so the rest of the code is less nested.
Don't test condition is True
. Just do condition
. In Python a lot of values can act as True
or False
in tests.
Your match
is never used anyway,anyway; the moment you set it to True
, you also return the result, so a while True:
would have sufficed here.
returnReturn type
While Truewhile True
You use a while Truewhile True
-loop, with an incrementing counter. A better way to do this would be to either use for i in range(...)
or using itertools.count
: for i in itertools.count()
. In this case you know there will be no more thenthan len(field) - 7
iterations, so you might as well use that.
revertRevert the algorithm
You explicitly test whether the substring is 8 characters long, and then if it is in the right format. By changing the while True
to the for
-loop, you know the substring will be 8 characters long. thenThen it makes sense to first try to convert it to a datetime
, and then check whether the year is correct: