3 ms·
My preferred way in Python is: ``` time.sleep(timedelta(minutes=5).total_seconds) ``` Or ``` time_to_sleep = timedelta(minutes=5) time.sleep(time_to_sleep
by amingilani 5y ago
My preferred way in Python is:
```
time.sleep(timedelta(minutes=5).total_seconds)
```
Or
```
time_to_sleep = timedelta(minutes=5)
time.sleep(time_to_sleep.total_seconds())
```
- jeffparsons 5y agoUnless I'm confident that I remember `time.sleep` wants a number of seconds, then I could miss an obvious error there. For example... time.sleep(timedelta(minutes=5).total_milliseconds) ...looks just as plausible. So what does this solve?
- amingilani 5y agoIt communicates my intent to the reviewer and future readers of the code that: 1) I mean to set the duration to 5 minutes, which is easier parsed by humans than 300 seconds. 2) I'm passing seconds into time.sleep, which makes any mistakes I make more obvious. I'm not saying time.sleep can't be improved but my method makes it easier to find any mistakes I've made in the future. As a demonstration, reading your code makes it more obvious that you've passed the wrong unit into time.sleep.
- jeffparsons 5y agoGot it — so it's more about mitigating the badness when it's somebody else's API. Seems reasonable! :) When I encounter these sorts of methods (which is surprisingly rare these days) I tend to double-check what units the method takes and additionally add a comment above my call saying "`sleep` takes duration in seconds", just to give future readers more ways to check whether I screwed up.