classification
Title: typing.NamedTuple default parameter type issue
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: PBrudny, eric.smith
Priority: normal Keywords:

Created on 2019-08-07 09:32 by PBrudny, last changed 2019-08-07 10:11 by eric.smith. This issue is now closed.

Files
File name Uploaded Description Edit
test.py PBrudny, 2019-08-07 09:32
Messages (2)
msg349157 - (view) Author: PBrudny (PBrudny) Date: 2019-08-07 09:32
There is an issue when NamedTuple parameter with default, which has not explicitly declared type is changed by keyword. Is that an expected behavior (no info https://docs.python.org/3.7/library/collections.html#collections.namedtuple)

Used python release:
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32

test.py:

from typing import NamedTuple


class MyTestedTuple(NamedTuple):
    example_text = "default_text"
    example_int: int = 3


if __name__ == '__main__':
    print(MyTestedTuple().example_text)
    fault_tuple = MyTestedTuple(example_text="text_from_call")
    print(fault_tuple.example_text)

Call:

python test.py

default_text

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    fault_tuple = MyTestedTuple(example_text="text_from_call")
TypeError: __new__() got an unexpected keyword argument 'example_text'
msg349159 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2019-08-07 10:11
example_text is not a field, since you're not giving it a type. It's just a normal class member.

The only field in the NamedTuple is example_int. You can't specify any other field in the call to MyTestedTuple().

To see this, help(MyTestedTuple) starts with:

class MyTestedTuple(builtins.tuple)
 |  MyTestedTuple(example_int: int = 3)
History
Date User Action Args
2019-08-07 10:11:52eric.smithsetstatus: open -> closed

nosy: + eric.smith
messages: + msg349159

resolution: not a bug
stage: resolved
2019-08-07 09:32:13PBrudnycreate