Typed version of namedtuple. Usage:: class Employee(NamedTuple): name: str id: int This is equivalent to:: Employee = collections.namedtuple('Employee', ['name', 'id']) The resulting class has an extra __annotations__ attribute, giving a d
(typename, fields=_sentinel, /, **kwargs)
| 3039 | |
| 3040 | |
| 3041 | def NamedTuple(typename, fields=_sentinel, /, **kwargs): |
| 3042 | """Typed version of namedtuple. |
| 3043 | |
| 3044 | Usage:: |
| 3045 | |
| 3046 | class Employee(NamedTuple): |
| 3047 | name: str |
| 3048 | id: int |
| 3049 | |
| 3050 | This is equivalent to:: |
| 3051 | |
| 3052 | Employee = collections.namedtuple('Employee', ['name', 'id']) |
| 3053 | |
| 3054 | The resulting class has an extra __annotations__ attribute, giving a |
| 3055 | dict that maps field names to types. (The field names are also in |
| 3056 | the _fields attribute, which is part of the namedtuple API.) |
| 3057 | An alternative equivalent functional syntax is also accepted:: |
| 3058 | |
| 3059 | Employee = NamedTuple('Employee', [('name', str), ('id', int)]) |
| 3060 | """ |
| 3061 | if fields is _sentinel: |
| 3062 | if kwargs: |
| 3063 | deprecated_thing = "Creating NamedTuple classes using keyword arguments" |
| 3064 | deprecation_msg = ( |
| 3065 | "{name} is deprecated and will be disallowed in Python {remove}. " |
| 3066 | "Use the class-based or functional syntax instead." |
| 3067 | ) |
| 3068 | else: |
| 3069 | deprecated_thing = "Failing to pass a value for the 'fields' parameter" |
| 3070 | example = f"`{typename} = NamedTuple({typename!r}, [])`" |
| 3071 | deprecation_msg = ( |
| 3072 | "{name} is deprecated and will be disallowed in Python {remove}. " |
| 3073 | "To create a NamedTuple class with 0 fields " |
| 3074 | "using the functional syntax, " |
| 3075 | "pass an empty list, e.g. " |
| 3076 | ) + example + "." |
| 3077 | elif fields is None: |
| 3078 | if kwargs: |
| 3079 | raise TypeError( |
| 3080 | "Cannot pass `None` as the 'fields' parameter " |
| 3081 | "and also specify fields using keyword arguments" |
| 3082 | ) |
| 3083 | else: |
| 3084 | deprecated_thing = "Passing `None` as the 'fields' parameter" |
| 3085 | example = f"`{typename} = NamedTuple({typename!r}, [])`" |
| 3086 | deprecation_msg = ( |
| 3087 | "{name} is deprecated and will be disallowed in Python {remove}. " |
| 3088 | "To create a NamedTuple class with 0 fields " |
| 3089 | "using the functional syntax, " |
| 3090 | "pass an empty list, e.g. " |
| 3091 | ) + example + "." |
| 3092 | elif kwargs: |
| 3093 | raise TypeError("Either list of fields or keywords" |
| 3094 | " can be provided to NamedTuple, not both") |
| 3095 | if fields is _sentinel or fields is None: |
| 3096 | import warnings |
| 3097 | warnings._deprecated(deprecated_thing, message=deprecation_msg, remove=(3, 15)) |
| 3098 | fields = kwargs.items() |