django / django/new-features

Explicit timeouts via `datetime.timedelta`

Open
#156 1 comment 13 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
188
Forks
7
PR merge metrics
No merged PRs in 30d

Description

### Code of Conduct

- [x] I agree to follow Django's Code of Conduct

### Feature Description

I'd love to add support for `datetime.timedelta` for all public functions (like cache).

### Problem

Currently Django uses unitless primitive types like int or float. Those are by unofficial convention in seconds.

However, this "by convention" isn't apparent to new users. Across the Pythonverse, you can find anything from seconds to milliseconds and this convention doesn't expand beyond Django thus, might be unknown to many.

Furthermore, especially for larger interval this leads to funny code like:

```python
TIMEOUT = 60 * 60 * 24 # one day
```

People end up using multiplication to improve readability or add comments in natural language.

All that, while Python has a beautiful native duration type:

```python
TIMEOUT = datetime.timedelta(days=1)
```

### Request or proposal

proposal

### Additional Details

I want to highlight the DateTimeField here as a wonderful example.
Django does an outstanding job to help people avoid the pitfalls of naive datetimes.

I would like to transfer the same foolproof approach to timeouts.

### Implementation Suggestions

Since Django already uses seconds, we could have a small warning utility:

```python
def cast_timeout(timeout):
try:
return timeout.total_seconds()
except AttributeError:
warnings.warn("Abigous timeout values are deprecated in favor of datetime.timedelta", DeprecationWarning)
return timeout
```

The EAFP approach avoids an instruction branch, which is good for runtime performance.
The warning can range from just a UserWarning to full deprecation. Depending on what serse the community best.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.