-
-
Notifications
You must be signed in to change notification settings - Fork 31.8k
Specialization of namedtuple types #92107
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
I'm not sure that it is a good idea to forbid parameterisation of The standard library has quite a few uses of If #92027 is merged, type checkers will be given the freedom to implement support for generic NamedTuples. If they do implement support, we'll want to make several of these stdlib namedtuple-at-runtime-but-NamedTuple-in-the-stub classes generic. If we forbid parameterisation of |
There isn't the same issue with forbidding runtime parameterisation of non-generic |
Is there a reason the PR just goes straight for option |
What about a namedtuple like this (for example): from collections import namedtuple
Foo = namedtuple("Foo", "dict_field list_field") In typeshed we might want to write a stub for this class like this: from typing import NamedTuple, Generic, TypeVar
T = TypeVar("T")
U = TypeVar("U")
V = TypeVar("V")
class Foo(NamedTuple, Generic[T, U, V]):
dict_field: dict[T, U]
list_field: list[V] A type checker will expect 3 parameters for this class, even though it only has two fields. So Option 2 would also be complicated to get right. |
Agree with @AlexWaygood; it can be useful to subscript collections.namedtuples if they are conceptually generic. We don't need to change anything here. |
@AlexWaygood, in your example the named tuple is generic. This issue is about non-generic named tuples. |
Indeed, but that was my point. If there's a class that's a non-generic |
collections.namedtuple()
creates atuple
subclass, and as a subclass it inherits alltuple
methods, including__class_getitem__
.The
__new__
method has been overridden in a named tuple class. It no longer accept an iterator of arbitrary length. The named tuple has fixed number of elements, and the constructor accept fixed number of arguments (some may be optional).But the
__class_getitem__
is inherited fromtuple
. It allows to specialize the named tuple type with arbitrary number of arguments.It looks confusing at best. A named tuple is not a general tuple, it cannot have an arbitrary number of items.
There are two options:
namedtuple()
. If you want to add type annotations, usetyping.NamedTuple
.__class_getitem__
which checks that the number of types corresponds to the size of the named tuple.@rhettinger
The text was updated successfully, but these errors were encountered: