Skip to content

Report duplicate KW_ONLY separators in dataclasses - #11495

Merged
Rich Chiodo (rchiodo) merged 1 commit into
microsoft:mainfrom
rchiodo:fix11451
Jun 29, 2026
Merged

Rich Chiodo (rchiodo) merged 1 commit into
microsoft:mainfrom
rchiodo:fix11451

Conversation

@rchiodo

@rchiodo Rich Chiodo (rchiodo) commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Pyright recognized the dataclass KW_ONLY sentinel only when it was assigned to a field named _. At runtime, the dataclasses module treats any field annotated as KW_ONLY as the keyword-only separator regardless of name. That core name-guard removal (the original #11451 fix) has since landed on main via #11486, so this PR is rebased on top of it and contributes the remaining test coverage plus a related correctness diagnostic.

Changes

After rebasing onto current main (which already contains the #11486 name-guard removal), this PR adds:

  1. New diagnostic — duplicate KW_ONLY separators. CPython raises TypeError: '<name>' is KW_ONLY, but KW_ONLY has already been specified when more than one KW_ONLY separator appears in a single dataclass. Pyright previously accepted this silently. dataClasses.ts now checks sawKeywordOnlySeparator before setting it and reports a reportGeneralTypeIssues diagnostic on the second separator.
    • New NLS key Diagnostic.dataClassDuplicateKwOnly (localize.ts + package.nls.en-us.json). The key is inserted as its own entry without modifying the adjacent dataClassFieldInheritedDefault line, so there is no Prettier/JSON whitespace change.
  2. Test coverage in dataclassKwOnly1.py:

Testing

  • npx jest typeEvaluator4 -t "DataClassKwOnly1" passes.
  • prettier -c and eslint pass on the changed files.

Addresses

Relates to https://github.com/microsoft/pylance-release/issues/11451 (the core recognition fix landed separately in #11486).

@github-actions

This comment has been minimized.

@rchiodo

Copy link
Copy Markdown
Collaborator Author

Core fix is correct, but it landed only in the pyright-internal copy. Pylance keeps a parallel async implementation that still has the old === '_' name guard, so the bug persists in async mode. Mirror the guard removal there and add Pylance-harness coverage for the non-_ separator under both sync and async modes.

@rchiodo

Copy link
Copy Markdown
Collaborator Author

The core fix is correct, but it was only applied to the pyright-internal copy of dataClasses.ts. Pylance's async copy (packages/pylance-internal/src/analyzer/dataClasses.ts) still has the old === '_' guard, so the bug persists in async mode and the sync/async paths diverge. Please mirror the guard removal there and add Pylance-harness coverage for the non-_ separator.

"dataClassConverterOverloads": "No overloads of \"{funcName}\" are valid converters for field \"{fieldName}\" of type \"{fieldType}\"",
"dataClassFieldInheritedDefault": "\"{fieldName}\" overrides a field of the same name but is missing a default value",
"dataClassDuplicateKwOnly": "\"{name}\" is a duplicate KW_ONLY separator; only one is allowed within a dataclass",
"dataClassFieldInheritedDefault":"\"{fieldName}\" overrides a field of the same name but is missing a default value",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📍 packages/pyright-internal/src/localization/package.nls.en-us.json:237
Prettier/JSON regression on the unrelated dataClassFieldInheritedDefault line: the space after the colon was dropped ("dataClassFieldInheritedDefault":"...) while every other entry uses ": ". This will fail npm run check. Restore the space and avoid touching this pre-existing line.

[verified]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. The regression came from editing the existing dataClassFieldInheritedDefault line to squeeze the new key in front of it. The incoming revision leaves that line untouched and adds dataClassDuplicateKwOnly as its own entry with the standard ": " spacing, so prettier -c passes on the file again.

variableNameNode
);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📍 packages/pyright-internal/src/analyzer/dataClasses.ts:382
This duplicate-KW_ONLY diagnostic is behaviorally correct (CPython raises the matching TypeError, and variableNameNode is provably non-null here), but it is a separate feature from #11451 — undisclosed in the title/description and added to the upstream-owned pyright subrepo, which should keep diffs surgical. Either split it into its own PR with an accurate description, or update this PR's description to document the new diagnostic, the new NLS key, the DC6 test, and the corrected error count.

[verified]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. I've updated the PR title and description to document the duplicate-KW_ONLY diagnostic, the new dataClassDuplicateKwOnly NLS key, the DC6 regression case, and the error-count bump. After rebasing onto main (where the #11451 name-guard fix already landed via #11486), this diagnostic is the PR's net-new contribution, which the description now makes explicit rather than framing the whole PR as the #11451 fix.

// Is this a KW_ONLY separator introduced in Python 3.10?
if (!isNamedTuple && statement.d.valueExpr.d.value === '_') {
// Is this a KW_ONLY separator introduced in Python 3.10? The
// separator is conventionally named "_", but the runtime recognizes

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📍 packages/pyright-internal/src/analyzer/dataClasses.ts:378
Stale diff base (verified): the core name-guard removal already exists in the pyright-internal working tree, so this hunk's - context line no longer exists and the patch will conflict on apply/rebase. Rebase onto current main; the net new contribution over the tree is essentially just the duplicate diagnostic, which makes the PR title's "#11451" framing misleading.

[verified]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rebasing onto current main. Since the name-guard removal already merged via #11486, I'm dropping that hunk entirely — the revised diff is just the duplicate-separator diagnostic plus the DC5 (non-_ separator name) and DC6 (duplicate separator) regression cases, so there's no longer a conflicting context line.

@heejaechang

Copy link
Copy Markdown
Collaborator

Main blocker: the fix only touches pyright-internal, but the Pylance async counterpart (packages/pylance-internal/src/analyzer/dataClasses.ts) still gates KW_ONLY on the field name being '_', so the bug still reproduces in Pylance's async path. Please port the name-agnostic recognition there with a Pylance-harness regression test. Also note the diff appears rebased on a stale base (the core fix already exists in the pyright-internal tree) and quietly adds an undisclosed duplicate-KW_ONLY diagnostic to the upstream subrepo.

@rchiodo Rich Chiodo (rchiodo) changed the title Fix #11451: KW_ONLY is only recognized when assigned to _ Report duplicate KW_ONLY separators in dataclasses Jun 29, 2026
@rchiodo

Copy link
Copy Markdown
Collaborator Author

Thanks for the review Heejae Chang (@heejaechang). Summary of how this revision addresses the feedback:

  • Stale base — Rebased onto current main. The KW_ONLY name-guard removal already merged via fix(dataClasses): recognize KW_ONLY separator for any variable name #11486, so that hunk is dropped; the remaining diff is just the new duplicate-separator diagnostic plus the DC5/DC6 regression cases.

  • Prettier/JSON regression — The new dataClassDuplicateKwOnly key is added as its own entry without touching the dataClassFieldInheritedDefault line, so the dropped-space change is gone and prettier -c passes.

  • Undisclosed feature — Title and description now document the duplicate-KW_ONLY diagnostic, the new NLS key, the DC6 test, and the 3 → 5 error-count change.

  • Pylance async path — This PR targets the standalone microsoft/pyright repo, which has no packages/pylance-internal (only pyright, pyright-internal, and vscode-pyright), so the async copy and its harness can't be modified here. The pylance-pyright-split guidance lives in the pyrx monorepo; the async-side guard removal and a regression covering both enableAsyncProgram=false/true belong there when this change is vendored in via the pyright subrepo. For this repo, dataclassKwOnly1.py (DC5 non-_ separator + DC6 duplicate separator) is the correct placement.

@heejaechang

Copy link
Copy Markdown
Collaborator

The core idea is correct, but the fix doesn't reach Pylance's async program path, and there's an unrelated formatting regression plus undisclosed scope (a new duplicate-KW_ONLY diagnostic in the upstream-owned pyright subrepo). Please port the fix to packages/pylance-internal, restore the dropped space in the NLS file, and update the description/scope before merge.

CPython raises a TypeError when more than one KW_ONLY separator appears in
a single dataclass. Detect this and emit a new dataClassDuplicateKwOnly
diagnostic on the second separator. Adds DC5 (non-_ separator name) and DC6
(duplicate separator) regression cases and bumps the expected error count.

The core KW_ONLY name-guard removal landed separately in microsoft#11486, so this is
rebased on top of it.

Co-authored-by: Copilot <[email protected]>
@heejaechang

Copy link
Copy Markdown
Collaborator

The pyright-internal change looks correct, but the equivalent fix is missing from Pylance's forked async analyzer (packages/pylance-internal/src/analyzer/dataClasses.ts), where the bug still reproduces. Please port the name-agnostic KW_ONLY recognition and duplicate detection there with a Pylance-harness regression test. The other candidate notes were false positives or already addressed by the PR description.

@github-actions

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

sympy (https://github.com/sympy/sympy)
-   .../projects/sympy/sympy/solvers/tests/test_solveset.py:445:30 - error: Cannot access attribute "limit_denominator" for class "NaN"
-     Attribute "limit_denominator" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/solvers/tests/test_solveset.py:445:30 - error: Cannot access attribute "limit_denominator" for class "ComplexInfinity"
-     Attribute "limit_denominator" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/stats/crv_types.py:2544:9 - error: Method "_cdf" overrides class "SingleContinuousDistribution" in an incompatible manner
-     Return type mismatch: base method returns type "None", override returns type "ComplexInfinity | NaN | Rational | Unknown"
-       Type "ComplexInfinity | NaN | Rational | Unknown" is not assignable to type "None"
-         "ComplexInfinity" is not assignable to "None" (reportIncompatibleMethodOverride)
-   .../projects/sympy/sympy/stats/crv_types.py:2723:9 - error: Method "_cdf" overrides class "SingleContinuousDistribution" in an incompatible manner
-     Return type mismatch: base method returns type "None", override returns type "Expr | NaN | ComplexInfinity | Rational | Unknown"
-       Type "Expr | NaN | ComplexInfinity | Rational | Unknown" is not assignable to type "None"
-         "Expr" is not assignable to "None" (reportIncompatibleMethodOverride)
-   .../projects/sympy/sympy/stats/frv_types.py:139:17 - error: Argument of type "NaN | ComplexInfinity | Rational | Unknown | Expr" cannot be assigned to parameter "value" of type "int" in function "__setitem__"
-     Type "NaN | ComplexInfinity | Rational | Unknown | Expr" is not assignable to type "int"
-       "Expr" is not assignable to "int" (reportArgumentType)
-   .../projects/sympy/sympy/stats/joint_rv_types.py:576:27 - error: Argument of type "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | Expr" cannot be assigned to parameter "stop" of type "SupportsIndex" in function "__new__"
+   .../projects/sympy/sympy/stats/joint_rv_types.py:576:27 - error: Argument of type "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Unknown | Infinity | NegativeInfinity | Float | Number | Expr" cannot be assigned to parameter "stop" of type "SupportsIndex" in function "__new__"
-     Type "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | Expr" is not assignable to type "SupportsIndex"
+     Type "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Unknown | Infinity | NegativeInfinity | Float | Number | Expr" is not assignable to type "SupportsIndex"
-   .../projects/sympy/sympy/stats/rv_interface.py:451:42 - error: Operator "-" not supported for types "Unknown | Basic | Any" and "Rational | NaN | ComplexInfinity"
+   .../projects/sympy/sympy/stats/rv_interface.py:451:42 - error: Operator "-" not supported for types "Unknown | Basic | Any" and "Rational | Unknown"
-     Operator "-" not supported for types "Basic" and "Rational"
-     Operator "-" not supported for types "Basic" and "NaN"
-     Operator "-" not supported for types "Basic" and "ComplexInfinity" (reportOperatorIssue)
+     Operator "-" not supported for types "Basic" and "Rational" (reportOperatorIssue)
-   .../projects/sympy/sympy/stats/tests/test_finite_rv.py:35:23 - error: Operator "/" not supported for types "Unknown | Any | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Expr | tuple[Unknown, ...] | MatMul | Infinity | NegativeInfinity | int" and "Unknown | Any | BernoulliDistribution | Probability | Zero | One | tuple[Unknown, ...] | Sum | Expr | ZeroMatrix | NaN | Piecewise | Basic | ComplexInfinity | Float | Infinity | Integer | Lambda | Mul | NegativeInfinity | NegativeOne | Number | Rational | Integral | Literal[0]"
+   .../projects/sympy/sympy/stats/tests/test_finite_rv.py:35:23 - error: Operator "/" not supported for types "Unknown | Any | One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Expr | Infinity | NegativeInfinity | Float | NotImplementedType | tuple[Unknown, ...] | MatMul | int" and "Unknown | Any | BernoulliDistribution | Probability | Zero | One | tuple[Unknown, ...] | Sum | Expr | ZeroMatrix | NaN | Piecewise | Basic | ComplexInfinity | Float | Infinity | Integer | Lambda | Mul | NegativeInfinity | NegativeOne | Number | Rational | Integral | Literal[0]"
-   .../projects/sympy/sympy/stats/tests/test_finite_rv.py:248:19 - error: Argument of type "Rational | NaN | ComplexInfinity" cannot be assigned to parameter "p" of type "Half" in function "Coin"
+   .../projects/sympy/sympy/stats/tests/test_finite_rv.py:248:19 - error: Argument of type "Rational | Unknown" cannot be assigned to parameter "p" of type "Half" in function "Coin"
-     Type "Rational | NaN | ComplexInfinity" is not assignable to type "Half"
+     Type "Rational | Unknown" is not assignable to type "Half"
-       "ComplexInfinity" is not assignable to "Half" (reportArgumentType)
+       "Rational" is not assignable to "Half" (reportArgumentType)
+   .../projects/sympy/sympy/tensor/array/expressions/from_array_to_matrix.py:402:32 - error: Cannot access attribute "shape" for class "Infinity"
+     Attribute "shape" is unknown (reportAttributeAccessIssue)
+   .../projects/sympy/sympy/tensor/array/expressions/from_array_to_matrix.py:402:32 - error: Cannot access attribute "shape" for class "NegativeInfinity"
+     Attribute "shape" is unknown (reportAttributeAccessIssue)
+   .../projects/sympy/sympy/tensor/array/expressions/from_array_to_matrix.py:402:32 - error: Cannot access attribute "shape" for class "Float"
+     Attribute "shape" is unknown (reportAttributeAccessIssue)
+   .../projects/sympy/sympy/tensor/array/expressions/from_array_to_matrix.py:428:25 - error: Cannot access attribute "shape" for class "Infinity"
+     Attribute "shape" is unknown (reportAttributeAccessIssue)
+   .../projects/sympy/sympy/tensor/array/expressions/from_array_to_matrix.py:428:25 - error: Cannot access attribute "shape" for class "NegativeInfinity"
+     Attribute "shape" is unknown (reportAttributeAccessIssue)
+   .../projects/sympy/sympy/tensor/array/expressions/from_array_to_matrix.py:428:25 - error: Cannot access attribute "shape" for class "Float"
+     Attribute "shape" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/tensor/array/expressions/from_array_to_matrix.py:438:31 - error: Operator "*" not supported for types "Zero | ZeroArray | Unknown | ArrayContraction | Basic | PermuteDims | Any | Transpose | One | NegativeOne | Integer | NaN | ComplexInfinity | Rational | Expr | MatMul" and "Zero | ZeroArray | Unknown | ArrayContraction | Basic | PermuteDims | Any | Transpose | MatrixExpr"
+   .../projects/sympy/sympy/tensor/array/expressions/from_array_to_matrix.py:438:31 - error: Operator "*" not supported for types "Zero | ZeroArray | Unknown | ArrayContraction | Basic | PermuteDims | Any | Transpose | One | NegativeOne | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | NotImplementedType | Expr | MatMul" and "Zero | ZeroArray | Unknown | ArrayContraction | Basic | PermuteDims | Any | Transpose | MatrixExpr"
-     Return type mismatch: base method returns type "tuple[tuple[int, int, str], tuple[int, tuple[Unknown, ...]], tuple[tuple[Literal[1], Literal[0], Literal['Number']], tuple[int, tuple[()]], tuple[()], Self@Number], One]", override returns type "tuple[tuple[int, int, str], tuple[int, tuple[str, ...]], tuple[tuple[Literal[1], Literal[0], Literal['Number']], tuple[int, tuple[()]], tuple[()], One] | Unknown, Number]"
+     Return type mismatch: base method returns type "tuple[tuple[int, int, str], tuple[int, tuple[tuple[tuple[int, int, str], tuple[int, tuple[Unknown, ...]], tuple[tuple[Literal[1], Literal[0], Literal['Number']], tuple[int, tuple[()]], tuple[()], One], One], ...]], tuple[tuple[Literal[1], Literal[0], Literal['Number']], tuple[int, tuple[()]], tuple[()], One], One]", override returns type "tuple[tuple[int, int, str], tuple[int, tuple[str, ...]], tuple[tuple[Literal[1], Literal[0], Literal['Number']], tuple[int, tuple[()]], tuple[()], One] | Unknown, Number]"
-       "tuple[tuple[int, int, str], tuple[int, tuple[str, ...]], tuple[tuple[Literal[1], Literal[0], Literal['Number']], tuple[int, tuple[()]], tuple[()], One] | Unknown, Number]" is not assignable to "tuple[tuple[int, int, str], tuple[int, tuple[Unknown, ...]], tuple[tuple[Literal[1], Literal[0], Literal['Number']], tuple[int, tuple[()]], tuple[()], Self@Number], One]"
+       "tuple[tuple[int, int, str], tuple[int, tuple[str, ...]], tuple[tuple[Literal[1], Literal[0], Literal['Number']], tuple[int, tuple[()]], tuple[()], One] | Unknown, Number]" is not assignable to "tuple[tuple[int, int, str], tuple[int, tuple[tuple[tuple[int, int, str], tuple[int, tuple[Unknown, ...]], tuple[tuple[Literal[1], Literal[0], Literal['Number']], tuple[int, tuple[()]], tuple[()], One], One], ...]], tuple[tuple[Literal[1], Literal[0], Literal['Number']], tuple[int, tuple[()]], tuple[()], One], One]"
-         Tuple entry 4 is incorrect type
+         Tuple entry 2 is incorrect type
-           "Number" is not assignable to "One" (reportIncompatibleMethodOverride)
+           "tuple[int, tuple[str, ...]]" is not assignable to "tuple[int, tuple[tuple[tuple[int, int, str], tuple[int, tuple[Unknown, ...]], tuple[tuple[Literal[1], Literal[0], Literal['Number']], tuple[int, tuple[()]], tuple[()], One], One], ...]]"
+             Tuple entry 2 is incorrect type (reportIncompatibleMethodOverride)

... (truncated 520 lines) ...

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved via Review Center.

@rchiodo
Rich Chiodo (rchiodo) merged commit 035fa62 into microsoft:main Jun 29, 2026
15 of 16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants