Alex Waygood <alex.wayg...@gmail.com> added the comment:

Consider the typeshed stub for `concurrent.futures.DoneAndNotDoneFutures`. At 
runtime this is a `collections.namedtuple`, but in the stub, we need it to be 
generic to allow precise type inference. But we can't have a generic 
NamedTuple, so the stub is currently this:

```
class DoneAndNotDoneFutures(Sequence[set[Future[_T]]]):
    @property
    def done(self) -> set[Future[_T]]: ...
    @property
    def not_done(self) -> set[Future[_T]]: ...
    def __new__(_cls, done: set[Future[_T]], not_done: set[Future[_T]]) -> 
DoneAndNotDoneFutures[_T]: ...
    def __len__(self) -> int: ...
    @overload
    def __getitem__(self, __i: SupportsIndex) -> set[Future[_T]]: ...
    @overload
    def __getitem__(self, __s: slice) -> DoneAndNotDoneFutures[_T]: ...
```

Until two days ago, this stub actually had a bug: `done` and `not_done` were 
both given as writeable attributes, whereas they are read-only properties at 
runtime.

With generic NamedTuples, we could write the stub for the class far more simply 
(and more accurately) like this:

```
class DoneAndNotDoneFutures(NamedTuple, Generic[_T]):
    done: set[Future[_T]]
    not_done: set[Future[_T]]
```

And in code that actually needs to run at runtime, I frequently find it 
frustrating that I have to use dataclasses instead of NamedTuples if I want a 
simple class that just happens to be generic. dataclasses are great, but for 
small, lightweight classes, I prefer to use NamedTuples where possible. I often 
find that I don't need to use the full range of features dataclasses provide; 
and NamedTuples are often more performant than dataclasses, especially in cases 
where there's a lot of tuple unpacking.

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue43923>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to