-
-
Notifications
You must be signed in to change notification settings - Fork 31.1k
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
typing.NamedTuple does not support mixins #80698
Comments
Subclassing typing.NamedTuple an inheriting from a mixin class does not work. It does work for collections.namedtuple, and can be worked around by modifying typing.NamedTupleMeta: >>> import collections
>>> import typing
>>>
>>>
>>> class Mixin:
... def mixin(self):
... return "mixin"
...
>>>
>>> class CollectionsNamedTuple(Mixin, collections.namedtuple('CollectionsNamedTuple', [
... "a",
... "b",
... ])):
... pass
...
>>>
>>> class TypingNamedTuple(Mixin, typing.NamedTuple):
... a: str
... b: str
...
>>>
>>> class NamedTupleMeta(typing.NamedTupleMeta):
... def __new__(cls, typename, bases, ns):
... cls_obj = super().__new__(cls, typename + '_nm_base', bases, ns)
... bases = bases + (cls_obj,)
... return type(typename, bases, {})
...
>>>
>>> class FixedTypingNamedTuple(Mixin, metaclass=NamedTupleMeta):
... a: str
... b: str
...
>>>
>>> cnt = CollectionsNamedTuple("av", "bv")
>>> tnt = TypingNamedTuple("av", "bv")
>>> ftnt = FixedTypingNamedTuple("av", "bv")
>>>
>>> cnt.mixin()
'mixin'
>>> ftnt.mixin()
'mixin'
>>> tnt.mixin()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'TypingNamedTuple' object has no attribute 'mixin' |
Hm, it looks like we can support this. I however don't think the proposed "patch" is the right way to fix it, since this makes the implementation with and without a mixin quite different. Also I am not sure I will have time to work on this in the nearest month. |
The patch PR blocks out a useful idiom: generic Nametuple >>> class LLNode(NamedTuple, Generic[T]):
... value :T
... next: Optional[LLNode[T]] I put forward that, at the least, NamedTuple should accept do-nothing bases like Generic. |
Generic NamedTuples are supported on 3.11+, and the decision has been taken to prohibit mixins in other situations. I don't think we'll be changing that now. Closing as completed. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: