Behaviour of time.sleep with negative arg

Jeff Epler jepler at unpythonic.net
Sun Mar 14 16:19:53 EST 2004


On Mon, Mar 15, 2004 at 08:43:51AM +1300, Colin Brown wrote:
> "Jeff Epler" <jepler at unpythonic.net> wrote in message
> news:mailman.15.1079236344.745.python-list at python.org...
> > I'd agree that time.sleep(interval) should do the same thing on all
> > platforms when interval<0, but I'd rather see it always raise an
> > exception than sleep for 0 seconds.
> 
> I am 100% with you that time.sleep() should perform the same on all
> platforms but would rather the sleep(0) for negative args because:
>     1.    2**31 seconds is about 68 years so interpreting a negative integer
> as unsigned is practically useless

I was not arguing that it was too useful to be able to sleep for 68
years (and certainly not that the argument -1 should be interpreted to
mean 68 years), but rather that sleep(-1) is a TypeError or ValueError
because it's not in the range of valid arguments to sleep.

>     2.    A common usage of sleep is with the difference of two values. If
> it raises an exception on negative numbers then when one takes the
> difference of say a timestamp and current-time (real-values), to be safe you
> would need to put the difference in a temporary variable, check that for
> negative and only sleep for positive values - not very elegant.

def unsurprising_sleep(d):
    if d < 0: return
    time.sleep(d)

> Whatever is decided, the behaviour needs to be documented under time.sleep!

    sleep(secs)
        Suspend execution for the given number of seconds. The argument
        may be a floating point number to indicate a more precise
        sleep time. The actual suspension time may be less than that
        requested because any caught signal will terminate the sleep()
        following execution of that signal's catching routine. Also,
        the suspension time may be longer than requested by an arbitrary
        amount because of the scheduling of other activity in the system.

+       The behavior when secs is less than zero is undefined.  In particular,
+       a future version of Python may interpret 'time.sleep(-1); other code'
+       to cause 'other code' to execute beginning one second before the call
+       to time.sleep.

You can find my proposed enhancement to the documentation above.

Jeff




More information about the Python-list mailing list