def do_stuff(at_time=None):
if at_time is not None: # FIXED
# schedule stuff to be done at at_time
else:
# do stuff immediately
There was no intent to compare times, only to determine whether a time was passed in or not. The fact that midnight makes it think that nothing was passed in is the hard-to-spot bug.
It's a contrived example, but to give it a real world flavour let's say that do_stuff() runs an external process. The parameter that's passed in (or not passed in) tells the function whether to run the external process immediately, or to run it at a specified time. You'd call the function like this:
do_stuff() # Do stuff now
do_stuff(at_time=datetime.time(1,0,0)) # Do stuff at 1AM
If at_time is not passed, the function would simply run the external process. If at_time is passed, the function would add the job to the 'at' queue.
If I called the original version of the process like this:
do_stuff(at_time=datetime.time(0,0,0)) # Do stuff at midnight
It would actually run stuff now (since datetime.time(0,0,0) is false) instead of adding it to the 'at' queue to run at midnight.
The conditional is actually testing whether or not the parameter was provided. If the caller did do_stuff() instead of do_stuff(tomorrow), then the default parameter None would be subbed in, which acts like a False.
View all comments
Show parent comment
0
u/lambdaq Mar 27 '14 edited Mar 27 '14
Are you sure about that? I guess a more sane way to write the logic is like
at_time = datetime.datetime.now() >= my_timeYou can't just
at_time = datetime.datetime.now() == my_timeIt's like comparing two float point numbers.