-
-
Notifications
You must be signed in to change notification settings - Fork 32k
implement __class_getitem__
for some classes in itertools
module
#112896
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
@JelleZijlstra Can you weigh in on this? Isn't it the norm to use I would think it would be bad design for a function to dictate how its input is formed:
|
I'm also a bit skeptical here, and you are right that in most cases users should not write annotations like This is very similar to #108761, which asks to make builtins like |
In general, I agree with @rhettinger and @JelleZijlstra. It's generally an antipattern to specify the exact type of iterator you need, unless that iterator has some special attributes or methods that distinguish it in some way from other kinds of iterators. Having said that, I think there is a good argument for adding import operator
from collections.abc import Callable, Iterable, Iterator
from itertools import groupby
def unique_justseen1[T](
iterable: Iterable[T], key: Callable[[T], bool] | None = None
) -> Iterator[T]:
g: groupby[T | bool, T] = groupby(iterable, key)
return map(next, map(operator.itemgetter(1), g))
def unique_justseen2[T](
iterable: Iterable[T], key: Callable[[T], bool] | None = None
) -> Iterator[T]:
g: Iterator[tuple[Iterator[T | bool], T]] = groupby(iterable, key)
return map(next, map(operator.itemgetter(1), g)) The former is obviously much more ergonomic. |
It does look a little nicer but it is only reasonable in this specific context where the type annotation is not leaked outside the function. If the return type was a groupby object, we would still be better off with the second form; otherwise, we fall into the concrete type specific anti-pattern again. And even with this self-contained example, it is still questionable. As a code reviewer trying to understand this small data pipeline, I still need to mentally unroll |
That's fair; those are all reasonable points |
I think this can be closed now. If new PEPs get approved that change the landscape, this can be reopened. |
Uh oh!
There was an error while loading. Please reload this page.
Feature or enhancement
Proposal:
Currently only
itertools.chain
can be subscripted at runtime. I think most of other iterators should be subscriptable too.Most of these classes are generic in typeshed, so typecheckers thing that subscripting them is fine, which is inconsistent with behaviour at runtime.
With pyright:
At runtime:
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
#108761 and #108761 (comment)
The text was updated successfully, but these errors were encountered: