-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Synthesize typed NamedTuple._replace so extra fields are errors #11642
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,6 +10,7 @@ | |
|
|
||
| import { DiagnosticRule } from '../common/diagnosticRules'; | ||
| import { convertOffsetsToRange } from '../common/positionUtils'; | ||
| import { PythonVersion, pythonVersion3_13 } from '../common/pythonVersion'; | ||
| import { TextRange } from '../common/textRange'; | ||
| import { LocMessage } from '../localization/localize'; | ||
| import { ArgCategory, ExpressionNode, ParamCategory, ParseNodeType } from '../parser/parseNodes'; | ||
|
|
@@ -44,6 +45,8 @@ import { | |
| combineTypes, | ||
| isClassInstance, | ||
| isInstantiableClass, | ||
| isKeywordOnlySeparator, | ||
| isPositionOnlySeparator, | ||
| } from './types'; | ||
|
|
||
| // Creates a new custom tuple factory class with named values. | ||
|
|
@@ -376,6 +379,14 @@ export function createNamedTupleType( | |
| classFields.set('__new__', Symbol.createWithType(SymbolFlags.ClassMember, constructorType)); | ||
| classFields.set('__init__', Symbol.createWithType(SymbolFlags.ClassMember, initType)); | ||
|
|
||
| synthesizeNamedTupleReplaceMethods( | ||
| classFields, | ||
| constructorType, | ||
| selfParam, | ||
| addGenericGetAttribute, | ||
| fileInfo.executionEnvironment.pythonVersion | ||
| ); | ||
|
|
||
| const lenType = FunctionType.createSynthesizedInstance('__len__'); | ||
| lenType.shared.declaredReturnType = evaluator.getBuiltInObject(errorNode, 'int'); | ||
| FunctionType.addParam(lenType, selfParam); | ||
|
|
@@ -422,6 +433,50 @@ export function createNamedTupleType( | |
| return classType; | ||
| } | ||
|
|
||
| function synthesizeNamedTupleReplaceMethods( | ||
| classFields: Map<string, Symbol>, | ||
| constructorType: FunctionType, | ||
| selfParam: FunctionParam, | ||
| addGenericGetAttribute: boolean, | ||
| pythonVersion: PythonVersion | ||
| ) { | ||
| const synthesizeDunderReplace = PythonVersion.isGreaterOrEqualTo(pythonVersion, pythonVersion3_13); | ||
| const replaceType = FunctionType.createSynthesizedInstance(synthesizeDunderReplace ? '__replace__' : '_replace'); | ||
| FunctionType.addParam(replaceType, selfParam); | ||
| FunctionType.addKeywordOnlyParamSeparator(replaceType); | ||
| replaceType.shared.declaredReturnType = selfParam._type; | ||
|
|
||
| if (addGenericGetAttribute) { | ||
| FunctionType.addDefaultParams(replaceType); | ||
| } else { | ||
| constructorType.shared.parameters.forEach((param) => { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Filtering parameters by the names |
||
| if (!param.name || param.name === 'cls' || param.name === 'self') { | ||
| return; | ||
| } | ||
|
|
||
| if (isPositionOnlySeparator(param) || isKeywordOnlySeparator(param)) { | ||
| return; | ||
| } | ||
|
|
||
| FunctionType.addParam( | ||
| replaceType, | ||
| FunctionParam.create( | ||
| param.category, | ||
| param._type, | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
This derives replacement fields from the synthesized constructor while the class-syntax NamedTuple path builds the corresponding signature in |
||
| param.flags, | ||
| param.name, | ||
| AnyType.create(/* isEllipsis */ true) | ||
| ) | ||
| ); | ||
| }); | ||
| } | ||
|
|
||
| if (synthesizeDunderReplace) { | ||
| classFields.set('__replace__', Symbol.createWithType(SymbolFlags.ClassMember, replaceType)); | ||
| } | ||
| classFields.set('_replace', Symbol.createWithType(SymbolFlags.ClassMember, replaceType)); | ||
| } | ||
|
|
||
| export function updateNamedTupleBaseClass(classType: ClassType, typeArgs: Type[], isTypeArgExplicit: boolean): boolean { | ||
| let isUpdateNeeded = false; | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # This sample tests that NamedTuple _replace rejects unknown fields | ||
| # and type-incompatible field values, matching runtime TypeError behavior. | ||
|
|
||
|
|
||
| from collections import namedtuple | ||
| from typing import NamedTuple | ||
|
|
||
|
|
||
| class NT1(NamedTuple): | ||
| x: int | ||
| y: str | ||
|
|
||
|
|
||
| nt1 = NT1(1, "") | ||
| nt1_clone = nt1._replace(x=2) | ||
| reveal_type(nt1_clone, expected_text="NT1") | ||
|
|
||
| # This should generate an error. | ||
| nt1._replace(z=1) | ||
|
|
||
| # This should generate an error. | ||
| nt1._replace(y=1) | ||
|
|
||
|
|
||
| NT2 = namedtuple("NT2", ["a", "b"]) | ||
| nt2 = NT2(1, 2) | ||
| nt2_clone = nt2._replace(a=3) | ||
| reveal_type(nt2_clone, expected_text="NT2") | ||
|
|
||
| # This should generate an error. | ||
| nt2._replace(c=1) | ||
|
|
||
|
|
||
| NT3 = NamedTuple("NT3", [("n", int), ("s", str)]) | ||
| nt3 = NT3(1, "") | ||
| nt3_clone = nt3._replace(s="ok") | ||
| reveal_type(nt3_clone, expected_text="NT3") | ||
|
|
||
| # This should generate an error. | ||
| nt3._replace(t="no") | ||
|
|
||
| # This should generate an error. | ||
| nt3._replace(n="") |
Uh oh!
There was an error while loading. Please reload this page.