Skip to content

Commit

Permalink
Address review (and fix bug)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexWaygood committed Nov 16, 2023
1 parent e0c88f0 commit d8102fd
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
11 changes: 10 additions & 1 deletion Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -7519,7 +7519,7 @@ class GenericNamedTuple(NamedTuple, Generic[T]):

self.assertEqual(CallNamedTuple.__orig_bases__, (NamedTuple,))

def test_setname_called_on_non_members(self):
def test_setname_called_on_values_in_class_dictionary(self):
class Vanilla:
def __set_name__(self, owner, name):
self.name = name
Expand All @@ -7533,6 +7533,15 @@ class Foo(NamedTuple):
self.assertIsInstance(foo.attr, Vanilla)
self.assertEqual(foo.attr.name, "attr")

class Bar(NamedTuple):
attr: Vanilla = Vanilla()

bar = Bar()
self.assertEqual(len(bar), 1)
self.assertIn('attr', Bar._fields)
self.assertIsInstance(bar.attr, Vanilla)
self.assertEqual(bar.attr.name, "attr")

def test_setname_raises_the_same_as_on_other_classes(self):
class CustomException(BaseException): pass

Expand Down
14 changes: 10 additions & 4 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2729,17 +2729,23 @@ def __new__(cls, typename, bases, ns):
for key, val in ns.items():
if key in _prohibited:
raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
elif key not in _special and key not in nm_tpl._fields:
setattr(nm_tpl, key, val)
if hasattr(type(val), "__set_name__"):
elif key not in _special:
if key not in nm_tpl._fields:
setattr(nm_tpl, key, val)
try:
set_name = type(val).__set_name__
except AttributeError:
pass
else:
try:
type(val).__set_name__(val, nm_tpl, key)
set_name(val, nm_tpl, key)
except BaseException as e:
e.add_note(
f"Error calling __set_name__ on {type(val).__name__!r} "
f"instance {key!r} in {typename!r}"
)
raise

if Generic in bases:
nm_tpl.__init_subclass__()
return nm_tpl
Expand Down

0 comments on commit d8102fd

Please sign in to comment.