Skip to content

Also test typing.NamedTuple with copy.replace #109956

Closed

Description

@sobolevn

Bug report

Right now only collections.namedtuple is tested:

def test_namedtuple(self):
from collections import namedtuple
Point = namedtuple('Point', 'x y', defaults=(0,))
p = Point(11, 22)
self.assertEqual(copy.replace(p), (11, 22))
self.assertEqual(copy.replace(p, x=1), (1, 22))
self.assertEqual(copy.replace(p, y=2), (11, 2))
self.assertEqual(copy.replace(p, x=1, y=2), (1, 2))
with self.assertRaisesRegex(ValueError, 'unexpected field name'):
copy.replace(p, x=1, error=2)

@serhiy-storchaka noted in #108752 (comment) that only named tuples created by collections.namedtuple() are supported. But, since typing.NamedTuple uses collections.namedtuple inside:

cpython/Lib/typing.py

Lines 2695 to 2696 in b1aebf1

nm_tpl = collections.namedtuple(name, fields,
defaults=defaults, module=module)
it is also supported:

>>> import typing
>>> 
>>> class N(typing.NamedTuple):
...    x: int
...    y: int
... 
>>> N.__replace__
<function N._replace at 0x10580a210>
>>> import copy
>>> copy.replace(N(1, 2), x=3)
N(x=3, y=2)

I have a PR ready with extra tests.

Refs #108751
Refs #108752

Linked PRs

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    testsTests in the Lib/test dir
    on Sep 27, 2023
  2. self-assigned this
    on Sep 27, 2023
  3. added a commit that references this issue on Sep 27, 2023
  4. serhiy-storchaka commented on Sep 29, 2023

    @serhiy-storchaka
    Member

    "Named tuple" is more general term (https://docs.python.org/3/glossary.html#term-named-tuple). Not all named tuples in wide meaning are supported (for example named tuples created by the PyStructSequence C API are not supported yet). typing.NamedTyple is a funny way to call collections.namedtuple(), so this note covers it too. If you want to test them, would not be better to add new tests to other typing.NamedTyple tests?

  5. added a commit that references this issue on Oct 3, 2023
  6. added a commit that references this issue on Sep 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

testsTests in the Lib/test dirtype-bugAn unexpected behavior, bug, or error

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions