Added a new typeCheckingMode called "standard". It's a subset of "strict" but a superset of "basic". It is the new default mode, and it should cover all of the required checks for conformance with the Python typing standard. This addresses #66607. (#6627)

This commit is contained in:
Eric Traut 2023-12-01 23:44:12 -08:00 committed by GitHub
parent f82a594102
commit f605c8fb24
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
39 changed files with 255 additions and 120 deletions

View File

@ -36,7 +36,7 @@ Relative paths specified within the config file are relative to the config file
**executionEnvironments** [array of objects, optional]: Specifies a list of execution environments (see [below](configuration.md#execution-environment-options)). Execution environments are searched from start to finish by comparing the path of a source file with the root path specified in the execution environment.
**typeCheckingMode** ["off", "basic", "strict"]: Specifies the default rule set to use. Some rules can be overridden using additional configuration flags documented below. The default value for this setting is "basic". If set to "off", all type-checking rules are disabled, but Python syntax and semantic errors are still reported.
**typeCheckingMode** ["off", "basic", "standard", "strict"]: Specifies the default rule set to use. Some rules can be overridden using additional configuration flags documented below. The default value for this setting is "standard". If set to "off", all type-checking rules are disabled, but Python syntax and semantic errors are still reported.
**useLibraryCodeForTypes** [boolean]: Determines whether pyright reads, parses and analyzes library code to extract type information in the absence of type stub files. Type information will typically be incomplete. We recommend using type stubs where possible. The default value for this option is true.
@ -66,7 +66,7 @@ The following settings control pyrights diagnostic output (warnings or errors
<a name="reportPropertyTypeMismatch"></a> **reportPropertyTypeMismatch** [boolean or string, optional]: Generate or suppress diagnostics for properties where the type of the value passed to the setter is not assignable to the value returned by the getter. Such mismatches violate the intended use of properties, which are meant to act like variables. The default value for this setting is `"none"`.
<a name="reportFunctionMemberAccess"></a> **reportFunctionMemberAccess** [boolean or string, optional]: Generate or suppress diagnostics for non-standard member accesses for functions. The default value for this setting is `"none"`.
<a name="reportFunctionMemberAccess"></a> **reportFunctionMemberAccess** [boolean or string, optional]: Generate or suppress diagnostics for non-standard member accesses for functions. The default value for this setting is `"error"`.
<a name="reportMissingImports"></a> **reportMissingImports** [boolean or string, optional]: Generate or suppress diagnostics for imports that have no corresponding imported python file or type stub file. The default value for this setting is `"error"`.
@ -120,13 +120,13 @@ The following settings control pyrights diagnostic output (warnings or errors
<a name="reportDeprecated"></a> **reportDeprecated** [boolean or string, optional]: Generate or suppress diagnostics for use of a class or function that has been marked as deprecated. The default value for this setting is `"none"`.
<a name="reportIncompatibleMethodOverride"></a> **reportIncompatibleMethodOverride** [boolean or string, optional]: Generate or suppress diagnostics for methods that override a method of the same name in a base class in an incompatible manner (wrong number of parameters, incompatible parameter types, or incompatible return type). The default value for this setting is `"none"`.
<a name="reportIncompatibleMethodOverride"></a> **reportIncompatibleMethodOverride** [boolean or string, optional]: Generate or suppress diagnostics for methods that override a method of the same name in a base class in an incompatible manner (wrong number of parameters, incompatible parameter types, or incompatible return type). The default value for this setting is `"error"`.
<a name="reportIncompatibleVariableOverride"></a> **reportIncompatibleVariableOverride** [boolean or string, optional]: Generate or suppress diagnostics for class variable declarations that override a symbol of the same name in a base class with a type that is incompatible with the base class symbol type. The default value for this setting is `"none"`.
<a name="reportIncompatibleVariableOverride"></a> **reportIncompatibleVariableOverride** [boolean or string, optional]: Generate or suppress diagnostics for class variable declarations that override a symbol of the same name in a base class with a type that is incompatible with the base class symbol type. The default value for this setting is `"error"`.
<a name="reportInconsistentConstructor"></a> **reportInconsistentConstructor** [boolean or string, optional]: Generate or suppress diagnostics when an `__init__` method signature is inconsistent with a `__new__` signature. The default value for this setting is `"none"`.
<a name="reportOverlappingOverload"></a> **reportOverlappingOverload** [boolean or string, optional]: Generate or suppress diagnostics for function overloads that overlap in signature and obscure each other or have incompatible return types. The default value for this setting is `"none"`.
<a name="reportOverlappingOverload"></a> **reportOverlappingOverload** [boolean or string, optional]: Generate or suppress diagnostics for function overloads that overlap in signature and obscure each other or have incompatible return types. The default value for this setting is `"error"`.
<a name="reportMissingSuperCall"></a> **reportMissingSuperCall** [boolean or string, optional]: Generate or suppress diagnostics for `__init__`, `__init_subclass__`, `__enter__` and `__exit__` methods in a subclass that fail to call through to the same-named method on a base class. The default value for this setting is `"none"`.
@ -298,78 +298,78 @@ Each diagnostic rule has a default severity level that is dictated by the specif
The following table lists the default severity levels for each diagnostic rule within each type checking mode (`"off"`, `"basic"` and `"strict"`).
| Diagnostic Rule | Off | Basic | Strict |
| :---------------------------------------- | :--------- | :--------- | :--------- |
| analyzeUnannotatedFunctions | true | true | true |
| strictParameterNoneValue | true | true | true |
| enableTypeIgnoreComments | true | true | true |
| disableBytesTypePromotions | false | false | true |
| strictListInference | false | false | true |
| strictDictionaryInference | false | false | true |
| strictSetInference | false | false | true |
| deprecateTypingAliases | false | false | false |
| enableExperimentalFeatures | false | false | false |
| reportMissingModuleSource | "warning" | "warning" | "warning" |
| reportMissingImports | "warning" | "error" | "error" |
| reportUndefinedVariable | "warning" | "error" | "error" |
| reportAssertAlwaysTrue | "none" | "warning" | "error" |
| reportInvalidStringEscapeSequence | "none" | "warning" | "error" |
| reportInvalidTypeVarUse | "none" | "warning" | "error" |
| reportMissingTypeStubs | "none" | "warning" | "error" |
| reportSelfClsParameterName | "none" | "warning" | "error" |
| reportUnsupportedDunderAll | "none" | "warning" | "error" |
| reportUnusedExpression | "none" | "warning" | "error" |
| reportWildcardImportFromLibrary | "none" | "warning" | "error" |
| reportGeneralTypeIssues | "none" | "error" | "error" |
| reportOptionalSubscript | "none" | "error" | "error" |
| reportOptionalMemberAccess | "none" | "error" | "error" |
| reportOptionalCall | "none" | "error" | "error" |
| reportOptionalIterable | "none" | "error" | "error" |
| reportOptionalContextManager | "none" | "error" | "error" |
| reportOptionalOperand | "none" | "error" | "error" |
| reportTypedDictNotRequiredAccess | "none" | "error" | "error" |
| reportPrivateImportUsage | "none" | "error" | "error" |
| reportUnboundVariable | "none" | "error" | "error" |
| reportUnusedCoroutine | "none" | "error" | "error" |
| reportConstantRedefinition | "none" | "none" | "error" |
| reportDeprecated | "none" | "none" | "error" |
| reportDuplicateImport | "none" | "none" | "error" |
| reportFunctionMemberAccess | "none" | "none" | "error" |
| reportIncompatibleMethodOverride | "none" | "none" | "error" |
| reportIncompatibleVariableOverride | "none" | "none" | "error" |
| reportIncompleteStub | "none" | "none" | "error" |
| reportInconsistentConstructor | "none" | "none" | "error" |
| reportInvalidStubStatement | "none" | "none" | "error" |
| reportMatchNotExhaustive | "none" | "none" | "error" |
| reportMissingParameterType | "none" | "none" | "error" |
| reportMissingTypeArgument | "none" | "none" | "error" |
| reportOverlappingOverload | "none" | "none" | "error" |
| reportPrivateUsage | "none" | "none" | "error" |
| reportTypeCommentUsage | "none" | "none" | "error" |
| reportUnknownArgumentType | "none" | "none" | "error" |
| reportUnknownLambdaType | "none" | "none" | "error" |
| reportUnknownMemberType | "none" | "none" | "error" |
| reportUnknownParameterType | "none" | "none" | "error" |
| reportUnknownVariableType | "none" | "none" | "error" |
| reportUnnecessaryCast | "none" | "none" | "error" |
| reportUnnecessaryComparison | "none" | "none" | "error" |
| reportUnnecessaryContains | "none" | "none" | "error" |
| reportUnnecessaryIsInstance | "none" | "none" | "error" |
| reportUnusedClass | "none" | "none" | "error" |
| reportUnusedImport | "none" | "none" | "error" |
| reportUnusedFunction | "none" | "none" | "error" |
| reportUnusedVariable | "none" | "none" | "error" |
| reportUntypedBaseClass | "none" | "none" | "error" |
| reportUntypedClassDecorator | "none" | "none" | "error" |
| reportUntypedFunctionDecorator | "none" | "none" | "error" |
| reportUntypedNamedTuple | "none" | "none" | "error" |
| reportCallInDefaultInitializer | "none" | "none" | "none" |
| reportImplicitOverride | "none" | "none" | "none" |
| reportImplicitStringConcatenation | "none" | "none" | "none" |
| reportImportCycles | "none" | "none" | "none" |
| reportMissingSuperCall | "none" | "none" | "none" |
| reportPropertyTypeMismatch | "none" | "none" | "none" |
| reportShadowedImports | "none" | "none" | "none" |
| reportUninitializedInstanceVariable | "none" | "none" | "none" |
| reportUnnecessaryTypeIgnoreComment | "none" | "none" | "none" |
| reportUnusedCallResult | "none" | "none" | "none" |
| Diagnostic Rule | Off | Basic | Standard | Strict |
| :---------------------------------------- | :--------- | :--------- | :--------- | :--------- |
| analyzeUnannotatedFunctions | true | true | true | true |
| strictParameterNoneValue | true | true | true | true |
| enableTypeIgnoreComments | true | true | true | true |
| disableBytesTypePromotions | false | false | false | true |
| strictListInference | false | false | false | true |
| strictDictionaryInference | false | false | false | true |
| strictSetInference | false | false | false | true |
| deprecateTypingAliases | false | false | false | false |
| enableExperimentalFeatures | false | false | false | false |
| reportMissingModuleSource | "warning" | "warning" | "warning" | "warning" |
| reportMissingImports | "warning" | "error" | "error" | "error" |
| reportUndefinedVariable | "warning" | "error" | "error" | "error" |
| reportAssertAlwaysTrue | "none" | "warning" | "warning" | "error" |
| reportInvalidStringEscapeSequence | "none" | "warning" | "warning" | "error" |
| reportInvalidTypeVarUse | "none" | "warning" | "warning" | "error" |
| reportMissingTypeStubs | "none" | "warning" | "warning" | "error" |
| reportSelfClsParameterName | "none" | "warning" | "warning" | "error" |
| reportUnsupportedDunderAll | "none" | "warning" | "warning" | "error" |
| reportUnusedExpression | "none" | "warning" | "warning" | "error" |
| reportWildcardImportFromLibrary | "none" | "warning" | "warning" | "error" |
| reportGeneralTypeIssues | "none" | "error" | "error" | "error" |
| reportOptionalSubscript | "none" | "error" | "error" | "error" |
| reportOptionalMemberAccess | "none" | "error" | "error" | "error" |
| reportOptionalCall | "none" | "error" | "error" | "error" |
| reportOptionalIterable | "none" | "error" | "error" | "error" |
| reportOptionalContextManager | "none" | "error" | "error" | "error" |
| reportOptionalOperand | "none" | "error" | "error" | "error" |
| reportTypedDictNotRequiredAccess | "none" | "error" | "error" | "error" |
| reportPrivateImportUsage | "none" | "error" | "error" | "error" |
| reportUnboundVariable | "none" | "error" | "error" | "error" |
| reportUnusedCoroutine | "none" | "error" | "error" | "error" |
| reportFunctionMemberAccess | "none" | "none" | "error" | "error" |
| reportIncompatibleMethodOverride | "none" | "none" | "error" | "error" |
| reportIncompatibleVariableOverride | "none" | "none" | "error" | "error" |
| reportOverlappingOverload | "none" | "none" | "error" | "error" |
| reportConstantRedefinition | "none" | "none" | "none" | "error" |
| reportDeprecated | "none" | "none" | "none" | "error" |
| reportDuplicateImport | "none" | "none" | "none" | "error" |
| reportIncompleteStub | "none" | "none" | "none" | "error" |
| reportInconsistentConstructor | "none" | "none" | "none" | "error" |
| reportInvalidStubStatement | "none" | "none" | "none" | "error" |
| reportMatchNotExhaustive | "none" | "none" | "none" | "error" |
| reportMissingParameterType | "none" | "none" | "none" | "error" |
| reportMissingTypeArgument | "none" | "none" | "none" | "error" |
| reportPrivateUsage | "none" | "none" | "none" | "error" |
| reportTypeCommentUsage | "none" | "none" | "none" | "error" |
| reportUnknownArgumentType | "none" | "none" | "none" | "error" |
| reportUnknownLambdaType | "none" | "none" | "none" | "error" |
| reportUnknownMemberType | "none" | "none" | "none" | "error" |
| reportUnknownParameterType | "none" | "none" | "none" | "error" |
| reportUnknownVariableType | "none" | "none" | "none" | "error" |
| reportUnnecessaryCast | "none" | "none" | "none" | "error" |
| reportUnnecessaryComparison | "none" | "none" | "none" | "error" |
| reportUnnecessaryContains | "none" | "none" | "none" | "error" |
| reportUnnecessaryIsInstance | "none" | "none" | "none" | "error" |
| reportUnusedClass | "none" | "none" | "none" | "error" |
| reportUnusedImport | "none" | "none" | "none" | "error" |
| reportUnusedFunction | "none" | "none" | "none" | "error" |
| reportUnusedVariable | "none" | "none" | "none" | "error" |
| reportUntypedBaseClass | "none" | "none" | "none" | "error" |
| reportUntypedClassDecorator | "none" | "none" | "none" | "error" |
| reportUntypedFunctionDecorator | "none" | "none" | "none" | "error" |
| reportUntypedNamedTuple | "none" | "none" | "none" | "error" |
| reportCallInDefaultInitializer | "none" | "none" | "none" | "none" |
| reportImplicitOverride | "none" | "none" | "none" | "none" |
| reportImplicitStringConcatenation | "none" | "none" | "none" | "none" |
| reportImportCycles | "none" | "none" | "none" | "none" |
| reportMissingSuperCall | "none" | "none" | "none" | "none" |
| reportPropertyTypeMismatch | "none" | "none" | "none" | "none" |
| reportShadowedImports | "none" | "none" | "none" | "none" |
| reportUninitializedInstanceVariable | "none" | "none" | "none" | "none" |
| reportUnnecessaryTypeIgnoreComment | "none" | "none" | "none" | "none" |
| reportUnusedCallResult | "none" | "none" | "none" | "none" |

View File

@ -30,7 +30,7 @@ The Pyright language server honors the following settings.
**python.analysis.stubPath** [path]: Path to directory containing custom type stub files.
**python.analysis.typeCheckingMode** ["off", "basic", "strict"]: Determines the default type-checking level used by pyright. This can be overridden in the configuration file. (Note: This setting used to be called "pyright.typeCheckingMode". The old name is deprecated but is still currently honored.)
**python.analysis.typeCheckingMode** ["off", "basic", "standard", "strict"]: Determines the default type-checking level used by pyright. This can be overridden in the configuration file. (Note: This setting used to be called "pyright.typeCheckingMode". The old name is deprecated but is still currently honored.)
**python.analysis.typeshedPaths** [array of paths]: Paths to look for typeshed modules. Pyright currently honors only the first path in the array.

View File

@ -15,6 +15,7 @@ import {
getBasicDiagnosticRuleSet,
getBooleanDiagnosticRules,
getDiagLevelDiagnosticRules,
getStandardDiagnosticRuleSet,
getStrictDiagnosticRuleSet,
getStrictModeNotOverriddenRules,
} from '../common/configOptions';
@ -28,6 +29,7 @@ import { Localizer } from '../localization/localize';
import { Token } from '../parser/tokenizerTypes';
const strictSetting = 'strict';
const standardSetting = 'standard';
const basicSetting = 'basic';
export interface CommentDiagnostic {
@ -74,6 +76,10 @@ function _applyStrictRules(ruleSet: DiagnosticRuleSet) {
_overrideRules(ruleSet, getStrictDiagnosticRuleSet(), getStrictModeNotOverriddenRules());
}
function _applyStandardRules(ruleSet: DiagnosticRuleSet) {
_overwriteRules(ruleSet, getStandardDiagnosticRuleSet());
}
function _applyBasicRules(ruleSet: DiagnosticRuleSet) {
_overwriteRules(ruleSet, getBasicDiagnosticRuleSet());
}
@ -163,6 +169,8 @@ function _parsePyrightComment(
// diagnostic rules with their strict counterparts.
if (operandList.some((s) => s.trim() === strictSetting)) {
_applyStrictRules(ruleSet);
} else if (operandList.some((s) => s.trim() === standardSetting)) {
_applyStandardRules(ruleSet);
} else if (operandList.some((s) => s.trim() === basicSetting)) {
_applyBasicRules(ruleSet);
}

View File

@ -115,7 +115,7 @@ export class CommandLineOptions {
extraPaths?: string[] | undefined;
// Default type-checking rule set. Should be one of 'off',
// 'basic', or 'strict'.
// 'basic', 'standard', or 'strict'.
typeCheckingMode?: string | undefined;
// Indicates that the settings came from VS Code rather than

View File

@ -610,6 +610,91 @@ export function getBasicDiagnosticRuleSet(): DiagnosticRuleSet {
return diagSettings;
}
export function getStandardDiagnosticRuleSet(): DiagnosticRuleSet {
const diagSettings: DiagnosticRuleSet = {
printUnknownAsAny: false,
omitTypeArgsIfUnknown: false,
omitUnannotatedParamType: true,
omitConditionalConstraint: false,
pep604Printing: true,
strictListInference: false,
strictSetInference: false,
strictDictionaryInference: false,
analyzeUnannotatedFunctions: true,
strictParameterNoneValue: true,
enableExperimentalFeatures: false,
enableTypeIgnoreComments: true,
deprecateTypingAliases: false,
disableBytesTypePromotions: false,
reportGeneralTypeIssues: 'error',
reportPropertyTypeMismatch: 'none',
reportFunctionMemberAccess: 'error',
reportMissingImports: 'error',
reportMissingModuleSource: 'warning',
reportMissingTypeStubs: 'none',
reportImportCycles: 'none',
reportUnusedImport: 'none',
reportUnusedClass: 'none',
reportUnusedFunction: 'none',
reportUnusedVariable: 'none',
reportDuplicateImport: 'none',
reportWildcardImportFromLibrary: 'warning',
reportOptionalSubscript: 'error',
reportOptionalMemberAccess: 'error',
reportOptionalCall: 'error',
reportOptionalIterable: 'error',
reportOptionalContextManager: 'error',
reportOptionalOperand: 'error',
reportTypedDictNotRequiredAccess: 'error',
reportUntypedFunctionDecorator: 'none',
reportUntypedClassDecorator: 'none',
reportUntypedBaseClass: 'none',
reportUntypedNamedTuple: 'none',
reportPrivateUsage: 'none',
reportTypeCommentUsage: 'none',
reportPrivateImportUsage: 'error',
reportConstantRedefinition: 'none',
reportDeprecated: 'none',
reportIncompatibleMethodOverride: 'error',
reportIncompatibleVariableOverride: 'error',
reportInconsistentConstructor: 'none',
reportOverlappingOverload: 'error',
reportMissingSuperCall: 'none',
reportUninitializedInstanceVariable: 'none',
reportInvalidStringEscapeSequence: 'warning',
reportUnknownParameterType: 'none',
reportUnknownArgumentType: 'none',
reportUnknownLambdaType: 'none',
reportUnknownVariableType: 'none',
reportUnknownMemberType: 'none',
reportMissingParameterType: 'none',
reportMissingTypeArgument: 'none',
reportInvalidTypeVarUse: 'warning',
reportCallInDefaultInitializer: 'none',
reportUnnecessaryIsInstance: 'none',
reportUnnecessaryCast: 'none',
reportUnnecessaryComparison: 'none',
reportUnnecessaryContains: 'none',
reportAssertAlwaysTrue: 'warning',
reportSelfClsParameterName: 'warning',
reportImplicitStringConcatenation: 'none',
reportUnboundVariable: 'error',
reportUndefinedVariable: 'error',
reportInvalidStubStatement: 'none',
reportIncompleteStub: 'none',
reportUnsupportedDunderAll: 'warning',
reportUnusedCallResult: 'none',
reportUnusedCoroutine: 'error',
reportUnusedExpression: 'warning',
reportUnnecessaryTypeIgnoreComment: 'none',
reportMatchNotExhaustive: 'none',
reportShadowedImports: 'none',
reportImplicitOverride: 'none',
};
return diagSettings;
}
export function getStrictDiagnosticRuleSet(): DiagnosticRuleSet {
const diagSettings: DiagnosticRuleSet = {
printUnknownAsAny: false,
@ -844,11 +929,15 @@ export class ConfigOptions {
return getStrictDiagnosticRuleSet();
}
if (typeCheckingMode === 'basic') {
return getBasicDiagnosticRuleSet();
}
if (typeCheckingMode === 'off') {
return getOffDiagnosticRuleSet();
}
return getBasicDiagnosticRuleSet();
return getStandardDiagnosticRuleSet();
}
getDefaultExecEnvironment(): ExecutionEnvironment {
@ -977,11 +1066,12 @@ export class ConfigOptions {
if (
configObj.typeCheckingMode === 'off' ||
configObj.typeCheckingMode === 'basic' ||
configObj.typeCheckingMode === 'standard' ||
configObj.typeCheckingMode === 'strict'
) {
configTypeCheckingMode = configObj.typeCheckingMode;
} else {
console.error(`Config "typeCheckingMode" entry must contain "off", "basic", or "strict".`);
console.error(`Config "typeCheckingMode" entry must contain "off", "basic", "standard", or "strict".`);
}
}

View File

@ -90,7 +90,7 @@ export class PyrightServer extends LanguageServerBase {
useLibraryCodeForTypes: true,
disableLanguageServices: false,
disableOrganizeImports: false,
typeCheckingMode: 'basic',
typeCheckingMode: 'standard',
diagnosticSeverityOverrides: {},
logLevel: LogLevel.Info,
autoImportCompletions: true,

View File

@ -182,7 +182,7 @@ export class TestState {
const configOptions = this._convertGlobalOptionsToConfigOptions(vfsInfo.projectRoot, mountPaths);
if (this.rawConfigJson) {
configOptions.initializeFromJson(this.rawConfigJson, 'basic', this.serviceProvider, testAccessHost);
configOptions.initializeFromJson(this.rawConfigJson, 'standard', this.serviceProvider, testAccessHost);
this._applyTestConfigOptions(configOptions);
}

View File

@ -1,5 +1,7 @@
# This sample tests that named tuple fields override abstract methods.
# pyright: reportIncompatibleVariableOverride=false
from abc import ABC, abstractmethod
from typing import NamedTuple

View File

@ -8,7 +8,7 @@ class DC1:
bbb: int
ccc: str
aaa: str = "string"
__hash__: None
__hash__: None # pyright: ignore[reportIncompatibleMethodOverride]
bar1 = DC1(bbb=5, ccc="hello")

View File

@ -1,6 +1,8 @@
# This sample tests the case where a dataclass declares an instance
# variable and a subclass redeclares it as a class variable.
# pyright: reportIncompatibleVariableOverride=false
from dataclasses import dataclass
from typing import ClassVar

View File

@ -1,6 +1,8 @@
# This sample tests the analyzer's ability to handle inherited
# data classes.
# pyright: reportIncompatibleVariableOverride=false
from dataclasses import dataclass, field

View File

@ -1,6 +1,8 @@
# This sample tests the handling of the @dataclass decorator
# with a custom __init__.
# pyright: reportIncompatibleMethodOverride=false
from dataclasses import dataclass

View File

@ -1,5 +1,7 @@
# This sample tests the __post_init__ validation logic.
# pyright: reportIncompatibleMethodOverride=false
from dataclasses import InitVar, dataclass, field
from typing import Iterable

View File

@ -1,6 +1,8 @@
# This sample tests the a class-based decorator that uses a
# __get__ method as a way to provide access to a __call__ method.
# pyright: reportIncompatibleMethodOverride=false
class Wrapper:
def __init__(self, func):

View File

@ -51,4 +51,4 @@ class EnumWithValue(EnumWithoutValue):
# This should generate an error because enums with values
# cannot be subclassed.
class EnumSubclass(EnumWithValue):
y: int
z: int

View File

@ -11,6 +11,7 @@ reveal_type(EnumA.x.value, expected_text="int")
class EnumC(str, Enum):
@staticmethod
def _generate_next_value_(name, start, count, last_values) -> str:
return name

View File

@ -1,6 +1,8 @@
# This sample tests that a Generic base class overrides the type parameter
# ordering of other type parameters.
# pyright: reportIncompatibleMethodOverride=false
from typing import Generic, Iterable, Iterator, Mapping, TypeVar
_T1 = TypeVar("_T1")
@ -23,6 +25,7 @@ class Foo(Iterable[_T2], Generic[_T1, _T2]):
a: Foo[int, str] = Foo(2, "")
b: str = a.foo(4, "")
# This should generate an error because a class shouldn't
# derive from Generic more than once.
class Bar(Generic[_T1], Generic[_T2]):
@ -32,6 +35,7 @@ class Bar(Generic[_T1], Generic[_T2]):
K = TypeVar("K")
V = TypeVar("V")
# This should generate an error because V isn't included
# in the Generic type variable list.
class A(Mapping[K, V], Generic[K]):

View File

@ -1,6 +1,8 @@
# This sample tests the check for hashability that applies to entries
# within a set expression and keys within a dictionary expression.
# pyright: reportIncompatibleVariableOverride=false
from dataclasses import dataclass
from typing import Any

View File

@ -1,5 +1,7 @@
# This sample tests that unhashable user classes are detected as unhashable.
# pyright: reportIncompatibleMethodOverride=false
class A:
...

View File

@ -6,6 +6,8 @@ from enum import Enum, auto
from typing import Annotated, TypeVar
from http import HTTPStatus
# pyright: reportIncompatibleMethodOverride=false
def handle_reply(reply: tuple[HTTPStatus, str] | tuple[HTTPStatus]):
match reply:

View File

@ -1,6 +1,8 @@
# This sample tests the handling of metaclass magic methods for
# binary operators.
# pyright: reportIncompatibleMethodOverride=false
class MetaA(type):
def __eq__(self, a: "type[ClassA]") -> str:

View File

@ -2,6 +2,8 @@
# __call__ method, thus overriding the __new__ method on classes
# that are created from it.
# pyright: reportIncompatibleMethodOverride=false
class MetaClass1(type):
def __call__(cls, **kwargs):

View File

@ -1,6 +1,8 @@
# This sample tests the type checker's handling
# of proper method resolution order (MRO).
# pyright: reportIncompatibleMethodOverride=false
class A:
def foo(self, v1: str):

View File

@ -1,6 +1,7 @@
# This sample tests the type checker's ability to check
# custom operator overrides.
# pyright: reportIncompatibleMethodOverride=false
from typing import NoReturn, Self

View File

@ -1,6 +1,8 @@
# This sample verifies that the reportOptionalOperand diagnostic
# isn't generated when the RHS operand accepts None.
# pyright: reportIncompatibleMethodOverride=false
from typing import Optional

View File

@ -164,7 +164,7 @@ def func7(cls: type[_T2], var: int | str) -> _T2:
return cls()
_T3 = TypeVar("_T3")
_T3 = TypeVar("_T3", bound=str)
@overload

View File

@ -1,6 +1,7 @@
# This sample tests the logic that infers parameter types based on
# annotated base class methods when the base class is generic.
# pyright: reportIncompatibleMethodOverride=false
from typing import Generic, TypeVar

View File

@ -43,7 +43,7 @@ class Class1:
@overload
# This should generate an error or warning if the setting
# is enabled because "self" is expected.
def foo6(x: "Class1") -> str:
def foo6(x: int) -> str:
...
# This should generate an error or warning if the setting

View File

@ -2,6 +2,8 @@
# is used as an input parameter to a function that returns a generic
# type parameterized by a ParamSpec and specialized with a Concatenate.
# pyright: reportOverlappingOverload=false
from __future__ import annotations
from typing_extensions import Self, Concatenate, ParamSpec
from typing import Any, Callable, TypeVar, Protocol, Generic, overload

View File

@ -1,6 +1,8 @@
# This sample tests the case where a property's getter and setter
# are defined in different classes.
# pyright: reportIncompatibleMethodOverride=false
from typing import Generic, Self, TypeVar

View File

@ -13,14 +13,14 @@ class SupportsIndex(Protocol):
class TupleLike(Sequence[_T_co]):
@overload
def __getitem__(self, __x: SupportsIndex) -> _T_co:
def __getitem__(self, index: SupportsIndex) -> _T_co:
...
@overload
def __getitem__(self, __x: slice) -> "TupleLike[_T_co]":
def __getitem__(self, index: slice) -> "TupleLike[_T_co]":
...
def __getitem__(self, __x: slice | SupportsIndex) -> "_T_co | TupleLike[_T_co]":
def __getitem__(self, index: slice | SupportsIndex) -> "_T_co | TupleLike[_T_co]":
...

View File

@ -21,7 +21,7 @@ class Ungulate(Mammal[_T3], Protocol):
class CamelLike(Ungulate[bytes], Protocol):
species: Literal["camel"]
species: Literal["camel"] # pyright: ignore[reportIncompatibleVariableOverride]
class Sloth:

View File

@ -2,6 +2,7 @@
# is supported for classes that have a custom metaclass
# with a __or__ or __ror__ method defined.
# pyright: reportIncompatibleMethodOverride=false
from typing import Type, TypeVar

View File

@ -20,11 +20,11 @@ _T = TypeVar("_T")
class MyList(MutableSequence[_T]):
@overload
def __getitem__(self, __i: SupportsIndex) -> _T: # type: ignore
def __getitem__(self, index: SupportsIndex) -> _T: # type: ignore
...
@overload
def __getitem__(self, __s: slice) -> MyList[_T]:
def __getitem__(self, index: slice) -> MyList[_T]:
...

View File

@ -888,12 +888,12 @@ test('KwargsUnpack1', () => {
});
test('FunctionMember1', () => {
// Analyze with reportFunctionMemberAccess disabled.
const analysisResult1 = TestUtils.typeAnalyzeSampleFiles(['functionMember1.py']);
const configOptions = new ConfigOptions('.');
configOptions.diagnosticRuleSet.reportFunctionMemberAccess = 'none';
const analysisResult1 = TestUtils.typeAnalyzeSampleFiles(['functionMember1.py'], configOptions);
TestUtils.validateResults(analysisResult1, 0);
// Analyze with reportFunctionMemberAccess enabled.
const configOptions = new ConfigOptions('.');
configOptions.diagnosticRuleSet.reportFunctionMemberAccess = 'error';
const analysisResult2 = TestUtils.typeAnalyzeSampleFiles(['functionMember1.py'], configOptions);
TestUtils.validateResults(analysisResult2, 3);

View File

@ -771,11 +771,10 @@ test('Classes4', () => {
test('Classes5', () => {
const configOptions = new ConfigOptions('.');
// By default, optional diagnostics are ignored.
configOptions.diagnosticRuleSet.reportIncompatibleVariableOverride = 'none';
let analysisResults = TestUtils.typeAnalyzeSampleFiles(['classes5.py'], configOptions);
TestUtils.validateResults(analysisResults, 11);
// Turn on reportIncompatibleVariableOverride.
configOptions.diagnosticRuleSet.reportIncompatibleVariableOverride = 'error';
analysisResults = TestUtils.typeAnalyzeSampleFiles(['classes5.py'], configOptions);
TestUtils.validateResults(analysisResults, 36);
@ -826,11 +825,10 @@ test('Methods1', () => {
test('MethodOverride1', () => {
const configOptions = new ConfigOptions('.');
// By default, optional diagnostics are ignored.
configOptions.diagnosticRuleSet.reportIncompatibleMethodOverride = 'none';
let analysisResults = TestUtils.typeAnalyzeSampleFiles(['methodOverride1.py'], configOptions);
TestUtils.validateResults(analysisResults, 0);
// Turn on errors.
configOptions.diagnosticRuleSet.reportIncompatibleMethodOverride = 'error';
analysisResults = TestUtils.typeAnalyzeSampleFiles(['methodOverride1.py'], configOptions);
TestUtils.validateResults(analysisResults, 36);
@ -839,11 +837,10 @@ test('MethodOverride1', () => {
test('MethodOverride2', () => {
const configOptions = new ConfigOptions('.');
// By default, optional diagnostics are ignored.
configOptions.diagnosticRuleSet.reportIncompatibleMethodOverride = 'none';
let analysisResults = TestUtils.typeAnalyzeSampleFiles(['methodOverride2.py'], configOptions);
TestUtils.validateResults(analysisResults, 0);
// Turn on errors.
configOptions.diagnosticRuleSet.reportIncompatibleMethodOverride = 'error';
analysisResults = TestUtils.typeAnalyzeSampleFiles(['methodOverride2.py'], configOptions);
TestUtils.validateResults(analysisResults, 6);
@ -852,11 +849,10 @@ test('MethodOverride2', () => {
test('MethodOverride3', () => {
const configOptions = new ConfigOptions('.');
// By default, optional diagnostics are ignored.
configOptions.diagnosticRuleSet.reportIncompatibleMethodOverride = 'none';
let analysisResults = TestUtils.typeAnalyzeSampleFiles(['methodOverride3.py'], configOptions);
TestUtils.validateResults(analysisResults, 0);
// Turn on errors.
configOptions.diagnosticRuleSet.reportIncompatibleMethodOverride = 'error';
analysisResults = TestUtils.typeAnalyzeSampleFiles(['methodOverride3.py'], configOptions);
TestUtils.validateResults(analysisResults, 5);
@ -878,6 +874,7 @@ test('MethodOverride5', () => {
test('MethodOverride6', () => {
const configOptions = new ConfigOptions('.');
configOptions.diagnosticRuleSet.reportIncompatibleMethodOverride = 'none';
const analysisResults1 = TestUtils.typeAnalyzeSampleFiles(['methodOverride6.py'], configOptions);
TestUtils.validateResults(analysisResults1, 0);

View File

@ -290,7 +290,7 @@ test('Overload4', () => {
test('Overload5', () => {
const configOptions = new ConfigOptions('.');
// By default, reportOverlappingOverload is off.
configOptions.diagnosticRuleSet.reportOverlappingOverload = 'none';
let analysisResults = TestUtils.typeAnalyzeSampleFiles(['overload5.py'], configOptions);
TestUtils.validateResults(analysisResults, 0);

View File

@ -188,7 +188,7 @@
},
"python.analysis.diagnosticSeverityOverrides": {
"type": "object",
"description": "Allows a user to override the severity levels for individual diagnostics. Use the rule name as a key and one of \"error\", \"warning\", \"information\", \"none\", `true` (alias for \"error\") or `false` (alias for \"none\") as value. The default value shown for each diagnostic is the default when \"python.analysis.typeCheckingMode\" is set to \"basic\". See [here](https://github.com/microsoft/pyright/blob/main/docs/configuration.md#diagnostic-rule-defaults) for defaults for each type checking mode (\"off\", \"basic\" and \"strict\").",
"description": "Allows a user to override the severity levels for individual diagnostics. Use the rule name as a key and one of \"error\", \"warning\", \"information\", \"none\", `true` (alias for \"error\") or `false` (alias for \"none\") as value. The default value shown for each diagnostic is the default when \"python.analysis.typeCheckingMode\" is set to \"standard\". See [here](https://github.com/microsoft/pyright/blob/main/docs/configuration.md#diagnostic-rule-defaults) for defaults for each type checking mode (\"off\", \"basic\", \"standard\", and \"strict\").",
"scope": "resource",
"properties": {
"reportGeneralTypeIssues": {
@ -229,7 +229,7 @@
"boolean"
],
"description": "Diagnostics for member accesses on functions.",
"default": "none",
"default": "error",
"enum": [
"none",
"information",
@ -661,7 +661,7 @@
"boolean"
],
"description": "Diagnostics for methods that override a method of the same name in a base class in an incompatible manner (wrong number of parameters, incompatible parameter types, or incompatible return type).",
"default": "none",
"default": "error",
"enum": [
"none",
"information",
@ -677,7 +677,7 @@
"boolean"
],
"description": "Diagnostics for overrides in subclasses that redefine a variable in an incompatible way.",
"default": "none",
"default": "error",
"enum": [
"none",
"information",
@ -709,7 +709,7 @@
"boolean"
],
"description": "Diagnostics for function overloads that overlap in signature and obscure each other or have incompatible return types.",
"default": "none",
"default": "error",
"enum": [
"none",
"information",
@ -1230,10 +1230,11 @@
},
"python.analysis.typeCheckingMode": {
"type": "string",
"default": "basic",
"default": "standard",
"enum": [
"off",
"basic",
"standard",
"strict"
],
"description": "Defines the default rule set for type checking.",

View File

@ -84,10 +84,11 @@
"enum": [
"off",
"basic",
"standard",
"strict"
],
"title": "Specifies the default rule set to use for type checking",
"default": "basic"
"default": "standard"
},
"useLibraryCodeForTypes": {
"$id": "#/properties/useLibraryCodeForTypes",
@ -182,7 +183,7 @@
"$id": "#/properties/reportFunctionMemberAccess",
"$ref": "#/definitions/diagnostic",
"title": "Controls reporting of member accesses on function objects",
"default": "none"
"default": "error"
},
"reportMissingImports": {
"$id": "#/properties/reportMissingImports",
@ -344,13 +345,13 @@
"$id": "#/properties/reportIncompatibleMethodOverride",
"$ref": "#/definitions/diagnostic",
"title": "Controls reporting of method overrides in subclasses that redefine the method in an incompatible way",
"default": "none"
"default": "error"
},
"reportIncompatibleVariableOverride": {
"$id": "#/properties/reportIncompatibleVariableOverride",
"$ref": "#/definitions/diagnostic",
"title": "Controls reporting of overrides in subclasses that redefine a variable in an incompatible way",
"default": "none"
"default": "error"
},
"reportInconsistentConstructor": {
"$id": "#/properties/reportInconsistentConstructor",
@ -362,7 +363,7 @@
"$id": "#/properties/reportOverlappingOverload",
"$ref": "#/definitions/diagnostic",
"title": "Controls reporting of function overloads that overlap in signature and obscure each other or do not agree on return type",
"default": "none"
"default": "error"
},
"reportMissingSuperCall": {
"$id": "#/properties/reportMissingSuperCall",