8000 gh-116241: Add support of multiple inheritance with typing.NamedTuple by serhiy-storchaka · Pull Request #31781 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-116241: Add support of multiple inheritance with typing.NamedTuple #31781

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

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Merge branch 'main' into typing-namedtuple-multiple-inheritance
  • Loading branch information
serhiy-storchaka committed Mar 2, 2024
commit d4bc7117010bdf005e24aac36e9c51dbdb434194
18 changes: 17 additions & 1 deletion Doc/library/typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2076,7 +2076,7 @@ types.

``NamedTuple`` subclasses can be generic::

class Group(NamedTuple, Generic[T]):
class Group[T](NamedTuple):
key: T
group: list[T]

Expand Down Expand Up @@ -2105,6 +2105,22 @@ types.
standard ``__annotations__`` attribute which has the same information.

.. versionchanged:: 3.11
Added support for generic namedtuples.

.. deprecated-removed:: 3.13 3.15
The undocumented keyword argument syntax for creating NamedTuple classes
(``NT = NamedTuple("NT", x=int)``) is deprecated, and will be disallowed
in 3.15. Use the class-based syntax or the functional syntax instead.

.. deprecated-removed:: 3.13 3.15
When using the functional syntax to create a NamedTuple class, failing to
pass a value to the 'fields' parameter (``NT = NamedTuple("NT")``) is
deprecated. Passing ``None`` to the 'fields' parameter
(``NT = NamedTuple("NT", None)``) is also deprecated. Both will be
disallowed in Python 3.15. To create a NamedTuple class with 0 fields,
use ``class NT(NamedTuple): pass`` or ``NT = NamedTuple("NT", [])``.

.. versionchanged:: 3.13
Added support of multiple inheritence.

.. class:: NewType(name, tp)
Expand Down
93 changes: 92 additions & 1 deletion Doc/whatsnew/3.11.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1092,12 +1092,103 @@ time
(Contributed by Benjamin Szőke, Donghee Na, Eryk Sun and Victor Stinner in :issue:`21302` and :issue:`45429`.)


.. _whatsnew311-tkinter:

tkinter
-------

* Added method ``info_patchlevel()`` which returns the exact version of
the Tcl library as a named tuple similar to :data:`sys.version_info`.
(Contributed by Serhiy Storchaka in :gh:`91827`.)


.. _whatsnew311-traceback:

traceback
---------

* Add :func:`traceback.StackSummary.format_frame_summary` to allow users
to override which frames appear in the traceback, and how they are
formatted.
(Contributed by Ammar Askar in :issue:`44569`.)

* Add :func:`traceback.TracebackException.print`, which prints the
formatted :exc:`~traceback.TracebackException` instance to a file.
(Contributed by Irit Katriel in :issue:`33809`.)


.. _whatsnew311-typing:

typing
------

* Added support of multiinheritance with :class:`~typing.NamedTuple`.
For major changes, see :ref:`new-feat-related-type-hints-311`.

* Add :func:`typing.assert_never` and :class:`typing.Never`.
:func:`typing.assert_never` is useful for asking a type checker to confirm
that a line of code is not reachable. At runtime, it raises an
:exc:`AssertionError`.
(Contributed by Jelle Zijlstra in :gh:`90633`.)

* Add :func:`typing.reveal_type`. This is useful for asking a type checker
what type it has inferred for a given expression. At runtime it prints
the type of the received value.
(Contributed by Jelle Zijlstra in :gh:`90572`.)

* Add :func:`typing.assert_type`. This is useful for asking a type checker
to confirm that the type it has inferred for a given expression matches
the given type. At runtime it simply returns the received value.
(Contributed by Jelle Zijlstra in :gh:`90638`.)

* :data:`typing.TypedDict` types can now be generic. (Contributed by
Samodya Abeysiriwardane in :gh:`89026`.)

* :class:`~typing.NamedTuple` types can now be generic.
(Contributed by Serhiy Storchaka in :issue:`43923`.)

* Allow subclassing of :class:`typing.Any`. This is useful for avoiding
type checker errors related to highly dynamic class, such as mocks.
(Contributed by Shantanu Jain in :gh:`91154`.)

* The :func:`typing.final` decorator now sets the ``__final__`` attributed on
the decorated object.
(Contributed by Jelle Zijlstra in :gh:`90500`.)

* The :func:`typing.get_overloads` function can be used for introspecting
the overloads of a function. :func:`typing.clear_overloads` can be used
to clear all registered overloads of a function.
(Contributed by Jelle Zijlstra in :gh:`89263`.)

* The :meth:`~object.__init__` method of :class:`~typing.Protocol` subclasses
is now preserved. (Contributed by Adrian Garcia Badarasco in :gh:`88970`.)

* The representation of empty tuple types (``Tuple[()]``) is simplified.
This affects introspection, e.g. ``get_args(Tuple[()])`` now evaluates
to ``()`` instead of ``((),)``.
(Contributed by Serhiy Storchaka in :gh:`91137`.)

* Loosen runtime requirements for type annotations by removing the callable
check in the private ``typing._type_check`` function. (Contributed by
Gregory Beauregard in :gh:`90802`.)

* :func:`typing.get_type_hints` now supports evaluating strings as forward
references in :ref:`PEP 585 generic aliases <types-genericalias>`.
(Contributed by Niklas Rosenstein in :gh:`85542`.)

* :func:`typing.get_type_hints` no longer adds :data:`~typing.Optional`
to parameters with ``None`` as a default. (Contributed by Nikita Sobolev
in :gh:`90353`.)

* :func:`typing.get_type_hints` now supports evaluating bare stringified
:data:`~typing.ClassVar` annotations. (Contributed by Gregory Beauregard
in :gh:`90711`.)

* :func:`typing.no_type_check` no longer modifies external classes and functions.
It also now correctly marks classmethods as not to be type checked. (Contributed
by Nikita Sobolev in :gh:`90729`.)


.. _whatsnew311-unicodedata:

unicodedata
-----------
Expand Down
3 changes: 3 additions & 0 deletions Doc/whatsnew/3.13.rst
Original file line number Diff line number Diff line change
Expand Up @@ -582,6 +582,9 @@ typing
check whether a class is a :class:`typing.Protocol`. (Contributed by Jelle Zijlstra in
:gh:`104873`.)

* Add support of multiple inheritance with :class:`~typing.NamedTuple`.
(Contributed by Serhiy Storchaka in :gh:`116241`.)

unicodedata
-----------

Expand Down
71 changes: 57 additions & 14 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -7489,16 +7489,21 @@ class Y(A, NamedTuple):
self.assertEqual(len(a), 10)

def test_multiple_inheritance_errors(self):
class A(NamedTuple):
x: int
with self.assertRaises(TypeError):
class X(NamedTuple, A):
x: int
with self.assertRaises(TypeError):
class X(NamedTuple, tuple):
class Y(NamedTuple, tuple):
x: int
with self.assertRaises(TypeError):
class X(NamedTuple, NamedTuple):
class Z(NamedTuple, NamedTuple):
x: int
class A(NamedTuple):
class B(NamedTuple):
x: int
with self.assertRaises(TypeError):
class X(NamedTuple, A):
class C(NamedTuple, B):
y: str

def test_generic(self):
Expand All @@ -7508,18 +7513,56 @@ class X(NamedTuple, Generic[T]):
self.assertEqual(X.__orig_bases__, (NamedTuple, Generic[T]))
self.assertEqual(X.__mro__, (X, tuple, Generic, object))

A = X[int]
self.assertEqual(A.__bases__, (tuple, Generic))
self.assertEqual(A.__orig_bases__, (NamedTuple, Generic[T]))
self.assertEqual(A.__mro__, (X, tuple, Generic, object))
self.assertIs(A.__origin__, X)
self.assertEqual(A.__args__, (int,))
self.assertEqual(A.__parameters__, ())
class Y(Generic[T], NamedTuple):
x: T
self.assertEqual(Y.__bases__, (Generic, tuple))
self.assertEqual(Y.__orig_bases__, (Generic[T], NamedTuple))
self.assertEqual(Y.__mro__, (Y, Generic, tuple, object))

for G in X, Y:
with self.subTest(type=G):
self.assertEqual(G.__parameters__, (T,))
self.assertEqual(G[T].__args__, (T,))
self.assertEqual(get_args(G[T]), (T,))
A = G[int]
self.assertIs(A.__origin__, G)
self.assertEqual(A.__args__, (int,))
self.assertEqual(get_args(A), (int,))
self.assertEqual(A.__parameters__, ())

a = A(3)
self.assertIs(type(a), G)
self.assertEqual(a.x, 3)

a = A(3)
self.assertIs(type(a), X)
self.assertEqual(a.x, 3)
with self.assertRaises(TypeError):
G[int, str]

def test_generic_pep695(self):
class X[T](NamedTuple):
x: T
T, = X.__type_params__
self.assertIsInstance(T, TypeVar)
self.assertEqual(T.__name__, 'T')
self.assertEqual(X.__bases__, (tuple, Generic))
self.assertEqual(X.__orig_bases__, (NamedTuple, Generic[T]))
self.assertEqual(X.__mro__, (X, tuple, Generic, object))
self.assertEqual(X.__parameters__, (T,))
self.assertEqual(X[str].__args__, (str,))
self.assertEqual(X[str].__parameters__, ())

def test_non_generic_subscript(self):
# For backward compatibility, subscription works
# on arbitrary NamedTuple types.
class Group(NamedTuple):
key: T
group: list[T]
A = Group[int]
self.assertEqual(A.__origin__, Group)
self.assertEqual(A.__parameters__, ())
self.assertEqual(A.__args__, (int,))
a = A(1, [2])
self.assertIs(type(a), Group)
self.assertEqual(a, (1, [2]))

def test_namedtuple_keyword_usage(self):
with self.assertWarnsRegex(
Expand Down
3 changes: 3 additions & 0 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2809,6 +2809,9 @@ def __new__(cls, typename, bases, ns):
defaults=[ns[n] for n in default_names],
module=ns['__module__'])
nm_tpl.__bases__ = bases
if Generic in bases:
class_getitem = _generic_class_getitem
nm_tpl.__class_getitem__ = classmethod(class_getitem)
# update from user namespace without overriding special namedtuple attributes
for key, val in ns.items():
if key in _prohibited:
Expand Down
You are viewing a condensed version of this merge commit. You can view the full changes here.
0