diff --git a/.github/workflows/mypy_primer_pr.yaml b/.github/workflows/mypy_primer_pr.yaml index 77af4c3f7..2b78ef57e 100644 --- a/.github/workflows/mypy_primer_pr.yaml +++ b/.github/workflows/mypy_primer_pr.yaml @@ -35,7 +35,7 @@ jobs: contents: read strategy: matrix: - shard-index: [0, 1] + shard-index: [0, 1, 2, 3, 4, 5, 6, 7] fail-fast: false steps: - uses: actions/checkout@v4 @@ -69,7 +69,7 @@ jobs: --repo pyright_to_test \ --type-checker pyright \ --new $GITHUB_SHA --old base_commit \ - --num-shards 2 --shard-index ${{ matrix.shard-index }} \ + --num-shards 8 --shard-index ${{ matrix.shard-index }} \ --debug \ --output concise \ | tee diff_${{ matrix.shard-index }}.txt diff --git a/packages/pyright-internal/src/analyzer/checker.ts b/packages/pyright-internal/src/analyzer/checker.ts index a45ba987c..436eea030 100644 --- a/packages/pyright-internal/src/analyzer/checker.ts +++ b/packages/pyright-internal/src/analyzer/checker.ts @@ -3092,106 +3092,123 @@ export class Checker extends ParseTreeWalker { private _reportInvalidOverload(name: string, symbol: Symbol) { const typedDecls = symbol.getTypedDeclarations(); - if (typedDecls.length >= 1) { - const primaryDecl = typedDecls[0]; + if (typedDecls.length === 0) { + return; + } - if (primaryDecl.type === DeclarationType.Function) { - const type = this._evaluator.getEffectiveTypeOfSymbol(symbol); - const overloadedFunctions = isOverloadedFunction(type) - ? OverloadedFunctionType.getOverloads(type) - : isFunction(type) && FunctionType.isOverloaded(type) - ? [type] - : []; + const primaryDecl = typedDecls[0]; - if (overloadedFunctions.length === 1) { - // There should never be a single overload. - this._evaluator.addDiagnostic( - DiagnosticRule.reportInconsistentOverload, - LocMessage.singleOverload().format({ name }), - primaryDecl.node.name - ); - } + if (primaryDecl.type !== DeclarationType.Function) { + return; + } - // If the file is not a stub and this is the first overload, - // verify that there is an implementation. - if (!this._fileInfo.isStubFile && overloadedFunctions.length > 0) { - let implementationFunction: FunctionType | undefined; - let exemptMissingImplementation = false; + const type = this._evaluator.getEffectiveTypeOfSymbol(symbol); + const overloadedFunctions = isOverloadedFunction(type) + ? OverloadedFunctionType.getOverloads(type) + : isFunction(type) && FunctionType.isOverloaded(type) + ? [type] + : []; - if (isOverloadedFunction(type)) { - implementationFunction = OverloadedFunctionType.getImplementation(type); + // If the implementation has no name, it was synthesized probably by a + // decorator that used a callable with a ParamSpec that captured the + // overloaded signature. We'll exempt it from this check. + if (isOverloadedFunction(type)) { + const overloads = OverloadedFunctionType.getOverloads(type); + if (overloads.length > 0 && overloads[0].details.name === '') { + return; + } + } else if (isFunction(type)) { + if (type.details.name === '') { + return; + } + } - // If the implementation has no name, it was synthesized probably by a - // decorator that used a callable with a ParamSpec that captured the - // overloaded signature. We'll exempt it from this check. - const overloads = OverloadedFunctionType.getOverloads(type); - if (overloads.length > 0 && overloads[0].details.name === '') { - exemptMissingImplementation = true; - } - } else if (isFunction(type) && !FunctionType.isOverloaded(type)) { - implementationFunction = type; + if (overloadedFunctions.length === 1) { + // There should never be a single overload. + this._evaluator.addDiagnostic( + DiagnosticRule.reportInconsistentOverload, + LocMessage.singleOverload().format({ name }), + primaryDecl.node.name + ); + } + + // If the file is not a stub and this is the first overload, + // verify that there is an implementation. + if (this._fileInfo.isStubFile || overloadedFunctions.length === 0) { + return; + } + + let implementationFunction: FunctionType | undefined; + + if (isOverloadedFunction(type)) { + implementationFunction = OverloadedFunctionType.getImplementation(type); + } else if (isFunction(type) && !FunctionType.isOverloaded(type)) { + implementationFunction = type; + } + + if (!implementationFunction) { + const containingClassNode = ParseTreeUtils.getEnclosingClassOrFunction(primaryDecl.node); + if (containingClassNode && containingClassNode.nodeType === ParseNodeType.Class) { + const classType = this._evaluator.getTypeOfClass(containingClassNode); + if (classType) { + if (ClassType.isProtocolClass(classType.classType)) { + return; } - if (!implementationFunction) { - const containingClassNode = ParseTreeUtils.getEnclosingClassOrFunction(primaryDecl.node); - if (containingClassNode && containingClassNode.nodeType === ParseNodeType.Class) { - const classType = this._evaluator.getTypeOfClass(containingClassNode); - if (classType) { - if (ClassType.isProtocolClass(classType.classType)) { - exemptMissingImplementation = true; - } else if (ClassType.supportsAbstractMethods(classType.classType)) { - if ( - isOverloadedFunction(type) && - OverloadedFunctionType.getOverloads(type).every((overload) => - FunctionType.isAbstractMethod(overload) - ) - ) { - exemptMissingImplementation = true; - } - } - } + if (ClassType.supportsAbstractMethods(classType.classType)) { + if ( + isOverloadedFunction(type) && + OverloadedFunctionType.getOverloads(type).every((overload) => + FunctionType.isAbstractMethod(overload) + ) + ) { + return; } - - // If this is a method within a protocol class, don't require that - // there is an implementation. - if (!exemptMissingImplementation) { - this._evaluator.addDiagnostic( - DiagnosticRule.reportNoOverloadImplementation, - LocMessage.overloadWithoutImplementation().format({ - name: primaryDecl.node.name.value, - }), - primaryDecl.node.name - ); - } - } else if (isOverloadedFunction(type)) { - // Verify that all overload signatures are assignable to implementation signature. - OverloadedFunctionType.getOverloads(type).forEach((overload, index) => { - const diag = new DiagnosticAddendum(); - if (!this._isLegalOverloadImplementation(overload, implementationFunction!, diag)) { - if (implementationFunction!.details.declaration) { - const diagnostic = this._evaluator.addDiagnostic( - DiagnosticRule.reportInconsistentOverload, - LocMessage.overloadImplementationMismatch().format({ - name, - index: index + 1, - }) + diag.getString(), - implementationFunction!.details.declaration.node.name - ); - - if (diagnostic && overload.details.declaration) { - diagnostic.addRelatedInfo( - LocAddendum.overloadSignature(), - overload.details.declaration?.uri ?? primaryDecl.uri, - overload.details.declaration?.range ?? primaryDecl.range - ); - } - } - } - }); } } } + + // If this is a method within a protocol class, don't require that + // there is an implementation. + this._evaluator.addDiagnostic( + DiagnosticRule.reportNoOverloadImplementation, + LocMessage.overloadWithoutImplementation().format({ + name: primaryDecl.node.name.value, + }), + primaryDecl.node.name + ); + + return; } + + if (!isOverloadedFunction(type)) { + return; + } + + // Verify that all overload signatures are assignable to implementation signature. + OverloadedFunctionType.getOverloads(type).forEach((overload, index) => { + const diag = new DiagnosticAddendum(); + if (!this._isLegalOverloadImplementation(overload, implementationFunction!, diag)) { + if (implementationFunction!.details.declaration) { + const diagnostic = this._evaluator.addDiagnostic( + DiagnosticRule.reportInconsistentOverload, + LocMessage.overloadImplementationMismatch().format({ + name, + index: index + 1, + }) + diag.getString(), + implementationFunction!.details.declaration.node.name + ); + + if (diagnostic && overload.details.declaration) { + diagnostic.addRelatedInfo( + LocAddendum.overloadSignature(), + overload.details.declaration?.uri ?? primaryDecl.uri, + overload.details.declaration?.range ?? primaryDecl.range + ); + } + } + } + }); } private _reportMultipleFinalDeclarations(name: string, symbol: Symbol, scopeType: ScopeType) { diff --git a/packages/pyright-internal/src/analyzer/codeFlowEngine.ts b/packages/pyright-internal/src/analyzer/codeFlowEngine.ts index 05456ceb2..6abeb2870 100644 --- a/packages/pyright-internal/src/analyzer/codeFlowEngine.ts +++ b/packages/pyright-internal/src/analyzer/codeFlowEngine.ts @@ -134,6 +134,11 @@ export interface IncompleteType { isRecursionSentinel?: boolean; } +interface ReachabilityCacheEntry { + isReachable: boolean | undefined; + isReachableFrom: Map; +} + // Define a user type guard function for IncompleteType. export function isIncompleteType(cachedType: CachedType): cachedType is IncompleteType { return !!(cachedType as IncompleteType).isIncompleteType; @@ -164,6 +169,7 @@ export function getCodeFlowEngine( speculativeTypeTracker: SpeculativeTypeTracker ): CodeFlowEngine { const isReachableRecursionSet = new Set(); + const reachabilityCache = new Map(); const callIsNoReturnCache = new Map(); const isExceptionContextManagerCache = new Map(); let flowIncompleteGeneration = 1; @@ -1182,11 +1188,29 @@ export function getCodeFlowEngine( printControlFlowGraph(flowNode, /* reference */ undefined, 'isFlowNodeReachable'); } - function isFlowNodeReachableRecursive( - flowNode: FlowNode, - sourceFlowNode: FlowNode | undefined, - recursionCount = 0 - ): boolean { + function cacheReachabilityResult(isReachable: boolean): boolean { + // If there is a finally gate set, we will not cache the results + // because this can affect the reachability. + if (closedFinallyGateSet.size > 0) { + return isReachable; + } + + let cacheEntry = reachabilityCache.get(flowNode.id); + if (!cacheEntry) { + cacheEntry = { isReachable: undefined, isReachableFrom: new Map() }; + reachabilityCache.set(flowNode.id, cacheEntry); + } + + if (!sourceFlowNode) { + cacheEntry.isReachable = isReachable; + } else { + cacheEntry.isReachableFrom.set(sourceFlowNode.id, isReachable); + } + + return isReachable; + } + + function isFlowNodeReachableRecursive(flowNode: FlowNode, recursionCount = 0): boolean { // Cut off the recursion at some point to prevent a stack overflow. const maxFlowNodeReachableRecursionCount = 64; if (recursionCount > maxFlowNodeReachableRecursionCount) { @@ -1197,21 +1221,36 @@ export function getCodeFlowEngine( let curFlowNode = flowNode; while (true) { + // See if we've already cached this result. + const cacheEntry = reachabilityCache.get(flowNode.id); + if (cacheEntry !== undefined && closedFinallyGateSet.size === 0) { + if (!sourceFlowNode) { + if (cacheEntry.isReachable !== undefined) { + return cacheEntry.isReachable; + } + } else { + const isReachableFrom = cacheEntry.isReachableFrom.get(sourceFlowNode.id); + if (isReachableFrom !== undefined) { + return isReachableFrom; + } + } + } + // If we've already visited this node, we can assume // it wasn't reachable. if (visitedFlowNodeSet.has(curFlowNode.id)) { - return false; + return cacheReachabilityResult(false); } // Note that we've been here before. visitedFlowNodeSet.add(curFlowNode.id); if (curFlowNode.flags & FlowFlags.Unreachable) { - return false; + return cacheReachabilityResult(false); } if (curFlowNode === sourceFlowNode) { - return true; + return cacheReachabilityResult(true); } if ( @@ -1271,7 +1310,7 @@ export function getCodeFlowEngine( } if (isUnreachable) { - return false; + return cacheReachabilityResult(false); } } } @@ -1287,7 +1326,7 @@ export function getCodeFlowEngine( // it always raises an exception or otherwise doesn't return, // so we can assume that the code before this is unreachable. if (!ignoreNoReturn && isCallNoReturn(evaluator, callFlowNode)) { - return false; + return cacheReachabilityResult(false); } curFlowNode = callFlowNode.antecedent; @@ -1304,29 +1343,29 @@ export function getCodeFlowEngine( isExceptionContextManager(evaluator, expr, contextMgrNode.isAsync) ) ) { - return false; + return cacheReachabilityResult(false); } } const labelNode = curFlowNode as FlowLabel; for (const antecedent of labelNode.antecedents) { - if (isFlowNodeReachableRecursive(antecedent, sourceFlowNode, recursionCount)) { - return true; + if (isFlowNodeReachableRecursive(antecedent, recursionCount)) { + return cacheReachabilityResult(true); } } - return false; + return cacheReachabilityResult(false); } if (curFlowNode.flags & FlowFlags.Start) { // If we hit the start but were looking for a particular source flow // node, return false. Otherwise, the start is what we're looking for. - return sourceFlowNode ? false : true; + return cacheReachabilityResult(sourceFlowNode ? false : true); } if (curFlowNode.flags & FlowFlags.PreFinallyGate) { const preFinallyFlowNode = curFlowNode as FlowPreFinallyGate; if (closedFinallyGateSet.has(preFinallyFlowNode.id)) { - return false; + return cacheReachabilityResult(false); } curFlowNode = preFinallyFlowNode.antecedent; @@ -1339,10 +1378,8 @@ export function getCodeFlowEngine( try { closedFinallyGateSet.add(postFinallyFlowNode.preFinallyGate.id); - return isFlowNodeReachableRecursive( - postFinallyFlowNode.antecedent, - sourceFlowNode, - recursionCount + return cacheReachabilityResult( + isFlowNodeReachableRecursive(postFinallyFlowNode.antecedent, recursionCount) ); } finally { if (!wasGateClosed) { @@ -1353,7 +1390,7 @@ export function getCodeFlowEngine( // We shouldn't get here. fail('Unexpected flow node flags'); - return false; + return cacheReachabilityResult(false); } } @@ -1364,7 +1401,7 @@ export function getCodeFlowEngine( isReachableRecursionSet.add(flowNode.id); try { - return isFlowNodeReachableRecursive(flowNode, sourceFlowNode); + return isFlowNodeReachableRecursive(flowNode); } finally { isReachableRecursionSet.delete(flowNode.id); } diff --git a/packages/pyright-internal/src/analyzer/constraintSolver.ts b/packages/pyright-internal/src/analyzer/constraintSolver.ts index e78e5219a..2e3d7d1b2 100644 --- a/packages/pyright-internal/src/analyzer/constraintSolver.ts +++ b/packages/pyright-internal/src/analyzer/constraintSolver.ts @@ -1020,7 +1020,7 @@ function assignTypeToParamSpec( // performs this reverse mapping of type arguments and populates the type var // map for the target type. If the type is not assignable to the expected type, // it returns false. -export function populateTypeVarContextBasedOnExpectedType( +export function addConstraintsForExpectedType( evaluator: TypeEvaluator, type: ClassType, expectedType: Type, diff --git a/packages/pyright-internal/src/analyzer/constructors.ts b/packages/pyright-internal/src/analyzer/constructors.ts index 672fba6a2..044183362 100644 --- a/packages/pyright-internal/src/analyzer/constructors.ts +++ b/packages/pyright-internal/src/analyzer/constructors.ts @@ -17,7 +17,7 @@ import { DiagnosticAddendum } from '../common/diagnostic'; import { DiagnosticRule } from '../common/diagnosticRules'; import { LocMessage } from '../localization/localize'; import { ArgumentCategory, ExpressionNode, ParameterCategory } from '../parser/parseNodes'; -import { populateTypeVarContextBasedOnExpectedType } from './constraintSolver'; +import { addConstraintsForExpectedType } from './constraintSolver'; import { applyConstructorTransform, hasConstructorTransform } from './constructorTransform'; import { getTypeVarScopesForNode } from './parseTreeUtils'; import { CallResult, FunctionArgument, TypeEvaluator, TypeResult } from './typeEvaluatorTypes'; @@ -25,14 +25,17 @@ import { InferenceContext, MemberAccessFlags, UniqueSignatureTracker, + addTypeVarsToListIfUnique, applySolvedTypeVars, buildTypeVarContextFromSpecializedClass, convertToInstance, + convertTypeToParamSpecValue, doForEachSignature, doForEachSubtype, ensureFunctionSignaturesAreUnique, getTypeVarArgumentsRecursive, getTypeVarScopeId, + getTypeVarScopeIds, isTupleClass, lookUpClassMember, mapSubtypes, @@ -60,6 +63,7 @@ import { isInstantiableClass, isNever, isOverloadedFunction, + isParamSpec, isTypeVar, isUnion, isUnknown, @@ -286,7 +290,7 @@ function validateNewAndInitMethods( newMethodReturnType = applySolvedTypeVars( ClassType.cloneAsInstance(type), new TypeVarContext(getTypeVarScopeId(type)), - { unknownIfNotFound: true } + { unknownIfNotFound: true, tupleClassType: evaluator.getTupleClassType() } ) as ClassType; } @@ -539,7 +543,7 @@ function validateInitMethod( typeVarContext.addSolveForScope(getTypeVarScopeId(initMethodType)); if ( - populateTypeVarContextBasedOnExpectedType( + !addConstraintsForExpectedType( evaluator, ClassType.cloneAsInstance(type), expectedSubType, @@ -548,54 +552,56 @@ function validateInitMethod( errorNode.start ) ) { - const specializedConstructor = applySolvedTypeVars(initMethodType, typeVarContext); - - let callResult: CallResult | undefined; - callResult = evaluator.useSpeculativeMode(errorNode, () => { - return evaluator.validateCallArguments( - errorNode, - argList, - { type: specializedConstructor }, - typeVarContext.clone(), - skipUnknownArgCheck, - /* inferenceContext */ undefined, - signatureTracker - ); - }); - - if (!callResult.argumentErrors) { - // Call validateCallArguments again, this time without speculative - // mode, so any errors are reported. - callResult = evaluator.validateCallArguments( - errorNode, - argList, - { type: specializedConstructor }, - typeVarContext, - skipUnknownArgCheck, - /* inferenceContext */ undefined, - signatureTracker - ); - - if (callResult.isTypeIncomplete) { - isTypeIncomplete = true; - } - - if (callResult.argumentErrors) { - argumentErrors = true; - } - - if (callResult.overloadsUsedForCall) { - appendArray(overloadsUsedForCall, callResult.overloadsUsedForCall); - } - - // Note that we've found an expected type that works. - foundWorkingExpectedType = true; - - return applyExpectedSubtypeForConstructor(evaluator, type, expectedSubType, typeVarContext); - } + return undefined; } - return undefined; + const specializedConstructor = applySolvedTypeVars(initMethodType, typeVarContext); + + let callResult: CallResult | undefined; + callResult = evaluator.useSpeculativeMode(errorNode, () => { + return evaluator.validateCallArguments( + errorNode, + argList, + { type: specializedConstructor }, + typeVarContext.clone(), + skipUnknownArgCheck, + /* inferenceContext */ undefined, + signatureTracker + ); + }); + + if (callResult.argumentErrors) { + return undefined; + } + + // Call validateCallArguments again, this time without speculative + // mode, so any errors are reported. + callResult = evaluator.validateCallArguments( + errorNode, + argList, + { type: specializedConstructor }, + typeVarContext, + skipUnknownArgCheck, + /* inferenceContext */ undefined, + signatureTracker + ); + + if (callResult.isTypeIncomplete) { + isTypeIncomplete = true; + } + + if (callResult.argumentErrors) { + argumentErrors = true; + } + + if (callResult.overloadsUsedForCall) { + appendArray(overloadsUsedForCall, callResult.overloadsUsedForCall); + } + + // Note that we've found an expected type that works. + foundWorkingExpectedType = true; + + return applyExpectedSubtypeForConstructor(evaluator, type, expectedSubType, typeVarContext); }, /* sortSubtypes */ true ); @@ -704,7 +710,7 @@ function validateFallbackConstructorCall( } if (expectedType) { - populateTypeVarContextBasedOnExpectedType( + addConstraintsForExpectedType( evaluator, ClassType.cloneAsInstance(type), expectedType, @@ -818,6 +824,7 @@ function applyExpectedTypeForConstructor( const specializedType = applySolvedTypeVars(type, typeVarContext, { unknownIfNotFound: unsolvedTypeVarsAreUnknown, + tupleClassType: evaluator.getTupleClassType(), }) as ClassType; return ClassType.cloneAsInstance(specializedType); } @@ -1086,10 +1093,43 @@ function createFunctionFromInitMethod( } const convertedInit = FunctionType.clone(boundInit); - convertedInit.details.declaredReturnType = boundInit.strippedFirstParamType ?? selfType ?? objectType; + let returnType = selfType; + if (!returnType) { + returnType = objectType; + + // If this is a generic type, self-specialize the class (i.e. fill in + // its own type parameters as type arguments). + if (objectType.details.typeParameters.length > 0 && !objectType.typeArguments) { + const typeVarContext = new TypeVarContext(getTypeVarScopeIds(objectType)); + + // If a TypeVar is not used in any of the parameter types, it should take + // on its default value (typically Unknown) in the resulting specialized type. + const typeVarsInParams: TypeVarType[] = []; + + convertedInit.details.parameters.forEach((param, index) => { + const paramType = FunctionType.getEffectiveParameterType(convertedInit, index); + addTypeVarsToListIfUnique(typeVarsInParams, getTypeVarArgumentsRecursive(paramType)); + }); + + typeVarsInParams.forEach((typeVar) => { + if (isParamSpec(typeVar)) { + typeVarContext.setTypeVarType(typeVar, convertTypeToParamSpecValue(typeVar)); + } else { + typeVarContext.setTypeVarType(typeVar, typeVar); + } + }); + + returnType = applySolvedTypeVars(objectType, typeVarContext, { + unknownIfNotFound: true, + tupleClassType: evaluator.getTupleClassType(), + }) as ClassType; + } + } + + convertedInit.details.declaredReturnType = boundInit.strippedFirstParamType ?? returnType; if (convertedInit.specializedTypes) { - convertedInit.specializedTypes.returnType = selfType ?? objectType; + convertedInit.specializedTypes.returnType = returnType; } if (!convertedInit.details.docString && classType.details.docString) { diff --git a/packages/pyright-internal/src/analyzer/dataClasses.ts b/packages/pyright-internal/src/analyzer/dataClasses.ts index 8494e9087..3d086e216 100644 --- a/packages/pyright-internal/src/analyzer/dataClasses.ts +++ b/packages/pyright-internal/src/analyzer/dataClasses.ts @@ -821,7 +821,10 @@ function getConverterInputType( const inputTypeVarContext = new TypeVarContext(typeVar.scopeId); if (evaluator.assignType(targetFunction, signature, diagAddendum, inputTypeVarContext)) { - const overloadSolution = applySolvedTypeVars(typeVar, inputTypeVarContext, { unknownIfNotFound: true }); + const overloadSolution = applySolvedTypeVars(typeVar, inputTypeVarContext, { + unknownIfNotFound: true, + tupleClassType: evaluator.getTupleClassType(), + }); acceptedTypes.push(overloadSolution); } }); diff --git a/packages/pyright-internal/src/analyzer/importResolver.ts b/packages/pyright-internal/src/analyzer/importResolver.ts index fba6ea175..3e362bc98 100644 --- a/packages/pyright-internal/src/analyzer/importResolver.ts +++ b/packages/pyright-internal/src/analyzer/importResolver.ts @@ -109,7 +109,8 @@ export class ImportResolver { private _cachedFilesForPath = new Map(); private _cachedDirExistenceForRoot = new Map(); private _stdlibModules: Set | undefined; - protected cachedParentImportResults: ParentDirectoryCache; + + protected readonly cachedParentImportResults: ParentDirectoryCache; constructor(readonly serviceProvider: ServiceProvider, private _configOptions: ConfigOptions, readonly host: Host) { this.cachedParentImportResults = new ParentDirectoryCache(() => this.getPythonSearchPaths([])); @@ -172,7 +173,7 @@ export class ImportResolver { return suggestions; } - const root = this.getParentImportResolutionRoot(sourceFileUri, execEnv.root); + const root = getParentImportResolutionRoot(sourceFileUri, execEnv.root); const origin = sourceFileUri.getDirectory(); let current: Uri | undefined = origin; @@ -533,7 +534,7 @@ export class ImportResolver { execEnv: ExecutionEnvironment, moduleDescriptor: ImportedModuleDescriptor ): ImportResult { - const importName = this.formatImportName(moduleDescriptor); + const importName = formatImportName(moduleDescriptor); const importFailureInfo: string[] = []; const importResult = this._resolveImportStrict( importName, @@ -559,7 +560,7 @@ export class ImportResolver { } // Check whether the given file is in the parent directory import resolution cache. - const root = this.getParentImportResolutionRoot(sourceFileUri, execEnv.root); + const root = getParentImportResolutionRoot(sourceFileUri, execEnv.root); if (!this.cachedParentImportResults.checkValidPath(this.fileSystem, sourceFileUri, root)) { return importResult; } @@ -776,74 +777,12 @@ export class ImportResolver { protected getNativeModuleName(uri: Uri): string | undefined { const fileExtension = uri.lastExtension.toLowerCase(); - if (this._isNativeModuleFileExtension(fileExtension)) { + if (_isNativeModuleFileExtension(fileExtension)) { return stripFileExtension(uri.fileName, /* multiDotExtension */ true); } return undefined; } - protected getModuleNameFromPath( - containerPath: Uri, - fileUri: Uri, - stripTopContainerDir = false - ): string | undefined { - const moduleNameInfo = this.getModuleNameInfoFromPath(containerPath, fileUri, stripTopContainerDir); - if (!moduleNameInfo || moduleNameInfo.containsInvalidCharacters) { - return undefined; - } - - return moduleNameInfo.moduleName; - } - - protected getModuleNameInfoFromPath( - containerPath: Uri, - fileUri: Uri, - stripTopContainerDir = false - ): ModuleNameInfoFromPath | undefined { - let fileUriWithoutExtension = fileUri.stripExtension(); - - // If module is native, strip platform part, such as 'cp36-win_amd64' in 'mtrand.cp36-win_amd64'. - if (this._isNativeModuleFileExtension(fileUri.lastExtension)) { - fileUriWithoutExtension = fileUriWithoutExtension.stripExtension(); - } - - if (!fileUriWithoutExtension.startsWith(containerPath)) { - return undefined; - } - - // Strip off the '/__init__' if it's present. - if (fileUriWithoutExtension.pathEndsWith('__init__')) { - fileUriWithoutExtension = fileUriWithoutExtension.getDirectory(); - } - - const parts = Array.from(containerPath.getRelativePathComponents(fileUriWithoutExtension)); - if (stripTopContainerDir) { - if (parts.length === 0) { - return undefined; - } - parts.shift(); - } - - if (parts.length === 0) { - return undefined; - } - - // Handle the case where the symbol was resolved to a stubs package - // rather than the real package. We'll strip off the "-stubs" suffix - // in this case. - if (parts[0].endsWith(stubsSuffix)) { - parts[0] = parts[0].substr(0, parts[0].length - stubsSuffix.length); - } - - // Check whether parts contains invalid characters. - const containsInvalidCharacters = parts.some((p) => !this._isIdentifier(p)); - - return { - moduleName: parts.join('.'), - containsInvalidCharacters, - }; - } - // Potentially modifies the ImportResult by removing some or all of the // implicit import entries. Only the imported symbols should be included. protected filterImplicitImports( @@ -880,22 +819,6 @@ export class ImportResolver { return newImportResult; } - protected formatImportName(moduleDescriptor: ImportedModuleDescriptor) { - return '.'.repeat(moduleDescriptor.leadingDots) + moduleDescriptor.nameParts.join('.'); - } - - protected getParentImportResolutionRoot(sourceFileUri: Uri, executionRoot: Uri | undefined): Uri { - if (!this._isDefaultWorkspace(executionRoot)) { - return executionRoot!; - } - - return sourceFileUri.getDirectory(); - } - - private _isDefaultWorkspace(uri: Uri | undefined) { - return !uri || uri.isEmpty() || Uri.isDefaultWorkspace(uri); - } - private _resolveImportStrict( importName: string, sourceFileUri: Uri, @@ -1119,7 +1042,7 @@ export class ImportResolver { ); if (stdLibTypeshedPath) { - moduleName = this.getModuleNameFromPath(stdLibTypeshedPath, fileUri); + moduleName = getModuleNameFromPath(stdLibTypeshedPath, fileUri); if (moduleName) { const moduleDescriptor: ImportedModuleDescriptor = { leadingDots: 0, @@ -1149,7 +1072,7 @@ export class ImportResolver { // Look for it in the root directory of the execution environment. if (execEnv.root) { - const candidateModuleNameInfo = this.getModuleNameInfoFromPath(execEnv.root, fileUri); + const candidateModuleNameInfo = _getModuleNameInfoFromPath(execEnv.root, fileUri); if (candidateModuleNameInfo) { if (candidateModuleNameInfo.containsInvalidCharacters) { @@ -1163,7 +1086,7 @@ export class ImportResolver { } for (const extraPath of execEnv.extraPaths) { - const candidateModuleNameInfo = this.getModuleNameInfoFromPath(extraPath, fileUri); + const candidateModuleNameInfo = _getModuleNameInfoFromPath(extraPath, fileUri); if (candidateModuleNameInfo) { if (candidateModuleNameInfo.containsInvalidCharacters) { @@ -1182,7 +1105,7 @@ export class ImportResolver { // Check for a typings file. if (this._configOptions.stubPath) { - const candidateModuleNameInfo = this.getModuleNameInfoFromPath(this._configOptions.stubPath, fileUri); + const candidateModuleNameInfo = _getModuleNameInfoFromPath(this._configOptions.stubPath, fileUri); if (candidateModuleNameInfo) { if (candidateModuleNameInfo.containsInvalidCharacters) { @@ -1209,7 +1132,7 @@ export class ImportResolver { ); if (thirdPartyTypeshedPath) { - const candidateModuleName = this.getModuleNameFromPath( + const candidateModuleName = getModuleNameFromPath( thirdPartyTypeshedPath, fileUri, /* stripTopContainerDir */ true @@ -1226,7 +1149,7 @@ export class ImportResolver { const thirdPartyTypeshedPathEx = this.getTypeshedPathEx(execEnv, importFailureInfo); if (thirdPartyTypeshedPathEx) { - const candidateModuleName = this.getModuleNameFromPath(thirdPartyTypeshedPathEx, fileUri); + const candidateModuleName = getModuleNameFromPath(thirdPartyTypeshedPathEx, fileUri); // Does this candidate look better than the previous best module name? // We'll always try to use the shortest version. @@ -1241,7 +1164,7 @@ export class ImportResolver { const pythonSearchPaths = this.getPythonSearchPaths(importFailureInfo); for (const searchPath of pythonSearchPaths) { - const candidateModuleNameInfo = this.getModuleNameInfoFromPath(searchPath, fileUri); + const candidateModuleNameInfo = _getModuleNameInfoFromPath(searchPath, fileUri); if (candidateModuleNameInfo) { if (candidateModuleNameInfo.containsInvalidCharacters) { @@ -1260,7 +1183,7 @@ export class ImportResolver { } if (detectPyTyped && importType === ImportType.ThirdParty) { - const root = this.getParentImportResolutionRoot(fileUri, execEnv.root); + const root = getParentImportResolutionRoot(fileUri, execEnv.root); // Go up directories one by one looking for a py.typed file. let current: Uri | undefined = fileUri.getDirectory(); @@ -1552,7 +1475,7 @@ export class ImportResolver { moduleDescriptor: ImportedModuleDescriptor, allowPyi: boolean ): ImportResult | undefined { - const importName = this.formatImportName(moduleDescriptor); + const importName = formatImportName(moduleDescriptor); const importFailureInfo: string[] = []; // Check for a local stub file using stubPath. @@ -1828,16 +1751,6 @@ export class ImportResolver { return bestImportSoFar; } - private _isIdentifier(value: string) { - for (let i = 0; i < value.length; i++) { - if (i === 0 ? !isIdentifierStartChar(value.charCodeAt(i)) : !isIdentifierChar(value.charCodeAt(i))) { - return false; - } - } - - return true; - } - private _findTypeshedPath( execEnv: ExecutionEnvironment, moduleDescriptor: ImportedModuleDescriptor, @@ -2588,7 +2501,7 @@ export class ImportResolver { // Make sure we don't use parent folder resolution when checking whether the given name is resolvable. let importResult: ImportResult | undefined; if (strictOnly) { - const importName = this.formatImportName(moduleDescriptor); + const importName = formatImportName(moduleDescriptor); const importFailureInfo: string[] = []; importResult = this._resolveImportStrict( @@ -2653,7 +2566,7 @@ export class ImportResolver { if (fileExt === '.py' || fileExt === '.pyi') { strippedFileName = stripFileExtension(filePath.fileName); } else if ( - this._isNativeModuleFileExtension(fileExt) && + _isNativeModuleFileExtension(fileExt) && !this.fileExistsCached(filePath.packageUri) && !this.fileExistsCached(filePath.packageStubUri) ) { @@ -2770,15 +2683,10 @@ export class ImportResolver { const fileExtension = fileUri.lastExtension.toLowerCase(); const withoutExtension = stripFileExtension(fileUri.fileName, /* multiDotExtension */ true); return ( - this._isNativeModuleFileExtension(fileExtension) && - equateStringsCaseInsensitive(moduleName, withoutExtension) + _isNativeModuleFileExtension(fileExtension) && equateStringsCaseInsensitive(moduleName, withoutExtension) ); } - private _isNativeModuleFileExtension(fileExtension: string): boolean { - return supportedNativeLibExtensions.some((ext) => ext === fileExtension); - } - private _tryWalkUp(current: Uri | undefined): Uri | undefined { if (!current || current.isEmpty() || current.isRoot()) { return undefined; @@ -2796,7 +2704,7 @@ export class ImportResolver { return ( current && !current.isEmpty() && - (current.isChild(root) || (current.equals(root) && this._isDefaultWorkspace(execEnv.root))) + (current.isChild(root) || (current.equals(root) && _isDefaultWorkspace(execEnv.root))) ); } } @@ -2806,3 +2714,95 @@ export type ImportResolverFactory = ( options: ConfigOptions, host: Host ) => ImportResolver; + +export function formatImportName(moduleDescriptor: ImportedModuleDescriptor) { + return '.'.repeat(moduleDescriptor.leadingDots) + moduleDescriptor.nameParts.join('.'); +} + +export function getParentImportResolutionRoot(sourceFileUri: Uri, executionRoot: Uri | undefined): Uri { + if (!_isDefaultWorkspace(executionRoot)) { + return executionRoot!; + } + + return sourceFileUri.getDirectory(); +} + +export function getModuleNameFromPath( + containerPath: Uri, + fileUri: Uri, + stripTopContainerDir = false +): string | undefined { + const moduleNameInfo = _getModuleNameInfoFromPath(containerPath, fileUri, stripTopContainerDir); + if (!moduleNameInfo || moduleNameInfo.containsInvalidCharacters) { + return undefined; + } + + return moduleNameInfo.moduleName; +} + +function _getModuleNameInfoFromPath( + containerPath: Uri, + fileUri: Uri, + stripTopContainerDir = false +): ModuleNameInfoFromPath | undefined { + let fileUriWithoutExtension = fileUri.stripExtension(); + + // If module is native, strip platform part, such as 'cp36-win_amd64' in 'mtrand.cp36-win_amd64'. + if (_isNativeModuleFileExtension(fileUri.lastExtension)) { + fileUriWithoutExtension = fileUriWithoutExtension.stripExtension(); + } + + if (!fileUriWithoutExtension.startsWith(containerPath)) { + return undefined; + } + + // Strip off the '/__init__' if it's present. + if (fileUriWithoutExtension.pathEndsWith('__init__')) { + fileUriWithoutExtension = fileUriWithoutExtension.getDirectory(); + } + + const parts = Array.from(containerPath.getRelativePathComponents(fileUriWithoutExtension)); + if (stripTopContainerDir) { + if (parts.length === 0) { + return undefined; + } + parts.shift(); + } + + if (parts.length === 0) { + return undefined; + } + + // Handle the case where the symbol was resolved to a stubs package + // rather than the real package. We'll strip off the "-stubs" suffix + // in this case. + if (parts[0].endsWith(stubsSuffix)) { + parts[0] = parts[0].substr(0, parts[0].length - stubsSuffix.length); + } + + // Check whether parts contains invalid characters. + const containsInvalidCharacters = parts.some((p) => !_isIdentifier(p)); + + return { + moduleName: parts.join('.'), + containsInvalidCharacters, + }; +} + +function _isNativeModuleFileExtension(fileExtension: string): boolean { + return supportedNativeLibExtensions.some((ext) => ext === fileExtension); +} + +function _isDefaultWorkspace(uri: Uri | undefined) { + return !uri || uri.isEmpty() || Uri.isDefaultWorkspace(uri); +} + +function _isIdentifier(value: string) { + for (let i = 0; i < value.length; i++) { + if (i === 0 ? !isIdentifierStartChar(value.charCodeAt(i)) : !isIdentifierChar(value.charCodeAt(i))) { + return false; + } + } + + return true; +} diff --git a/packages/pyright-internal/src/analyzer/operations.ts b/packages/pyright-internal/src/analyzer/operations.ts index afc08dfb8..1d03d957b 100644 --- a/packages/pyright-internal/src/analyzer/operations.ts +++ b/packages/pyright-internal/src/analyzer/operations.ts @@ -703,7 +703,7 @@ export function getTypeOfBinaryOperation( } } - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { // Exempt "|" because it might be a union operation involving unknowns. if (node.operator !== OperatorType.BitwiseOr) { evaluator.addDiagnostic(DiagnosticRule.reportInvalidTypeForm, LocMessage.binaryOperationNotAllowed(), node); @@ -950,7 +950,7 @@ export function getTypeOfUnaryOperation( flags: EvaluatorFlags, inferenceContext: InferenceContext | undefined ): TypeResult { - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { evaluator.addDiagnostic(DiagnosticRule.reportInvalidTypeForm, LocMessage.unaryOperationNotAllowed(), node); return { type: UnknownType.create() }; } @@ -1087,7 +1087,7 @@ export function getTypeOfTernaryOperation( ): TypeResult { const fileInfo = getFileInfo(node); - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { evaluator.addDiagnostic(DiagnosticRule.reportInvalidTypeForm, LocMessage.ternaryNotAllowed(), node); return { type: UnknownType.create() }; } diff --git a/packages/pyright-internal/src/analyzer/patternMatching.ts b/packages/pyright-internal/src/analyzer/patternMatching.ts index 5eba983a0..c943b8e25 100644 --- a/packages/pyright-internal/src/analyzer/patternMatching.ts +++ b/packages/pyright-internal/src/analyzer/patternMatching.ts @@ -29,7 +29,7 @@ import { PatternValueNode, } from '../parser/parseNodes'; import { CodeFlowReferenceExpressionNode } from './codeFlowTypes'; -import { populateTypeVarContextBasedOnExpectedType } from './constraintSolver'; +import { addConstraintsForExpectedType } from './constraintSolver'; import { getTypeVarScopesForNode, isMatchingExpression } from './parseTreeUtils'; import { EvaluatorFlags, TypeEvaluator, TypeResult } from './typeEvaluatorTypes'; import { @@ -685,7 +685,7 @@ function narrowTypeBasedOnClassPattern( // specialize it with Unknown type arguments. if (isClass(exprType) && !exprType.typeAliasInfo) { exprType = ClassType.cloneRemoveTypePromotions(exprType); - exprType = specializeWithUnknownTypeArgs(exprType); + exprType = specializeWithUnknownTypeArgs(exprType, evaluator.getTupleClassType()); } // Are there any positional arguments? If so, try to get the mappings for @@ -921,7 +921,7 @@ function narrowTypeBasedOnClassPattern( const matchTypeInstance = ClassType.cloneAsInstance(unspecializedMatchType); if ( - populateTypeVarContextBasedOnExpectedType( + addConstraintsForExpectedType( evaluator, matchTypeInstance, subjectSubtypeExpanded, @@ -932,6 +932,7 @@ function narrowTypeBasedOnClassPattern( ) { resultType = applySolvedTypeVars(matchTypeInstance, typeVarContext, { unknownIfNotFound: true, + tupleClassType: evaluator.getTupleClassType(), }) as ClassType; } } @@ -1454,7 +1455,7 @@ function getSequencePatternInfo( if (sequenceType && isInstantiableClass(sequenceType)) { const sequenceTypeVarContext = new TypeVarContext(getTypeVarScopeId(sequenceType)); if ( - populateTypeVarContextBasedOnExpectedType( + addConstraintsForExpectedType( evaluator, ClassType.cloneAsInstance(sequenceType), subtype, diff --git a/packages/pyright-internal/src/analyzer/protocols.ts b/packages/pyright-internal/src/analyzer/protocols.ts index 719de991e..867aeb740 100644 --- a/packages/pyright-internal/src/analyzer/protocols.ts +++ b/packages/pyright-internal/src/analyzer/protocols.ts @@ -102,7 +102,7 @@ export function assignClassToProtocol( // If the caller has provided a destination type var context, // we can't use the cached value unless the dest has no type // parameters to solve. - if (!destTypeVarContext || destType.details.typeParameters.length === 0) { + if (!destTypeVarContext || !requiresSpecialization(destType)) { return true; } } diff --git a/packages/pyright-internal/src/analyzer/service.ts b/packages/pyright-internal/src/analyzer/service.ts index 7483894d4..473e6430a 100644 --- a/packages/pyright-internal/src/analyzer/service.ts +++ b/packages/pyright-internal/src/analyzer/service.ts @@ -643,7 +643,7 @@ export class AnalyzerService { const configs = this._getExtendedConfigurations(configFilePath ?? pyprojectFilePath); - if (configs) { + if (configs && configs.length > 0) { for (const config of configs) { configOptions.initializeFromJson( config.configFileJsonObj, diff --git a/packages/pyright-internal/src/analyzer/typeEvaluator.ts b/packages/pyright-internal/src/analyzer/typeEvaluator.ts index 1ce5281dd..ce703dc28 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluator.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluator.ts @@ -97,7 +97,7 @@ import { isCodeFlowSupportedForReference, wildcardImportReferenceKey, } from './codeFlowTypes'; -import { assignTypeToTypeVar, populateTypeVarContextBasedOnExpectedType, updateTypeVarType } from './constraintSolver'; +import { addConstraintsForExpectedType, assignTypeToTypeVar, updateTypeVarType } from './constraintSolver'; import { createFunctionFromConstructor, getBoundInitMethod, @@ -1266,7 +1266,7 @@ export function createTypeEvaluator( } case ParseNodeType.AssignmentExpression: { - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { addError(LocMessage.walrusNotAllowed(), node); } @@ -1294,7 +1294,7 @@ export function createTypeEvaluator( typeResult = getTypeOfExpression( node.typeAnnotation, EvaluatorFlags.ExpectingInstantiableType | - EvaluatorFlags.ExpectingTypeAnnotation | + EvaluatorFlags.ExpectingTypeExpression | EvaluatorFlags.EvaluateStringLiteralAsType | EvaluatorFlags.DisallowParamSpec | EvaluatorFlags.DisallowTypeVarTuple | @@ -1337,7 +1337,7 @@ export function createTypeEvaluator( // If this is a PEP 695 type alias, remove the special form so the type // printer prints it as its aliased type rather than TypeAliasType. - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { if (typeResult.type.specialForm && ClassType.isBuiltIn(typeResult.type.specialForm, 'TypeAliasType')) { typeResult.type = TypeBase.cloneAsSpecialForm(typeResult.type, undefined); } @@ -1404,7 +1404,7 @@ export function createTypeEvaluator( } function getTypeOfAwaitOperator(node: AwaitNode, flags: EvaluatorFlags, inferenceContext?: InferenceContext) { - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { addError(LocMessage.awaitNotAllowed(), node); return { type: UnknownType.create() }; } @@ -1484,7 +1484,7 @@ export function createTypeEvaluator( ClassType.isBuiltIn(iterType, 'tuple') ) { typeResult = { type: ClassType.cloneForUnpacked(iterType) }; - } else if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + } else if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { addError(LocMessage.unpackInAnnotation(), node, node.starToken); typeResult = { type: UnknownType.create() }; } else { @@ -1726,7 +1726,7 @@ export function createTypeEvaluator( let evaluatorFlags = EvaluatorFlags.ExpectingInstantiableType | - EvaluatorFlags.ExpectingTypeAnnotation | + EvaluatorFlags.ExpectingTypeExpression | EvaluatorFlags.ConvertEllipsisToAny | EvaluatorFlags.EvaluateStringLiteralAsType; @@ -4411,7 +4411,7 @@ export function createTypeEvaluator( node, name, !allowForwardReferences, - allowForwardReferences && (flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0 + allowForwardReferences && (flags & EvaluatorFlags.ExpectingTypeExpression) !== 0 ); if (!symbolWithScope) { @@ -4424,7 +4424,7 @@ export function createTypeEvaluator( alias, alias.value, !allowForwardReferences, - allowForwardReferences && (flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0 + allowForwardReferences && (flags & EvaluatorFlags.ExpectingTypeExpression) !== 0 ); } } @@ -4517,7 +4517,7 @@ export function createTypeEvaluator( const codeFlowTypeResult = getFlowTypeOfReference(node, /* startNode */ undefined, { targetSymbolId: symbol.id, typeAtStart: { type: typeAtStart, isIncomplete: isTypeAtStartIncomplete }, - skipConditionalNarrowing: (flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0, + skipConditionalNarrowing: (flags & EvaluatorFlags.ExpectingTypeExpression) !== 0, }); if (codeFlowTypeResult.type) { @@ -4532,7 +4532,7 @@ export function createTypeEvaluator( // Detect, report, and fill in missing type arguments if appropriate. type = reportMissingTypeArguments(node, type, flags); - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { // Verify that the name does not refer to a (non type alias) variable. if (effectiveTypeInfo.includesVariableDecl && !type.typeAliasInfo) { let isAllowedTypeForVariable = isTypeVar(type) || isTypeAliasPlaceholder(type); @@ -4593,7 +4593,7 @@ export function createTypeEvaluator( type = convertTypeVarToRuntimeInstance(node, type, flags); - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) === 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) === 0) { reportUseOfTypeCheckOnly(type, node); } @@ -4926,7 +4926,10 @@ export function createTypeEvaluator( let defaultType: Type; if (param.details.isDefaultExplicit || param.details.isParamSpec) { - defaultType = applySolvedTypeVars(param, typeVarContext, { unknownIfNotFound: true }); + defaultType = applySolvedTypeVars(param, typeVarContext, { + unknownIfNotFound: true, + tupleClassType: getTupleClassType(), + }); } else if (param.details.isVariadic && tupleClass && isInstantiableClass(tupleClass)) { defaultType = makeTupleObject( [{ type: UnknownType.create(), isUnbounded: true }], @@ -4951,7 +4954,10 @@ export function createTypeEvaluator( } type = TypeBase.cloneForTypeAlias( - applySolvedTypeVars(type, typeVarContext, { unknownIfNotFound: true }), + applySolvedTypeVars(type, typeVarContext, { + unknownIfNotFound: true, + tupleClassType: getTupleClassType(), + }), type.typeAliasInfo.name, type.typeAliasInfo.fullName, type.typeAliasInfo.moduleName, @@ -5088,7 +5094,7 @@ export function createTypeEvaluator( let leftExprFlags = EvaluatorFlags.MemberAccessBaseDefaults; leftExprFlags |= flags & - (EvaluatorFlags.ExpectingTypeAnnotation | + (EvaluatorFlags.ExpectingTypeExpression | EvaluatorFlags.VariableTypeAnnotation | EvaluatorFlags.AllowForwardReferences | EvaluatorFlags.NotParsedByInterpreter | @@ -5155,7 +5161,7 @@ export function createTypeEvaluator( const codeFlowTypeResult = getFlowTypeOfReference(node, /* startNode */ undefined, { targetSymbolId: indeterminateSymbolId, typeAtStart: { type: typeAtStart, isIncomplete: isTypeAtStartIncomplete }, - skipConditionalNarrowing: (flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0, + skipConditionalNarrowing: (flags & EvaluatorFlags.ExpectingTypeExpression) !== 0, }); if (codeFlowTypeResult.type) { @@ -5288,7 +5294,7 @@ export function createTypeEvaluator( } // It's illegal to reference a member from a type variable. - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { if (!isIncomplete) { addDiagnostic( DiagnosticRule.reportGeneralTypeIssues, @@ -5632,7 +5638,7 @@ export function createTypeEvaluator( type = isFunctionRule ? AnyType.create() : UnknownType.create(); } - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) === 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) === 0) { reportUseOfTypeCheckOnly(type, node.memberName); } @@ -6515,7 +6521,7 @@ export function createTypeEvaluator( type: indexTypeResult.type, isIncomplete: !!baseTypeResult.isIncomplete || !!indexTypeResult.isIncomplete, }, - skipConditionalNarrowing: (flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0, + skipConditionalNarrowing: (flags & EvaluatorFlags.ExpectingTypeExpression) !== 0, }); if (codeFlowTypeResult.type) { @@ -6855,7 +6861,10 @@ export function createTypeEvaluator( if (index < typeArgs.length) { typeArgType = convertToInstance(typeArgs[index].type); } else if (param.details.isDefaultExplicit) { - typeArgType = applySolvedTypeVars(param, typeVarContext, { unknownIfNotFound: true }); + typeArgType = applySolvedTypeVars(param, typeVarContext, { + unknownIfNotFound: true, + tupleClassType: getTupleClassType(), + }); } else { typeArgType = UnknownType.create(); } @@ -7018,7 +7027,7 @@ export function createTypeEvaluator( getIndexAccessMagicMethodName(usage) ); - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { // If the class doesn't derive from Generic, a type argument should not be allowed. addDiagnostic( DiagnosticRule.reportInvalidTypeArguments, @@ -7059,7 +7068,7 @@ export function createTypeEvaluator( // Special-case InitVar, used in dataclasses. const typeArgs = getTypeArgs(node, flags); - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { if ((flags & EvaluatorFlags.VariableTypeAnnotation) === 0) { addError(LocMessage.initVarNotAllowed(), node.baseExpression); } @@ -7743,7 +7752,7 @@ export function createTypeEvaluator( signatureTracker: UniqueSignatureTracker | undefined ): TypeResult { if ( - (flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0 && + (flags & EvaluatorFlags.ExpectingTypeExpression) !== 0 && node.parent?.nodeType !== ParseNodeType.Argument ) { // This is allowed inside of an index trailer, specifically @@ -7769,7 +7778,7 @@ export function createTypeEvaluator( } flags &= ~( - EvaluatorFlags.ExpectingTypeAnnotation | + EvaluatorFlags.ExpectingTypeExpression | EvaluatorFlags.EvaluateStringLiteralAsType | EvaluatorFlags.ExpectingInstantiableType ); @@ -7872,7 +7881,7 @@ export function createTypeEvaluator( } else { const tupleTypeVarContext = new TypeVarContext(getTypeVarScopeId(tupleClass)); if ( - !populateTypeVarContextBasedOnExpectedType( + !addConstraintsForExpectedType( evaluatorInterface, ClassType.cloneAsInstance(tupleClass), inferenceContext.expectedType, @@ -8001,7 +8010,7 @@ export function createTypeEvaluator( // allowed, and it's a common mistake, so we want to emit a diagnostic // that guides the user to the right solution. if ( - (flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0 && + (flags & EvaluatorFlags.ExpectingTypeExpression) !== 0 && node.leftExpression.nodeType === ParseNodeType.Name && node.leftExpression.value === 'type' ) { @@ -8129,7 +8138,7 @@ export function createTypeEvaluator( } } - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { addDiagnostic(DiagnosticRule.reportInvalidTypeForm, LocMessage.typeAnnotationCall(), node); typeResult = { type: UnknownType.create() }; @@ -11316,7 +11325,7 @@ export function createTypeEvaluator( if (isClassInstance(effectiveExpectedType) && !isTypeSame(effectiveReturnType, effectiveExpectedType)) { const tempTypeVarContext = new TypeVarContext(getTypeVarScopeId(effectiveReturnType)); if ( - populateTypeVarContextBasedOnExpectedType( + addConstraintsForExpectedType( evaluatorInterface, effectiveReturnType, effectiveExpectedType, @@ -11333,6 +11342,7 @@ export function createTypeEvaluator( effectiveExpectedType = applySolvedTypeVars(genericReturnType, tempTypeVarContext, { unknownIfNotFound: true, + tupleClassType: getTupleClassType(), }); effectiveFlags |= AssignTypeFlags.SkipPopulateUnknownExpectedType; @@ -11633,6 +11643,7 @@ export function createTypeEvaluator( let specializedReturnType = applySolvedTypeVars(returnType, typeVarContext, { unknownIfNotFound, + tupleClassType: getTupleClassType(), unknownExemptTypeVars: getUnknownExemptTypeVarsForReturnType(type, returnType), eliminateUnsolvedInUnions, applyInScopePlaceholders: true, @@ -12067,7 +12078,7 @@ export function createTypeEvaluator( EvaluatorFlags.DisallowTypeVarTuple | EvaluatorFlags.DisallowFinal | EvaluatorFlags.DoNotSpecialize - : EvaluatorFlags.DoNotSpecialize | EvaluatorFlags.DisallowFinal; + : EvaluatorFlags.DisallowFinal | EvaluatorFlags.DoNotSpecialize; const exprTypeResult = getTypeOfExpression( argParam.argument.valueExpression, flags, @@ -12516,6 +12527,7 @@ export function createTypeEvaluator( const concreteDefaultType = makeTopLevelTypeVarsConcrete( applySolvedTypeVars(typeVar.details.defaultType, typeVarContext, { unknownIfNotFound: true, + tupleClassType: getTupleClassType(), }) ); @@ -13006,14 +13018,12 @@ export function createTypeEvaluator( ); } - let classFlags = baseClass.details.flags & ~(ClassTypeFlags.BuiltInClass | ClassTypeFlags.SpecialBuiltIn); - classFlags |= ClassTypeFlags.Final | ClassTypeFlags.NewTypeClass | ClassTypeFlags.ValidTypeAliasClass; const classType = ClassType.createInstantiable( className, ParseTreeUtils.getClassFullName(errorNode, fileInfo.moduleName, className), fileInfo.moduleName, fileInfo.fileUri, - classFlags, + ClassTypeFlags.Final | ClassTypeFlags.NewTypeClass | ClassTypeFlags.ValidTypeAliasClass, ParseTreeUtils.getTypeSourceId(errorNode), /* declaredMetaclass */ undefined, baseClass.details.effectiveMetaclass @@ -13255,7 +13265,7 @@ export function createTypeEvaluator( inferenceContext: InferenceContext | undefined ): TypeResult { if ( - (flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0 && + (flags & EvaluatorFlags.ExpectingTypeExpression) !== 0 && node.parent?.nodeType !== ParseNodeType.Argument ) { const diag = new DiagnosticAddendum(); @@ -13397,7 +13407,7 @@ export function createTypeEvaluator( const dictTypeVarContext = new TypeVarContext(getTypeVarScopeId(builtInDict)); if ( - !populateTypeVarContextBasedOnExpectedType( + !addConstraintsForExpectedType( evaluatorInterface, builtInDict, inferenceContext.expectedType, @@ -13575,7 +13585,7 @@ export function createTypeEvaluator( const keyFlags = flags & ~( - EvaluatorFlags.ExpectingTypeAnnotation | + EvaluatorFlags.ExpectingTypeExpression | EvaluatorFlags.EvaluateStringLiteralAsType | EvaluatorFlags.ExpectingInstantiableType ); @@ -13837,7 +13847,7 @@ export function createTypeEvaluator( inferenceContext: InferenceContext | undefined ): TypeResult { if ( - (flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0 && + (flags & EvaluatorFlags.ExpectingTypeExpression) !== 0 && node.nodeType === ParseNodeType.List && node.parent?.nodeType !== ParseNodeType.Argument ) { @@ -13847,7 +13857,7 @@ export function createTypeEvaluator( } flags &= ~( - EvaluatorFlags.ExpectingTypeAnnotation | + EvaluatorFlags.ExpectingTypeExpression | EvaluatorFlags.EvaluateStringLiteralAsType | EvaluatorFlags.ExpectingInstantiableType ); @@ -14016,7 +14026,7 @@ export function createTypeEvaluator( const typeVarContext = new TypeVarContext(getTypeVarScopeId(expectedClassType)); if ( - !populateTypeVarContextBasedOnExpectedType( + !addConstraintsForExpectedType( evaluatorInterface, ClassType.cloneAsInstance(expectedClassType), inferenceContext.expectedType, @@ -14921,7 +14931,7 @@ export function createTypeEvaluator( // If no type arguments are provided, the resulting type // depends on whether we're evaluating a type annotation or // we're in some other context. - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { addError(LocMessage.optionalExtraArgs(), errorNode); return UnknownType.create(); } @@ -15139,7 +15149,7 @@ export function createTypeEvaluator( // depends on whether we're evaluating a type annotation or // we're in some other context. if (!typeArgs) { - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { addError(LocMessage.typeGuardArgCount(), errorNode); } @@ -15184,7 +15194,7 @@ export function createTypeEvaluator( const enclosingClassTypeResult = enclosingClass ? getTypeOfClass(enclosingClass) : undefined; if (!enclosingClassTypeResult) { - if ((flags & (EvaluatorFlags.ExpectingTypeAnnotation | EvaluatorFlags.ExpectingInstantiableType)) !== 0) { + if ((flags & (EvaluatorFlags.ExpectingTypeExpression | EvaluatorFlags.ExpectingInstantiableType)) !== 0) { addDiagnostic(DiagnosticRule.reportGeneralTypeIssues, LocMessage.selfTypeContext(), errorNode); } @@ -15246,7 +15256,7 @@ export function createTypeEvaluator( // If no type arguments are provided, the resulting type // depends on whether we're evaluating a type annotation or // we're in some other context. - if (!typeArgs && (flags & EvaluatorFlags.ExpectingTypeAnnotation) === 0) { + if (!typeArgs && (flags & EvaluatorFlags.ExpectingTypeExpression) === 0) { return { type: classType }; } @@ -15330,7 +15340,7 @@ export function createTypeEvaluator( // If no type arguments are provided, the resulting type // depends on whether we're evaluating a type annotation or // we're in some other context. - if (!typeArgs && (flags & EvaluatorFlags.ExpectingTypeAnnotation) === 0) { + if (!typeArgs && (flags & EvaluatorFlags.ExpectingTypeExpression) === 0) { return classType; } @@ -15654,7 +15664,7 @@ export function createTypeEvaluator( // If no type arguments are provided, the resulting type // depends on whether we're evaluating a type annotation or // we're in some other context. - if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { + if ((flags & EvaluatorFlags.ExpectingTypeExpression) !== 0) { addError(LocMessage.unionTypeArgCount(), errorNode); return NeverType.createNever(); } @@ -15741,7 +15751,7 @@ export function createTypeEvaluator( // If no type arguments are provided, the resulting type // depends on whether we're evaluating a type annotation or // we're in some other context. - if ((flags & (EvaluatorFlags.ExpectingTypeAnnotation | EvaluatorFlags.DisallowNakedGeneric)) !== 0) { + if ((flags & (EvaluatorFlags.ExpectingTypeExpression | EvaluatorFlags.DisallowNakedGeneric)) !== 0) { addError(LocMessage.genericTypeArgMissing(), errorNode); } @@ -16113,19 +16123,8 @@ export function createTypeEvaluator( flags |= EvaluatorFlags.DoNotSpecialize; } - if (isDeclaredTypeAlias(node.leftExpression)) { - flags |= - EvaluatorFlags.ExpectingInstantiableType | - EvaluatorFlags.ExpectingTypeAnnotation | - EvaluatorFlags.EvaluateStringLiteralAsType | - EvaluatorFlags.DisallowParamSpec | - EvaluatorFlags.DisallowTypeVarTuple | - EvaluatorFlags.DisallowClassVar; - flags &= ~EvaluatorFlags.DoNotSpecialize; - } - // Is this type already cached? - let rightHandType = readTypeCache(node.rightExpression, flags); + let rightHandType = readTypeCache(node.rightExpression, /* flags */ undefined); let isIncomplete = false; let expectedTypeDiagAddendum: DiagnosticAddendum | undefined; @@ -16138,76 +16137,118 @@ export function createTypeEvaluator( writeTypeCache(node.rightExpression, { type: rightHandType }, EvaluatorFlags.None); } } + } - if (!rightHandType) { - // Determine whether there is a declared type. - const declaredType = getDeclaredTypeForExpression(node.leftExpression, { - method: 'set', - }); + if (!rightHandType) { + // Determine whether there is a declared type. + const declaredType = getDeclaredTypeForExpression(node.leftExpression, { method: 'set' }); - let typeAliasNameNode: NameNode | undefined; - let isSpeculativeTypeAlias = false; + let typeAliasNameNode: NameNode | undefined; + let isSpeculativeTypeAlias = false; + let typeAliasPlaceholder: TypeVarType | undefined; - if (isDeclaredTypeAlias(node.leftExpression)) { - typeAliasNameNode = (node.leftExpression as TypeAnnotationNode).valueExpression as NameNode; + if (isDeclaredTypeAlias(node.leftExpression)) { + flags = + EvaluatorFlags.ExpectingInstantiableType | + EvaluatorFlags.ExpectingTypeExpression | + EvaluatorFlags.EvaluateStringLiteralAsType | + EvaluatorFlags.DisallowParamSpec | + EvaluatorFlags.DisallowTypeVarTuple | + EvaluatorFlags.DisallowClassVar; - if (!isLegalTypeAliasExpressionForm(node.rightExpression)) { - addDiagnostic( - DiagnosticRule.reportInvalidTypeForm, - LocMessage.typeAliasIllegalExpressionForm(), - node.rightExpression - ); - } - } else if (node.leftExpression.nodeType === ParseNodeType.Name) { - const symbolWithScope = lookUpSymbolRecursive( - node.leftExpression, - node.leftExpression.value, - /* honorCodeFlow */ false + typeAliasNameNode = (node.leftExpression as TypeAnnotationNode).valueExpression as NameNode; + + if (!isLegalTypeAliasExpressionForm(node.rightExpression)) { + addDiagnostic( + DiagnosticRule.reportInvalidTypeForm, + LocMessage.typeAliasIllegalExpressionForm(), + node.rightExpression ); - if (symbolWithScope) { - const decls = symbolWithScope.symbol.getDeclarations(); - if (decls.length === 1 && isPossibleTypeAliasOrTypedDict(decls[0])) { + } + } else if (node.leftExpression.nodeType === ParseNodeType.Name) { + const symbolWithScope = lookUpSymbolRecursive( + node.leftExpression, + node.leftExpression.value, + /* honorCodeFlow */ false + ); + + if (symbolWithScope) { + const decls = symbolWithScope.symbol.getDeclarations(); + + if (decls.length === 1) { + if (isPossibleTypeAliasDeclaration(decls[0])) { typeAliasNameNode = node.leftExpression; isSpeculativeTypeAlias = true; + } else if (isPossibleTypeDictFactoryCall(decls[0])) { + // Handle calls to TypedDict factory functions like type + // aliases to support recursive field type definitions. + typeAliasNameNode = node.leftExpression; } } } + } - // Synthesize a type variable that represents the type alias while we're - // evaluating it. This allows us to handle recursive definitions. - let typeAliasTypeVar: TypeVarType | undefined; - if (typeAliasNameNode) { - typeAliasTypeVar = TypeVarType.createInstantiable(`__type_alias_${typeAliasNameNode.value}`); - typeAliasTypeVar.details.isSynthesized = true; - typeAliasTypeVar.details.recursiveTypeAliasName = typeAliasNameNode.value; - const scopeId = ParseTreeUtils.getScopeIdForNode(typeAliasNameNode); - typeAliasTypeVar.details.recursiveTypeAliasScopeId = scopeId; - typeAliasTypeVar.details.recursiveTypeAliasIsPep695Syntax = false; - typeAliasTypeVar.scopeId = scopeId; + if (typeAliasNameNode) { + typeAliasPlaceholder = synthesizeTypeAliasPlaceholder(typeAliasNameNode); - // Write the type back to the type cache. It will be replaced below. - writeTypeCache(node, { type: typeAliasTypeVar }, /* flags */ undefined); - writeTypeCache(node.leftExpression, { type: typeAliasTypeVar }, /* flags */ undefined); - if (node.leftExpression.nodeType === ParseNodeType.TypeAnnotation) { - writeTypeCache( - node.leftExpression.valueExpression, - { type: typeAliasTypeVar }, - /* flags */ undefined - ); - } + writeTypeCache(node, { type: typeAliasPlaceholder }, /* flags */ undefined); + writeTypeCache(node.leftExpression, { type: typeAliasPlaceholder }, /* flags */ undefined); + + if (node.leftExpression.nodeType === ParseNodeType.TypeAnnotation) { + writeTypeCache( + node.leftExpression.valueExpression, + { type: typeAliasPlaceholder }, + /* flags */ undefined + ); } + } - const srcTypeResult = getTypeOfExpression( - node.rightExpression, - flags, - makeInferenceContext(declaredType) + const srcTypeResult = getTypeOfExpression(node.rightExpression, flags, makeInferenceContext(declaredType)); + + rightHandType = srcTypeResult.type; + expectedTypeDiagAddendum = srcTypeResult.expectedTypeDiagAddendum; + if (srcTypeResult.isIncomplete) { + isIncomplete = true; + } + + // If this was a speculative type alias, it becomes a real type alias + // only if the evaluated type is an instantiable type. + if (isSpeculativeTypeAlias && !isLegalImplicitTypeAliasType(rightHandType)) { + typeAliasNameNode = undefined; + } + + if (typeAliasNameNode) { + assert(typeAliasPlaceholder !== undefined); + + // If this is a type alias, record its name based on the assignment target. + rightHandType = transformTypeForTypeAlias( + rightHandType, + typeAliasNameNode, + typeAliasNameNode, + /* isPep695Syntax */ false, + /* isPep695TypeVarType */ false ); - let srcType = srcTypeResult.type; - expectedTypeDiagAddendum = srcTypeResult.expectedTypeDiagAddendum; - if (srcTypeResult.isIncomplete) { - isIncomplete = true; + + if (isTypeAliasRecursive(typeAliasPlaceholder, rightHandType)) { + addDiagnostic( + DiagnosticRule.reportGeneralTypeIssues, + LocMessage.typeAliasIsRecursiveDirect().format({ + name: typeAliasNameNode.value, + }), + node.rightExpression + ); + + rightHandType = UnknownType.create(); } + // Set the resulting type to the boundType of the original type alias + // to support recursive type aliases. + typeAliasPlaceholder.details.boundType = rightHandType; + + // Record the type parameters within the recursive type alias so it + // can be specialized. + typeAliasPlaceholder.details.recursiveTypeParameters = rightHandType.typeAliasInfo?.typeParameters; + } else { // If the RHS is a constant boolean expression, assign it a literal type. const constExprValue = evaluateStaticBoolExpression( node.rightExpression, @@ -16218,46 +16259,7 @@ export function createTypeEvaluator( if (constExprValue !== undefined) { const boolType = getBuiltInObject(node, 'bool'); if (isClassInstance(boolType)) { - srcType = ClassType.cloneWithLiteral(boolType, constExprValue); - } - } - - // If this is an enum, transform the type as required. - rightHandType = srcType; - - if (typeAliasNameNode) { - // If this was a speculative type alias, it becomes a real type alias - // only if the evaluated type is an instantiable type. - if (!isSpeculativeTypeAlias || isLegalImplicitTypeAliasType(rightHandType)) { - // If this is a type alias, record its name based on the assignment target. - rightHandType = transformTypeForTypeAlias( - rightHandType, - typeAliasNameNode, - typeAliasNameNode, - /* isPep695Syntax */ false, - /* isPep695TypeVarType */ false - ); - - assert(typeAliasTypeVar !== undefined); - if (isTypeAliasRecursive(typeAliasTypeVar, rightHandType)) { - addDiagnostic( - DiagnosticRule.reportGeneralTypeIssues, - LocMessage.typeAliasIsRecursiveDirect().format({ - name: typeAliasNameNode.value, - }), - node.rightExpression - ); - - rightHandType = UnknownType.create(); - } - - // Set the resulting type to the boundType of the original type alias - // to support recursive type aliases. - typeAliasTypeVar.details.boundType = rightHandType; - - // Record the type parameters within the recursive type alias so it - // can be specialized. - typeAliasTypeVar.details.recursiveTypeParameters = rightHandType.typeAliasInfo?.typeParameters; + rightHandType = ClassType.cloneWithLiteral(boolType, constExprValue); } } } @@ -16275,39 +16277,18 @@ export function createTypeEvaluator( writeTypeCache(node, { type: rightHandType, isIncomplete }, EvaluatorFlags.None); } - function isPossibleTypeAliasOrTypedDict(decl: Declaration) { - if (isPossibleTypeAliasDeclaration(decl)) { - return true; - } + // Synthesize a TypeVar that acts as a placeholder for a type alias. This allows + // the type alias definition to refer to itself. + function synthesizeTypeAliasPlaceholder(nameNode: NameNode): TypeVarType { + const placeholder = TypeVarType.createInstantiable(`__type_alias_${nameNode.value}`); + placeholder.details.isSynthesized = true; + placeholder.details.recursiveTypeAliasName = nameNode.value; + const scopeId = ParseTreeUtils.getScopeIdForNode(nameNode); + placeholder.details.recursiveTypeAliasScopeId = scopeId; + placeholder.details.recursiveTypeAliasIsPep695Syntax = false; + placeholder.scopeId = scopeId; - if ( - decl.type === DeclarationType.Variable && - decl.node.parent && - decl.node.parent.nodeType === ParseNodeType.Assignment && - decl.node.parent.rightExpression?.nodeType === ParseNodeType.Call - ) { - const callLeftNode = decl.node.parent.rightExpression.leftExpression; - - // Use a simple heuristic to determine whether this is potentially - // a call to the TypedDict call. This avoids the expensive (and potentially - // recursive) call to getTypeOfExpression in cases where it's not needed. - if ( - (callLeftNode.nodeType === ParseNodeType.Name && callLeftNode.value) === 'TypedDict' || - (callLeftNode.nodeType === ParseNodeType.MemberAccess && - callLeftNode.memberName.value === 'TypedDict' && - callLeftNode.leftExpression.nodeType === ParseNodeType.Name) - ) { - // See if this is a call to TypedDict. We want to support - // recursive type references in a TypedDict call. - const callType = getTypeOfExpression(callLeftNode, EvaluatorFlags.CallBaseDefaults).type; - - if (isInstantiableClass(callType) && ClassType.isBuiltIn(callType, 'TypedDict')) { - return true; - } - } - } - - return false; + return placeholder; } // Evaluates the type of a type alias (i.e. "type") statement. This code @@ -16346,15 +16327,9 @@ export function createTypeEvaluator( // Synthesize a type variable that represents the type alias while we're // evaluating it. This allows us to handle recursive definitions. - const typeAliasTypeVar = TypeVarType.createInstantiable(`__type_alias_${nameNode.value}`); - typeAliasTypeVar.details.isSynthesized = true; - typeAliasTypeVar.details.recursiveTypeAliasName = nameNode.value; - const scopeId = ParseTreeUtils.getScopeIdForNode(nameNode); - typeAliasTypeVar.details.recursiveTypeAliasScopeId = scopeId; - typeAliasTypeVar.details.recursiveTypeAliasIsPep695Syntax = isPep695Syntax; - typeAliasTypeVar.scopeId = scopeId; + const typeAliasTypeVar = synthesizeTypeAliasPlaceholder(nameNode); - // Write the type to the type cache. It will be replaced below. + // Write the type to the type cache to support recursive type alias definitions. writeTypeCache(nameNode, { type: typeAliasTypeVar }, /* flags */ undefined); // Set a partial type to handle recursive (self-referential) type aliases. @@ -18340,6 +18315,7 @@ export function createTypeEvaluator( // Replace any unsolved TypeVars with Unknown (including all function-scoped TypeVars). inferredParamType = applySolvedTypeVars(inferredParamType, typeVarContext, { unknownIfNotFound: true, + tupleClassType: getTupleClassType(), }); } @@ -18764,6 +18740,11 @@ export function createTypeEvaluator( return false; } + const statements = functionDecl.node.suite.statements; + if (statements.some((statement) => statement.nodeType !== ParseNodeType.StatementList)) { + return false; + } + for (const raiseStatement of functionDecl.raiseStatements) { if (!raiseStatement.typeExpression || raiseStatement.valueExpression) { return false; @@ -19494,6 +19475,16 @@ export function createTypeEvaluator( continue; } + // Forward-declared type annotation expressions need to be be evaluated + // in context so they have the appropriate flags set. Most of these cases + // will have been detected above when calling getParentAnnotationNode, + // but TypeAlias expressions are not handled there. + const stringEnclosure = ParseTreeUtils.getParentNodeOfType(parent, ParseNodeType.StringList); + if (stringEnclosure) { + nodeToEvaluate = stringEnclosure as StringListNode; + continue; + } + // The left expression of a call or member access expression is not generally contextual. if (parent.nodeType === ParseNodeType.Call || parent.nodeType === ParseNodeType.MemberAccess) { if (nodeToEvaluate === parent.leftExpression) { @@ -19520,15 +19511,7 @@ export function createTypeEvaluator( // The base expression of an index expression is not contextual. if (nodeToEvaluate === parent.baseExpression) { flags = EvaluatorFlags.IndexBaseDefaults; - break; } - } else if (parent.nodeType === ParseNodeType.StringList && nodeToEvaluate === parent.typeAnnotation) { - // Forward-declared type annotation expressions need to be be evaluated - // in context so they have the appropriate flags set. Most of these cases - // will have been detected above when calling getParentAnnotationNode, - // but TypeAlias expressions are not handled there. - nodeToEvaluate = parent; - continue; } if (!isExpressionNode(parent)) { @@ -19873,7 +19856,19 @@ export function createTypeEvaluator( // don't bother doing additional work. let cacheEntry = readTypeCacheEntry(subnode); if (cacheEntry && !cacheEntry.typeResult.isIncomplete) { - return cacheEntry.typeResult; + const typeResult = cacheEntry.typeResult; + + // Handle the special case where a function or class is partially evaluated. + // Indicate that these are not complete types. + if (isFunction(typeResult.type) && FunctionType.isPartiallyEvaluated(typeResult.type)) { + return { ...typeResult, isIncomplete: true }; + } + + if (isClass(typeResult.type) && ClassType.isPartiallyEvaluated(typeResult.type)) { + return { ...typeResult, isIncomplete: true }; + } + + return typeResult; } callback(); @@ -20024,7 +20019,7 @@ export function createTypeEvaluator( case 'Protocol': { if ( (flags & - (EvaluatorFlags.DisallowNonTypeSpecialForms | EvaluatorFlags.ExpectingTypeAnnotation)) !== + (EvaluatorFlags.DisallowNonTypeSpecialForms | EvaluatorFlags.ExpectingTypeExpression)) !== 0 ) { addError(LocMessage.protocolNotAllowed(), errorNode); @@ -20049,7 +20044,7 @@ export function createTypeEvaluator( case 'TypedDict': { if ( (flags & - (EvaluatorFlags.DisallowNonTypeSpecialForms | EvaluatorFlags.ExpectingTypeAnnotation)) !== + (EvaluatorFlags.DisallowNonTypeSpecialForms | EvaluatorFlags.ExpectingTypeExpression)) !== 0 ) { addError(LocMessage.typedDictNotAllowed(), errorNode); @@ -20060,7 +20055,7 @@ export function createTypeEvaluator( case 'Literal': { if ( (flags & - (EvaluatorFlags.DisallowNonTypeSpecialForms | EvaluatorFlags.ExpectingTypeAnnotation)) !== + (EvaluatorFlags.DisallowNonTypeSpecialForms | EvaluatorFlags.ExpectingTypeExpression)) !== 0 ) { addError(LocMessage.literalNotAllowed(), errorNode); @@ -20375,7 +20370,10 @@ export function createTypeEvaluator( return; } - const solvedDefaultType = applySolvedTypeVars(typeParam, typeVarContext, { unknownIfNotFound: true }); + const solvedDefaultType = applySolvedTypeVars(typeParam, typeVarContext, { + unknownIfNotFound: true, + tupleClassType: getTupleClassType(), + }); typeArgTypes.push(solvedDefaultType); if (isParamSpec(typeParam)) { typeVarContext.setTypeVarType(typeParam, convertTypeToParamSpecValue(solvedDefaultType)); @@ -20510,7 +20508,7 @@ export function createTypeEvaluator( } if (options?.allowRequired) { - flags |= EvaluatorFlags.AllowRequired | EvaluatorFlags.ExpectingTypeAnnotation; + flags |= EvaluatorFlags.AllowRequired | EvaluatorFlags.ExpectingTypeExpression; } if (options?.allowUnpackedTuple) { @@ -20524,7 +20522,7 @@ export function createTypeEvaluator( } if (options?.enforceTypeAnnotationRules) { - flags |= EvaluatorFlags.ExpectingTypeAnnotation; + flags |= EvaluatorFlags.ExpectingTypeExpression; } if (options?.disallowProtocolAndTypedDict) { @@ -22347,7 +22345,7 @@ export function createTypeEvaluator( getEffectiveTypeOfSymbol(member.symbol), member.classType, /* selfClass */ undefined, - typeClass ?? UnknownType.create() + typeClass && isInstantiableClass(typeClass) ? typeClass : undefined ); } return UnknownType.create(); @@ -25944,7 +25942,7 @@ export function createTypeEvaluator( !assignedType.tupleTypeArguments ) { const typeVarContext = new TypeVarContext(getTypeVarScopeId(assignedType)); - populateTypeVarContextBasedOnExpectedType( + addConstraintsForExpectedType( evaluatorInterface, ClassType.cloneForSpecialization( assignedType, @@ -27118,6 +27116,43 @@ export function createTypeEvaluator( return isLegal; } + function isPossibleTypeAliasOrTypedDict(decl: Declaration) { + return isPossibleTypeAliasDeclaration(decl) || isPossibleTypeDictFactoryCall(decl); + } + + function isPossibleTypeDictFactoryCall(decl: Declaration) { + if ( + decl.type !== DeclarationType.Variable || + !decl.node.parent || + decl.node.parent.nodeType !== ParseNodeType.Assignment || + decl.node.parent.rightExpression?.nodeType !== ParseNodeType.Call + ) { + return false; + } + + const callLeftNode = decl.node.parent.rightExpression.leftExpression; + + // Use a simple heuristic to determine whether this is potentially + // a call to the TypedDict call. This avoids the expensive (and potentially + // recursive) call to getTypeOfExpression in cases where it's not needed. + if ( + (callLeftNode.nodeType === ParseNodeType.Name && callLeftNode.value) === 'TypedDict' || + (callLeftNode.nodeType === ParseNodeType.MemberAccess && + callLeftNode.memberName.value === 'TypedDict' && + callLeftNode.leftExpression.nodeType === ParseNodeType.Name) + ) { + // See if this is a call to TypedDict. We want to support + // recursive type references in a TypedDict call. + const callType = getTypeOfExpression(callLeftNode, EvaluatorFlags.CallBaseDefaults).type; + + if (isInstantiableClass(callType) && ClassType.isBuiltIn(callType, 'TypedDict')) { + return true; + } + } + + return false; + } + function printObjectTypeForClass(type: ClassType): string { return TypePrinter.printObjectTypeForClass( type, diff --git a/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts b/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts index b9b5ff7f6..6975d86a9 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts @@ -86,10 +86,9 @@ export const enum EvaluatorFlags { // than an instance (object) ExpectingInstantiableType = 1 << 7, - // A type annotation restricts the types of expressions that are - // allowed. If this flag is set, illegal type expressions are - // flagged as errors. - ExpectingTypeAnnotation = 1 << 8, + // A type expression imposes grammatical and semantic limits on an + // expression. If this flag is set, illegal type expressions are + ExpectingTypeExpression = 1 << 8, // Suppress the reportMissingTypeArgument diagnostic in this context. AllowMissingTypeArgs = 1 << 9, diff --git a/packages/pyright-internal/src/analyzer/typeGuards.ts b/packages/pyright-internal/src/analyzer/typeGuards.ts index 4c6bf2896..8a19a3829 100644 --- a/packages/pyright-internal/src/analyzer/typeGuards.ts +++ b/packages/pyright-internal/src/analyzer/typeGuards.ts @@ -22,7 +22,7 @@ import { } from '../parser/parseNodes'; import { KeywordType, OperatorType } from '../parser/tokenizerTypes'; import { getFileInfo } from './analyzerNodeInfo'; -import { populateTypeVarContextBasedOnExpectedType } from './constraintSolver'; +import { addConstraintsForExpectedType } from './constraintSolver'; import { Declaration, DeclarationType } from './declaration'; import { transformTypeForEnumMember } from './enums'; import * as ParseTreeUtils from './parseTreeUtils'; @@ -638,7 +638,7 @@ export function getTypeNarrowingCallback( ); const arg1Type = arg1TypeResult.type; - const classTypeList = getIsInstanceClassTypes(arg1Type); + const classTypeList = getIsInstanceClassTypes(evaluator, arg1Type); const isIncomplete = !!callTypeResult.isIncomplete || !!arg1TypeResult.isIncomplete; if (classTypeList) { @@ -1146,7 +1146,10 @@ function narrowTypeForIsEllipsis(evaluator: TypeEvaluator, type: Type, isPositiv // that accepts a single class, and a more complex form that accepts a tuple // of classes (including arbitrarily-nested tuples). This method determines // which form and returns a list of classes or undefined. -function getIsInstanceClassTypes(argType: Type): (ClassType | TypeVarType | FunctionType)[] | undefined { +function getIsInstanceClassTypes( + evaluator: TypeEvaluator, + argType: Type +): (ClassType | TypeVarType | FunctionType)[] | undefined { let foundNonClassType = false; const classTypeList: (ClassType | TypeVarType | FunctionType)[] = []; @@ -1155,7 +1158,7 @@ function getIsInstanceClassTypes(argType: Type): (ClassType | TypeVarType | Func const addClassTypesToList = (types: Type[]) => { types.forEach((subtype) => { if (isClass(subtype)) { - subtype = specializeWithUnknownTypeArgs(subtype); + subtype = specializeWithUnknownTypeArgs(subtype, evaluator.getTupleClassType()); if (isInstantiableClass(subtype) && ClassType.isBuiltIn(subtype, 'Callable')) { subtype = convertToInstantiable(getUnknownTypeForCallable()); @@ -1359,7 +1362,8 @@ function narrowTypeForIsInstanceInternal( concreteFilterType, /* typeArguments */ undefined, /* isTypeArgumentExplicit */ false - ) + ), + evaluator.getTupleClassType() ); } @@ -1451,7 +1455,7 @@ function narrowTypeForIsInstanceInternal( ); if ( - populateTypeVarContextBasedOnExpectedType( + addConstraintsForExpectedType( evaluator, unspecializedFilterType, concreteVarType, @@ -1463,7 +1467,11 @@ function narrowTypeForIsInstanceInternal( specializedFilterType = applySolvedTypeVars( unspecializedFilterType, typeVarContext, - { unknownIfNotFound: true, useUnknownOverDefault: true } + { + unknownIfNotFound: true, + useUnknownOverDefault: true, + tupleClassType: evaluator.getTupleClassType(), + } ) as ClassType; } } @@ -1764,7 +1772,11 @@ function narrowTypeForIsInstanceInternal( const filteredType = evaluator.mapSubtypesExpandTypeVars( expandedTypes, - /* options */ undefined, + { + expandCallback: (type) => { + return evaluator.expandPromotionTypes(errorNode, type); + }, + }, (subtype, unexpandedSubtype) => { // If we fail to filter anything in the negative case, we need to decide // whether to retain the original TypeVar or replace it with its specialized @@ -2459,33 +2471,69 @@ function narrowTypeForClassComparison( isPositiveTest: boolean ): Type { return mapSubtypes(referenceType, (subtype) => { - const concreteSubtype = evaluator.makeTopLevelTypeVarsConcrete(subtype); + let concreteSubtype = evaluator.makeTopLevelTypeVarsConcrete(subtype); if (isPositiveTest) { if (isNoneInstance(concreteSubtype)) { - return undefined; + return isNoneTypeClass(classType) ? classType : undefined; } - if (isClassInstance(concreteSubtype) && TypeBase.isInstance(subtype)) { - if (ClassType.isBuiltIn(concreteSubtype, 'type')) { - return classType; + if ( + isClassInstance(concreteSubtype) && + TypeBase.isInstance(subtype) && + ClassType.isBuiltIn(concreteSubtype, 'type') + ) { + concreteSubtype = + concreteSubtype.typeArguments && concreteSubtype.typeArguments.length > 0 + ? convertToInstantiable(concreteSubtype.typeArguments[0]) + : UnknownType.create(); + } + + if (isAnyOrUnknown(concreteSubtype)) { + return classType; + } + + if (isClass(concreteSubtype)) { + if (TypeBase.isInstance(concreteSubtype)) { + return ClassType.isBuiltIn(concreteSubtype, 'object') ? classType : undefined; } - return undefined; - } + const isSuperType = isIsinstanceFilterSuperclass( + evaluator, + subtype, + concreteSubtype, + classType, + classType, + /* isInstanceCheck */ false + ); - if (isInstantiableClass(concreteSubtype) && ClassType.isFinal(concreteSubtype)) { - if ( - !ClassType.isSameGenericClass(concreteSubtype, classType) && - !isIsinstanceFilterSuperclass( + if (!classType.includeSubclasses) { + // Handle the case where the LHS and RHS operands are specific + // classes, as opposed to types that represent classes and their + // subclasses. + if (!concreteSubtype.includeSubclasses) { + return ClassType.isSameGenericClass(concreteSubtype, classType) ? classType : undefined; + } + + const isSubType = isIsinstanceFilterSubclass( evaluator, - subtype, concreteSubtype, classType, - classType, /* isInstanceCheck */ false - ) - ) { + ); + + if (isSuperType) { + return classType; + } + + if (isSubType) { + return addConditionToType(classType, getTypeCondition(concreteSubtype)); + } + + return undefined; + } + + if (ClassType.isFinal(concreteSubtype) && !isSuperType) { return undefined; } } diff --git a/packages/pyright-internal/src/analyzer/typeUtils.ts b/packages/pyright-internal/src/analyzer/typeUtils.ts index 75de2b068..154af071e 100644 --- a/packages/pyright-internal/src/analyzer/typeUtils.ts +++ b/packages/pyright-internal/src/analyzer/typeUtils.ts @@ -245,12 +245,13 @@ export const enum AssignTypeFlags { } export interface ApplyTypeVarOptions { + typeClassType?: ClassType; + tupleClassType?: ClassType; unknownIfNotFound?: boolean; useUnknownOverDefault?: boolean; unknownExemptTypeVars?: TypeVarType[]; useNarrowBoundOnly?: boolean; eliminateUnsolvedInUnions?: boolean; - typeClassType?: Type; applyInScopePlaceholders?: boolean; } @@ -1073,7 +1074,7 @@ export function specializeWithDefaultTypeArgs(type: ClassType): ClassType { // Specializes the class with "Unknown" type args (or the equivalent for ParamSpecs // or TypeVarTuples). -export function specializeWithUnknownTypeArgs(type: ClassType): ClassType { +export function specializeWithUnknownTypeArgs(type: ClassType, tupleClassType?: ClassType): ClassType { if (type.details.typeParameters.length === 0) { return type; } @@ -1091,18 +1092,22 @@ export function specializeWithUnknownTypeArgs(type: ClassType): ClassType { return ClassType.cloneForSpecialization( type, - type.details.typeParameters.map((param) => getUnknownTypeForTypeVar(param)), + type.details.typeParameters.map((param) => getUnknownTypeForTypeVar(param, tupleClassType)), /* isTypeArgumentExplicit */ false, /* includeSubclasses */ type.includeSubclasses ); } // Returns "Unknown" for simple TypeVars or the equivalent for a ParamSpec. -export function getUnknownTypeForTypeVar(typeVar: TypeVarType): Type { +export function getUnknownTypeForTypeVar(typeVar: TypeVarType, tupleClassType?: ClassType): Type { if (typeVar.details.isParamSpec) { return getUnknownTypeForParamSpec(); } + if (typeVar.details.isVariadic && tupleClassType) { + return getUnknownTypeForVariadicTypeVar(tupleClassType); + } + return UnknownType.create(); } @@ -1118,6 +1123,19 @@ export function getUnknownTypeForParamSpec(): FunctionType { return newFunction; } +export function getUnknownTypeForVariadicTypeVar(tupleClassType: ClassType): Type { + assert(isInstantiableClass(tupleClassType) && ClassType.isBuiltIn(tupleClassType, 'tuple')); + + return ClassType.cloneAsInstance( + specializeTupleClass( + tupleClassType, + [{ type: UnknownType.create(), isUnbounded: true }], + /* isTypeArgumentExplicit */ true, + /* isUnpackedTuple */ true + ) + ); +} + // Returns the equivalent of "Callable[..., Unknown]". export function getUnknownTypeForCallable(): FunctionType { const newFunction = FunctionType.createSynthesizedInstance('', FunctionTypeFlags.GradualCallableForm); @@ -1374,7 +1392,7 @@ export function partiallySpecializeType( type: Type, contextClassType: ClassType, selfClass?: ClassType | TypeVarType, - typeClassType?: Type + typeClassType?: ClassType ): Type { // If the context class is not specialized (or doesn't need specialization), // then there's no need to do any more work. @@ -3115,7 +3133,7 @@ export function computeMroLinearization(classType: ClassType): boolean { // The first class in the MRO is the class itself. const typeVarContext = buildTypeVarContextFromSpecializedClass(classType); let specializedClassType = applySolvedTypeVars(classType, typeVarContext); - if (!isClass(specializedClassType) && !isAny(specializedClassType) && !isUnknown(specializedClassType)) { + if (!isClass(specializedClassType) && !isAnyOrUnknown(specializedClassType)) { specializedClassType = UnknownType.create(); } @@ -3159,11 +3177,16 @@ export function computeMroLinearization(classType: ClassType): boolean { if (!isInstantiableClass(classList[0])) { foundValidHead = true; - assert(isClass(classList[0]) || isAnyOrUnknown(classList[0])); - classType.details.mro.push(classList[0]); + let head = classList[0]; + if (!isClass(head) && !isAnyOrUnknown(head)) { + head = UnknownType.create(); + } + classType.details.mro.push(head); classList.shift(); break; - } else if (!isInTail(classList[0], classListsToMerge)) { + } + + if (!isInTail(classList[0], classListsToMerge)) { foundValidHead = true; classType.details.mro.push(classList[0]); filterClass(classList[0], classListsToMerge); @@ -3186,8 +3209,11 @@ export function computeMroLinearization(classType: ClassType): boolean { // Handle the situation by pull the head off the first empty list. // This allows us to make forward progress. if (!isInstantiableClass(nonEmptyList[0])) { - assert(isClass(nonEmptyList[0]) || isAnyOrUnknown(nonEmptyList[0])); - classType.details.mro.push(nonEmptyList[0]); + let head = nonEmptyList[0]; + if (!isClass(head) && !isAnyOrUnknown(head)) { + head = UnknownType.create(); + } + classType.details.mro.push(head); nonEmptyList.shift(); } else { classType.details.mro.push(nonEmptyList[0]); @@ -3290,6 +3316,8 @@ export function convertTypeToParamSpecValue(type: Type): FunctionType { newFunction.details.typeVarScopeId = newFunction.details.higherOrderTypeVarScopeIds.pop(); } + newFunction.details.constructorTypeVarScopeId = type.details.constructorTypeVarScopeId; + return newFunction; } @@ -3328,6 +3356,7 @@ export function convertParamSpecValueToType(type: FunctionType): Type { FunctionType.addHigherOrderTypeVarScopeIds(functionType, withoutParamSpec.details.typeVarScopeId); FunctionType.addHigherOrderTypeVarScopeIds(functionType, withoutParamSpec.details.higherOrderTypeVarScopeIds); + functionType.details.constructorTypeVarScopeId = withoutParamSpec.details.constructorTypeVarScopeId; withoutParamSpec.details.parameters.forEach((entry, index) => { FunctionType.addParameter(functionType, { @@ -4122,7 +4151,7 @@ class ApplySolvedTypeVarsTransformer extends TypeVarTransformer { if (this._options.unknownIfNotFound) { return this._options.useUnknownOverDefault - ? specializeWithUnknownTypeArgs(subtype) + ? specializeWithUnknownTypeArgs(subtype, this._options.tupleClassType) : specializeWithDefaultTypeArgs(subtype); } } @@ -4160,7 +4189,7 @@ class ApplySolvedTypeVarsTransformer extends TypeVarTransformer { return this._solveDefaultType(typeVar.details.defaultType, recursionCount); } - return UnknownType.create(); + return getUnknownTypeForTypeVar(typeVar, this._options.tupleClassType); } } diff --git a/packages/pyright-internal/src/analyzer/types.ts b/packages/pyright-internal/src/analyzer/types.ts index 924b2302b..f355de9f7 100644 --- a/packages/pyright-internal/src/analyzer/types.ts +++ b/packages/pyright-internal/src/analyzer/types.ts @@ -825,9 +825,7 @@ export namespace ClassType { newClassType.includeSubclasses = true; } - newClassType.tupleTypeArguments = tupleTypeArguments?.map((t) => - isNever(t.type) ? { type: UnknownType.create(), isUnbounded: t.isUnbounded, isOptional: t.isOptional } : t - ); + newClassType.tupleTypeArguments = tupleTypeArguments ? [...tupleTypeArguments] : undefined; if (isEmptyContainer !== undefined) { newClassType.isEmptyContainer = isEmptyContainer; @@ -1766,6 +1764,7 @@ export namespace FunctionType { FunctionType.addHigherOrderTypeVarScopeIds(newFunction, paramSpecValue.details.typeVarScopeId); FunctionType.addHigherOrderTypeVarScopeIds(newFunction, paramSpecValue.details.higherOrderTypeVarScopeIds); + newFunction.details.constructorTypeVarScopeId = paramSpecValue.details.constructorTypeVarScopeId; if (!newFunction.details.methodClass && paramSpecValue.details.methodClass) { newFunction.details.methodClass = paramSpecValue.details.methodClass; diff --git a/packages/pyright-internal/src/backgroundAnalysis.ts b/packages/pyright-internal/src/backgroundAnalysis.ts index 579047123..852bed50a 100644 --- a/packages/pyright-internal/src/backgroundAnalysis.ts +++ b/packages/pyright-internal/src/backgroundAnalysis.ts @@ -24,11 +24,13 @@ export class BackgroundAnalysis extends BackgroundAnalysisBase { constructor(serviceProvider: ServiceProvider) { super(serviceProvider.console()); + const index = ++BackgroundAnalysis._workerIndex; const initialData: InitializationData = { rootUri: getRootUri(serviceProvider)?.toString() ?? '', + serviceId: index.toString(), cancellationFolderName: getCancellationFolderName(), runner: undefined, - workerIndex: ++BackgroundAnalysis._workerIndex, + workerIndex: index, }; // this will load this same file in BG thread and start listener diff --git a/packages/pyright-internal/src/backgroundAnalysisBase.ts b/packages/pyright-internal/src/backgroundAnalysisBase.ts index c0368ebac..9bd3d49fb 100644 --- a/packages/pyright-internal/src/backgroundAnalysisBase.ts +++ b/packages/pyright-internal/src/backgroundAnalysisBase.ts @@ -310,7 +310,14 @@ export abstract class BackgroundAnalysisRunnerBase extends BackgroundThreadBase const console = this.getConsole(); this.logTracker = new LogTracker(console, `BG(${threadId})`); - this._program = new Program(this.importResolver, this._configOptions, serviceProvider, this.logTracker); + this._program = new Program( + this.importResolver, + this._configOptions, + serviceProvider, + this.logTracker, + undefined, + data.serviceId + ); } get program(): Program { diff --git a/packages/pyright-internal/src/backgroundThreadBase.ts b/packages/pyright-internal/src/backgroundThreadBase.ts index 8775b2615..5f39836f6 100644 --- a/packages/pyright-internal/src/backgroundThreadBase.ts +++ b/packages/pyright-internal/src/backgroundThreadBase.ts @@ -251,10 +251,10 @@ export function getBackgroundWaiter(port: MessagePort, deserializer: (v: any) export interface InitializationData { rootUri: string; + serviceId: string; + workerIndex: number; cancellationFolderName: string | undefined; runner: string | undefined; - title?: string; - workerIndex: number; } export interface RequestResponse { diff --git a/packages/pyright-internal/src/common/collectionUtils.ts b/packages/pyright-internal/src/common/collectionUtils.ts index 6456f881b..3311a09fa 100644 --- a/packages/pyright-internal/src/common/collectionUtils.ts +++ b/packages/pyright-internal/src/common/collectionUtils.ts @@ -6,7 +6,7 @@ * Helper functions relating to collections and arrays. */ -import { compareValues, Comparison, equateValues, isArray } from './core'; +import { compareValues, Comparison, equateValues, isArray, MapLike } from './core'; export const emptyArray: never[] = [] as never[]; export type EqualityComparer = (a: T, b: T) => boolean; @@ -318,7 +318,7 @@ export function getNestedProperty(object: any, property: string) { return value; } -export function getOrAdd(map: Map, key: K, newValueFactory: () => V): V { +export function getOrAdd(map: MapLike, key: K, newValueFactory: () => V): V { const value = map.get(key); if (value !== undefined) { return value; diff --git a/packages/pyright-internal/src/common/core.ts b/packages/pyright-internal/src/common/core.ts index c82d31cc4..269043952 100644 --- a/packages/pyright-internal/src/common/core.ts +++ b/packages/pyright-internal/src/common/core.ts @@ -102,8 +102,11 @@ const hasOwnProperty = Object.prototype.hasOwnProperty; * The `in` and `for-in` operators can *not* be safely used, * since `Object.prototype` may be modified by outside code. */ -export interface MapLike { - [index: string]: T; +export interface MapLike { + readonly [Symbol.toStringTag]: string; + get(key: K): V | undefined; + has(key: K): boolean; + set(key: K, value: V): this; } /** @@ -112,7 +115,7 @@ export interface MapLike { * @param map A map-like. * @param key A property key. */ -export function hasProperty(map: MapLike, key: string): boolean { +export function hasProperty(map: { [index: string]: any }, key: string): boolean { return hasOwnProperty.call(map, key); } diff --git a/packages/pyright-internal/src/common/envVarUtils.ts b/packages/pyright-internal/src/common/envVarUtils.ts index 17911db80..5a5b4457a 100644 --- a/packages/pyright-internal/src/common/envVarUtils.ts +++ b/packages/pyright-internal/src/common/envVarUtils.ts @@ -70,6 +70,7 @@ export function expandPathVariables(path: string, rootPath: Uri, workspaces: Wor const ws_regexp = RegExp(`\\$\\{workspaceFolder:${escapedWorkspaceName}\\}`, 'g'); path = path.replace(ws_regexp, workspace.rootUri.getPath()); } + if (process.env.HOME !== undefined) { replace(/\$\{env:HOME\}/g, process.env.HOME || ''); } diff --git a/packages/pyright-internal/src/languageService/completionProvider.ts b/packages/pyright-internal/src/languageService/completionProvider.ts index 8c5fcc7f6..23fe7e396 100644 --- a/packages/pyright-internal/src/languageService/completionProvider.ts +++ b/packages/pyright-internal/src/languageService/completionProvider.ts @@ -46,6 +46,7 @@ import { printLiteralValue } from '../analyzer/typePrinter'; import { ClassType, combineTypes, + EnumLiteral, FunctionType, isClass, isClassInstance, @@ -127,6 +128,7 @@ import { import { DocumentSymbolCollector } from './documentSymbolCollector'; import { getAutoImportText, getDocumentationPartsForTypeAndDecl } from './tooltipUtils'; import '../common/serviceProviderExtensions'; +import { transformTypeForEnumMember } from '../analyzer/enums'; namespace Keywords { const base: string[] = [ @@ -705,13 +707,7 @@ export class CompletionProvider { // Handle enum members specially. Enum members normally look like // variables, but the are declared using assignment expressions // within an enum class. - if ( - primaryDecl.type === DeclarationType.Variable && - detail.boundObjectOrClass && - isInstantiableClass(detail.boundObjectOrClass) && - ClassType.isEnumClass(detail.boundObjectOrClass) && - primaryDecl.node.parent?.nodeType === ParseNodeType.Assignment - ) { + if (this._isEnumMember(detail.boundObjectOrClass, name)) { itemKind = CompletionItemKind.EnumMember; } @@ -757,19 +753,16 @@ export class CompletionProvider { if (isClass(subtype)) { const instance = TypeBase.isInstance(subtype); - if (ClassType.isEnumClass(subtype) && instance) { - // We don't add members for instances of enum members, but do add members of `enum.Enum` itself. - // ex) 'MyEnum.member.' <= here - const enumType = subtype.details.baseClasses.find( - (t) => isClass(t) && ClassType.isBuiltIn(t, 'Enum') - ) as ClassType | undefined; - if (!enumType) { - return; - } + getMembersForClass(subtype, symbolTable, instance); - getMembersForClass(enumType, symbolTable, /* instance */ true); - } else { - getMembersForClass(subtype, symbolTable, instance); + if (ClassType.isEnumClass(subtype) && instance) { + // Don't show enum member out of another enum member + // ex) Enum.Member. <= shouldn't show `Member` again. + for (const name of symbolTable.keys()) { + if (this._isEnumMember(subtype, name)) { + symbolTable.delete(name); + } + } } } else if (isModule(subtype)) { getMembersForModule(subtype, symbolTable); @@ -3143,6 +3136,21 @@ export class CompletionProvider { // before doing more expensive type evaluation. return decl.isMethod && decl.node.decorators.length > 0; } + + private _isEnumMember(containingType: ClassType | undefined, name: string) { + if (!containingType || !ClassType.isEnumClass(containingType)) { + return false; + } + + const symbolType = transformTypeForEnumMember(this.evaluator, containingType, name); + + return ( + symbolType && + isClassInstance(symbolType) && + ClassType.isSameGenericClass(symbolType, containingType) && + symbolType.literalValue instanceof EnumLiteral + ); + } } export class CompletionMap { diff --git a/packages/pyright-internal/src/localization/localize.ts b/packages/pyright-internal/src/localization/localize.ts index 06c94d41f..8c47b714f 100644 --- a/packages/pyright-internal/src/localization/localize.ts +++ b/packages/pyright-internal/src/localization/localize.ts @@ -118,7 +118,7 @@ export function setLocaleOverride(locale: string) { localeOverride = locale.toLowerCase(); } -export function getLocaleFromEnv() { +export function getLocaleFromEnv(): string { if (localeOverride) { return localeOverride; } @@ -130,7 +130,7 @@ export function getLocaleFromEnv() { const vscodeConfigString = env?.VSCODE_NLS_CONFIG; if (vscodeConfigString) { try { - return JSON.parse(vscodeConfigString).locale; + return JSON.parse(vscodeConfigString).locale || defaultLocale; } catch { // Fall through } @@ -142,7 +142,7 @@ export function getLocaleFromEnv() { // This string may contain a local followed by an encoding (e.g. "en-us.UTF-8"). const localeStringSplit = localeString.split('.'); if (localeStringSplit.length > 0 && localeStringSplit[0]) { - return localeStringSplit[0]; + return localeStringSplit[0] || defaultLocale; } } } catch { diff --git a/packages/pyright-internal/src/localization/package.nls.cs.json b/packages/pyright-internal/src/localization/package.nls.cs.json index b4df26b34..91e443960 100644 --- a/packages/pyright-internal/src/localization/package.nls.cs.json +++ b/packages/pyright-internal/src/localization/package.nls.cs.json @@ -158,8 +158,8 @@ "enumMemberDelete": "Člen výčtu {name} se nedá odstranit.", "enumMemberSet": "Člen výčtu {name} se nedá přiřadit.", "enumMemberTypeAnnotation": "Poznámky typu nejsou pro členy výčtu povolené", - "exceptionGroupIncompatible": "Syntaxe skupiny výjimek (except*) vyžaduje Python 3.11 nebo novější", - "exceptionGroupTypeIncorrect": "Typ výjimky v kromě* se nedá odvodit z BaseGroupException.", + "exceptionGroupIncompatible": "Syntaxe skupiny výjimek (\"except*\") vyžaduje Python 3.11 nebo novější", + "exceptionGroupTypeIncorrect": "Typ výjimky v except* se nedá odvodit z BaseGroupException.", "exceptionTypeIncorrect": "„{type}“ se neodvozuje od BaseException", "exceptionTypeNotClass": "{type} není platná třída výjimky", "exceptionTypeNotInstantiable": "Konstruktor pro výjimku typu {type} vyžaduje jeden nebo více argumentů", @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "Argumenty typu nejsou u třídy Protocol povoleny při použití syntaxe parametru typu", "protocolIllegal": "Použití protokolu vyžaduje Python 3.7 nebo novější", "protocolNotAllowed": "„Protocol“ nejde v tomto kontextu použít.", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "Argument typu pro „protokol“ musí být parametr typu", "protocolUnsafeOverlap": "Třída se nebezpečně překrývá s názvem „{name}“ a může vytvořit shodu při spuštění.", "protocolVarianceContravariant": "Proměnná typu „{variable}“ použitá v obecném protokolu „{class}“ by měla být kontravariantní", "protocolVarianceCovariant": "Proměnná typu „{variable}“ použitá v obecném protokolu „{class}“ by měla být kovariantní", diff --git a/packages/pyright-internal/src/localization/package.nls.de.json b/packages/pyright-internal/src/localization/package.nls.de.json index 666913cbb..a45fa71b4 100644 --- a/packages/pyright-internal/src/localization/package.nls.de.json +++ b/packages/pyright-internal/src/localization/package.nls.de.json @@ -159,7 +159,7 @@ "enumMemberSet": "Das Enumerationselement \"{name}\" kann nicht zugewiesen werden.", "enumMemberTypeAnnotation": "Typanmerkungen sind für Enumerationsmember nicht zulässig", "exceptionGroupIncompatible": "Die Ausnahmegruppensyntax (\"except*\") erfordert Python 3.11 oder höher.", - "exceptionGroupTypeIncorrect": "Der Ausnahmetyp in „except*“ kann nicht von BaseGroupException abgeleitet werden.", + "exceptionGroupTypeIncorrect": "Der Ausnahmetyp in except* kann nicht von BaseGroupException abgeleitet werden.", "exceptionTypeIncorrect": "\"{type}\" ist nicht von BaseException abgeleitet.", "exceptionTypeNotClass": "\"{type}\" ist keine gültige Ausnahmeklasse.", "exceptionTypeNotInstantiable": "Der Konstruktor für den Ausnahmetyp \"{type}\" erfordert mindestens ein Argument.", @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "Typargumente sind mit der Protokollklasse nicht zulässig, wenn die Typparametersyntax verwendet wird.", "protocolIllegal": "Die Verwendung von \"Protocol\" erfordert Python 3.7 oder höher.", "protocolNotAllowed": "\"Protocol\" kann in diesem Kontext nicht verwendet werden.", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "Das Typargument für „Protocol“ muss ein Typparameter sein.", "protocolUnsafeOverlap": "Die Klasse überlappt unsicher mit „{name}“ und könnte zur Laufzeit eine Übereinstimmung erzeugen.", "protocolVarianceContravariant": "Die Typvariable \"{variable}\", die im generischen Protokoll \"{class}\" verwendet wird, muss \"contravariant\" sein.", "protocolVarianceCovariant": "Die Typvariable \"{variable}\", die im generischen Protokoll \"{class}\" verwendet wird, muss \"covariant\" sein.", diff --git a/packages/pyright-internal/src/localization/package.nls.es.json b/packages/pyright-internal/src/localization/package.nls.es.json index 0bbf5cd93..73daf4ced 100644 --- a/packages/pyright-internal/src/localization/package.nls.es.json +++ b/packages/pyright-internal/src/localization/package.nls.es.json @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "No se permiten argumentos de tipo con la clase Protocol cuando se usa la sintaxis de parámetro de tipo", "protocolIllegal": "El uso de \"Protocolo\" requiere Python 3.7 o posterior.", "protocolNotAllowed": "\"Protocolo\" no puede utilizarse en este contexto", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "El argumento de tipo para \"Protocol\" debe ser un parámetro de tipo", "protocolUnsafeOverlap": "La clase se superpone \"{name}\" de forma no segura y podría producir una coincidencia en tiempo de ejecución", "protocolVarianceContravariant": "La variable de tipo \"{variable}\" usada en el protocolo genérico \"{class}\" debe ser contravariante.", "protocolVarianceCovariant": "La variable de tipo \"{variable}\" usada en el protocolo genérico \"{class}\" debe ser covariante", diff --git a/packages/pyright-internal/src/localization/package.nls.fr.json b/packages/pyright-internal/src/localization/package.nls.fr.json index f7a882115..c9c4b6900 100644 --- a/packages/pyright-internal/src/localization/package.nls.fr.json +++ b/packages/pyright-internal/src/localization/package.nls.fr.json @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "Les arguments de type ne sont pas autorisés avec la classe Protocol lors de l'utilisation de la syntaxe des paramètres de type", "protocolIllegal": "L’utilisation de « Protocole » nécessite Python 3.7 ou une version plus récente", "protocolNotAllowed": "\"Protocole\" ne peut pas être utilisé dans ce contexte", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "L’argument de type pour « Protocol » doit être un paramètre de type", "protocolUnsafeOverlap": "La classe chevauche « {name} » de manière non sécurisée et peut produire une correspondance au moment de l’exécution", "protocolVarianceContravariant": "La variable de type \"{variable}\" utilisée dans le protocole générique \"{class}\" doit être contravariante", "protocolVarianceCovariant": "La variable de type \"{variable}\" utilisée dans le protocole générique \"{class}\" doit être covariante", diff --git a/packages/pyright-internal/src/localization/package.nls.it.json b/packages/pyright-internal/src/localization/package.nls.it.json index 599bc9fb1..771dd88fe 100644 --- a/packages/pyright-internal/src/localization/package.nls.it.json +++ b/packages/pyright-internal/src/localization/package.nls.it.json @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "Gli argomenti tipo non sono consentiti con la classe Protocollo quando si usa la sintassi dei parametri tipo", "protocolIllegal": "L'uso del \"protocollo\" richiede Python 3.7 o versione successiva", "protocolNotAllowed": "\"Protocol\" non può essere usato in questo contesto", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "L'argomento di tipo per \"Protocol\" deve essere un parametro di tipo", "protocolUnsafeOverlap": "La classe si sovrappone a \"{name}\" in modo non sicuro e può produrre una corrispondenza in fase di esecuzione", "protocolVarianceContravariant": "La variabile di tipo \"{variable}\" usata nel protocollo generico \"{class}\" deve essere controvariante", "protocolVarianceCovariant": "La variabile di tipo \"{variable}\" usata nel protocollo generico \"{class}\" deve essere covariante", diff --git a/packages/pyright-internal/src/localization/package.nls.ja.json b/packages/pyright-internal/src/localization/package.nls.ja.json index 3afee55c0..b8037b565 100644 --- a/packages/pyright-internal/src/localization/package.nls.ja.json +++ b/packages/pyright-internal/src/localization/package.nls.ja.json @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "型パラメーター構文を使用する場合、Protocol クラスでは型引数を使用できません", "protocolIllegal": "\"Protocol\" を使用するには Python 3.7 以降が必要です", "protocolNotAllowed": "\"Protocol\" はこのコンテキストでは使用できません", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "\"Protocol\" の型引数は型パラメーターである必要があります", "protocolUnsafeOverlap": "クラスが安全でない方法で \"{name}\" と重複しており、実行時に一致する可能性があります", "protocolVarianceContravariant": "ジェネリック プロトコル \"{class}\" で使用される型変数 \"{variable}\" は反変である必要があります", "protocolVarianceCovariant": "ジェネリック プロトコル \"{class}\" で使用される型変数 \"{variable}\" は共変である必要があります", diff --git a/packages/pyright-internal/src/localization/package.nls.ko.json b/packages/pyright-internal/src/localization/package.nls.ko.json index 3b3075e20..1a6ce84a7 100644 --- a/packages/pyright-internal/src/localization/package.nls.ko.json +++ b/packages/pyright-internal/src/localization/package.nls.ko.json @@ -159,7 +159,7 @@ "enumMemberSet": "열거형 멤버 \"{name}\"을(를) 할당할 수 없음", "enumMemberTypeAnnotation": "열거형 멤버에는 형식 주석을 사용할 수 없습니다.", "exceptionGroupIncompatible": "예외 그룹 구문(\"except*\")에는 Python 3.11 이상이 필요합니다.", - "exceptionGroupTypeIncorrect": "exception*의 예외 형식은 BaseGroupException에서 파생될 수 없습니다.", + "exceptionGroupTypeIncorrect": "except*의 예외 형식은 BaseGroupException에서 파생될 수 없습니다.", "exceptionTypeIncorrect": "‘{type}’은 BaseException에서 파생되지 않습니다.", "exceptionTypeNotClass": "\"{type}\"은(는) 올바른 예외 클래스가 아닙니다.", "exceptionTypeNotInstantiable": "예외 형식 \"{type}\"에 대한 생성자에는 하나 이상의 인수가 필요합니다.", @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "형식 매개 변수 구문을 사용할 때는 Protocol 클래스에 형식 인수가 허용되지 않습니다.", "protocolIllegal": "\"프로토콜\"을 사용하려면 Python 3.7 이상이 필요합니다.", "protocolNotAllowed": "이 컨텍스트에서는 \"Protocol\"을 사용할 수 없습니다.", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "\"Protocol\"의 형식 인수는 형식 매개 변수여야 합니다.", "protocolUnsafeOverlap": "클래스가 \"{name}\"과(와) 안전하지 않게 겹치며 런타임에 일치 항목을 생성할 수 있습니다.", "protocolVarianceContravariant": "‘{class}‘ 제네릭 프로토콜에서 사용되는 ’{variable}‘ 형식 변수는 반공변이어야 합니다.", "protocolVarianceCovariant": "‘{class}‘ 제네릭 프로토콜에서 사용되는 ’{variable}‘ 형식 변수는 공변이어야 합니다", diff --git a/packages/pyright-internal/src/localization/package.nls.pl.json b/packages/pyright-internal/src/localization/package.nls.pl.json index 736a5d4dd..440a5bf5e 100644 --- a/packages/pyright-internal/src/localization/package.nls.pl.json +++ b/packages/pyright-internal/src/localization/package.nls.pl.json @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "Argumenty typu są niedozwolone w przypadku klasy protokołu, gdy jest używana składnia parametru typu", "protocolIllegal": "Użycie elementu „Protocol” wymaga języka Python w wersji 3.7 lub nowszej", "protocolNotAllowed": "„Protokół” nie może być używany w tym kontekście", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "Argument typu dla elementy „Protocol” musi być parametrem typu", "protocolUnsafeOverlap": "Klasa nakłada się niebezpiecznie na element „{name}” i może utworzyć dopasowanie w czasie wykonywania", "protocolVarianceContravariant": "Zmienna typu „{variable}” używana w klasie protokołu ogólnego „{class}” powinna być kontrawariantna", "protocolVarianceCovariant": "Zmienna typu „{variable}” używana w klasie protokołu ogólnego „{class}” powinna być kowariantna", diff --git a/packages/pyright-internal/src/localization/package.nls.pt-br.json b/packages/pyright-internal/src/localization/package.nls.pt-br.json index 5934ec1dd..fc71b2676 100644 --- a/packages/pyright-internal/src/localization/package.nls.pt-br.json +++ b/packages/pyright-internal/src/localization/package.nls.pt-br.json @@ -158,8 +158,8 @@ "enumMemberDelete": "O membro enumerado \"{name}\" não pode ser excluído", "enumMemberSet": "O membro enumerado \"{name}\" não pode ser atribuído", "enumMemberTypeAnnotation": "Anotações de tipo não são permitidas para membros de enumeração", - "exceptionGroupIncompatible": "A sintaxe do grupo de exceção (\"exceto*\") requer o Python 3.11 ou mais recente", - "exceptionGroupTypeIncorrect": "O tipo de exceção em exceto* não pode derivar de BaseGroupException", + "exceptionGroupIncompatible": "A sintaxe do grupo de exceção (\"except*\") requer o Python 3.11 ou mais recente", + "exceptionGroupTypeIncorrect": "O tipo de exceção em except* não pode derivar de BaseGroupException", "exceptionTypeIncorrect": "\"{type}\" não deriva de BaseException", "exceptionTypeNotClass": "\"{type}\" não é uma classe de exceção válida", "exceptionTypeNotInstantiable": "O construtor para o tipo de exceção \"{type}\" requer um ou mais argumentos", @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "Argumentos de tipo não são permitidos com a classe Protocol ao usar a sintaxe de parâmetro de tipo", "protocolIllegal": "O uso de \"Protocol\" requer o Python 3.7 ou mais recente", "protocolNotAllowed": "\"Protocol\" não pode ser usado nesse contexto", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "O argumento de tipo para o \"Protocolo\" deve ser um parâmetro de tipo", "protocolUnsafeOverlap": "A classe se sobrepõe a \"{name}\" de forma não segura e pode produzir uma correspondência em runtime", "protocolVarianceContravariant": "A variável de tipo \"{variable}\" usada no protocolo genérico \"{class}\" deve ser contravariante", "protocolVarianceCovariant": "A variável de tipo \"{variable}\" usada no protocolo genérico \"{class}\" deve ser covariante", diff --git a/packages/pyright-internal/src/localization/package.nls.ru.json b/packages/pyright-internal/src/localization/package.nls.ru.json index 18e5477f3..e29f99b4b 100644 --- a/packages/pyright-internal/src/localization/package.nls.ru.json +++ b/packages/pyright-internal/src/localization/package.nls.ru.json @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "Аргументы типа не допускаются с классом протокола при использовании синтаксиса параметра типа", "protocolIllegal": "Ключевое слово \"Protocol\" можно использовать в Python версии не ниже 3.7", "protocolNotAllowed": "Невозможно использовать \"Protocol\" в этом контексте", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "Аргумент типа для параметра \"Protocol\" должен быть параметром типа", "protocolUnsafeOverlap": "Класс небезопасно перекрывает \"{name}\" и может вызвать совпадение во время выполнения", "protocolVarianceContravariant": "Переменная типа \"{variable}\", используемая в универсальном протоколе \"{class}\", должна быть контравариантной.", "protocolVarianceCovariant": "Переменная типа \"{variable}\", используемая в универсальном протоколе \"{class}\", должна быть ковариантной", diff --git a/packages/pyright-internal/src/localization/package.nls.tr.json b/packages/pyright-internal/src/localization/package.nls.tr.json index db0e01230..2802b3ba9 100644 --- a/packages/pyright-internal/src/localization/package.nls.tr.json +++ b/packages/pyright-internal/src/localization/package.nls.tr.json @@ -159,7 +159,7 @@ "enumMemberSet": "Sabit liste üyesi \"{name}\" atanamıyor", "enumMemberTypeAnnotation": "Sabit listesi üyeleri için tür ek açıklamalarına izin verilmiyor", "exceptionGroupIncompatible": "Özel durum grubu söz dizimi (\"except*\") için Python 3.11 veya daha yeni bir sürümü gerekiyor", - "exceptionGroupTypeIncorrect": "Except* altındaki özel durum türü BaseGroupException değerinden türetilemiyor", + "exceptionGroupTypeIncorrect": "except* altındaki özel durum türü BaseGroupException değerinden türetilemiyor", "exceptionTypeIncorrect": "\"{type}\", BaseException türevi değil", "exceptionTypeNotClass": "\"{type}\" geçerli bir özel durum sınıfı değil", "exceptionTypeNotInstantiable": "\"{type}\" özel durum türü oluşturucusu bir veya daha fazla bağımsız değişken gerektiriyor", @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "Tür parametresi söz dizimi kullanılırken, tür bağımsız değişkenlerinin Protokol sınıfıyla kullanılmasına izin verilmez", "protocolIllegal": "\"Protocol\" kullanımı için Python 3.7 veya daha yeni bir sürümü gerekiyor", "protocolNotAllowed": "\"Protokol\" bu bağlamda kullanılamaz", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "“Protokol” için tür bağımsız değişkeni bir tür parametresi olmalıdır", "protocolUnsafeOverlap": "Sınıf, \"{name}\" ile güvenli olmayan bir şekilde çakışıyor ve çalışma zamanında bir eşleşme üretebilir", "protocolVarianceContravariant": "\"{class}\" genel protokolünde kullanılan \"{variable}\" tür değişkeni, değişken karşıtı olmalıdır", "protocolVarianceCovariant": "\"{class}\" genel protokolünde kullanılan \"{variable}\" tür değişkeni birlikte değişen olmalıdır", diff --git a/packages/pyright-internal/src/localization/package.nls.zh-cn.json b/packages/pyright-internal/src/localization/package.nls.zh-cn.json index e0a3b416f..3306e6c71 100644 --- a/packages/pyright-internal/src/localization/package.nls.zh-cn.json +++ b/packages/pyright-internal/src/localization/package.nls.zh-cn.json @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "使用类型参数语法时,协议类不允许使用类型参数", "protocolIllegal": "使用 \"Protocol\" 需要 Python 3.7 或更高版本", "protocolNotAllowed": "\"Protocol\" 不能用于此上下文", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "“协议”的类型参数必须是类型参数", "protocolUnsafeOverlap": "类与“{name}”不安全地重叠,并且可能在运行时生成匹配项", "protocolVarianceContravariant": "泛型协议“{class}”中使用的类型变量“{variable}”应为逆变", "protocolVarianceCovariant": "泛型协议“{class}”中使用的类型变量“{variable}”应为协变", diff --git a/packages/pyright-internal/src/localization/package.nls.zh-tw.json b/packages/pyright-internal/src/localization/package.nls.zh-tw.json index 0907de171..92d5e3e16 100644 --- a/packages/pyright-internal/src/localization/package.nls.zh-tw.json +++ b/packages/pyright-internal/src/localization/package.nls.zh-tw.json @@ -403,7 +403,7 @@ "protocolBaseClassWithTypeArgs": "使用型別參數語法時,通訊協定類別不允許使用型別引數", "protocolIllegal": "使用 \"Protocol\" 需要 Python 3.7 或更新版本", "protocolNotAllowed": "\"Protocol\" 不能用在此內容中", - "protocolTypeArgMustBeTypeParam": "Type argument for \"Protocol\" must be a type parameter", + "protocolTypeArgMustBeTypeParam": "“Protocol” 的型別引數必須是型別參數", "protocolUnsafeOverlap": "類別以不安全方式重疊 \"{name}\",且可能會在運行時間產生相符專案", "protocolVarianceContravariant": "一般通訊協定 \"{class}\" 中使用的型別變數 \"{variable}\" 必須為逆變數", "protocolVarianceCovariant": "一般通訊協定 \"{class}\" 中使用的型別變數 \"{variable}\" 必須為共變數", diff --git a/packages/pyright-internal/src/tests/completions.test.ts b/packages/pyright-internal/src/tests/completions.test.ts index 10c21096e..6bd5321e5 100644 --- a/packages/pyright-internal/src/tests/completions.test.ts +++ b/packages/pyright-internal/src/tests/completions.test.ts @@ -1302,3 +1302,90 @@ test('import from completion for namespace package', async () => { }, }); }); + +test('members off enum member', async () => { + const code = ` +// @filename: test.py +//// from enum import Enum +//// class Planet(Enum): +//// MERCURY = (3.303e+23, 2.4397e6) +//// EARTH = (5.976e+24, 6.37814e6) +//// +//// def __init__(self, mass, radius): +//// self.mass = mass # in kilograms +//// self.radius = radius # in meters +//// +//// @property +//// def surface_gravity(self): +//// # universal gravitational constant (m3 kg-1 s-2) +//// G = 6.67300E-11 +//// return G * self.mass / (self.radius * self.radius) +//// +//// Planet.EARTH.[|/*marker*/|] + `; + + const state = parseAndGetTestState(code).state; + + await state.verifyCompletion('excluded', 'markdown', { + ['marker']: { + completions: [ + { + label: 'MERCURY', + kind: CompletionItemKind.EnumMember, + }, + { + label: 'EARTH', + kind: CompletionItemKind.EnumMember, + }, + ], + }, + }); + + await state.verifyCompletion('included', 'markdown', { + ['marker']: { + completions: [ + { + label: 'mass', + kind: CompletionItemKind.Variable, + }, + { + label: 'radius', + kind: CompletionItemKind.Variable, + }, + { + label: 'surface_gravity', + kind: CompletionItemKind.Property, + }, + ], + }, + }); +}); + +test('enum with regular base type', async () => { + const code = ` +// @filename: test.py +//// from enum import Enum +//// from datetime import timedelta +//// class Period(timedelta, Enum): +//// Today = -1 +//// +//// Period.Today.[|/*marker*/|] + `; + + const state = parseAndGetTestState(code).state; + + await state.verifyCompletion('included', 'markdown', { + ['marker']: { + completions: [ + { + label: 'days', + kind: CompletionItemKind.Property, + }, + { + label: 'seconds', + kind: CompletionItemKind.Property, + }, + ], + }, + }); +}); diff --git a/packages/pyright-internal/src/tests/languageServer.test.ts b/packages/pyright-internal/src/tests/languageServer.test.ts index 27e7b6933..c12f62ddc 100644 --- a/packages/pyright-internal/src/tests/languageServer.test.ts +++ b/packages/pyright-internal/src/tests/languageServer.test.ts @@ -192,4 +192,47 @@ describe(`Basic language server tests`, () => { assert.equal(diagnostic.diagnostics[3].code, 'reportUnusedImport'); assert.equal(diagnostic.diagnostics[5].code, 'reportUnusedImport'); }); + + test('Diagnostic severity overrides test', async () => { + const code = ` +// @filename: test.py +//// def test([|/*marker*/x|]): ... +//// +// @filename: pyproject.toml +//// + `; + const settings = [ + { + item: { + scopeUri: `file://${normalizeSlashes(DEFAULT_WORKSPACE_ROOT, '/')}`, + section: 'python.analysis', + }, + value: { + diagnosticSeverityOverrides: { + reportUnknownParameterType: 'warning', + }, + }, + }, + ]; + + const info = await runLanguageServer( + DEFAULT_WORKSPACE_ROOT, + code, + /* callInitialize */ true, + settings, + undefined, + /* supportsBackgroundThread */ true + ); + + // get the file containing the marker that also contains our task list comments + await openFile(info, 'marker'); + + // Wait for the diagnostics to publish + const diagnostics = await waitForDiagnostics(info); + const diagnostic = diagnostics.find((d) => d.uri.includes('test.py')); + assert(diagnostic); + + // Make sure the error has a special rule + assert.equal(diagnostic.diagnostics[0].code, 'reportUnknownParameterType'); + }); }); diff --git a/packages/pyright-internal/src/tests/samples/abstractClass10.py b/packages/pyright-internal/src/tests/samples/abstractClass10.py index 993cb9d16..3a6624dd3 100644 --- a/packages/pyright-internal/src/tests/samples/abstractClass10.py +++ b/packages/pyright-internal/src/tests/samples/abstractClass10.py @@ -7,8 +7,7 @@ from abc import ABC, abstractmethod class A(ABC): @staticmethod @abstractmethod - def method1() -> None: - ... + def method1() -> None: ... @staticmethod @abstractmethod @@ -66,8 +65,7 @@ def func1(a: type[A]): a.method3() -class C(A): - ... +class C(A): ... # This should generate an error. diff --git a/packages/pyright-internal/src/tests/samples/abstractClass5.py b/packages/pyright-internal/src/tests/samples/abstractClass5.py index ff6b56e43..d5411cbe2 100644 --- a/packages/pyright-internal/src/tests/samples/abstractClass5.py +++ b/packages/pyright-internal/src/tests/samples/abstractClass5.py @@ -18,8 +18,7 @@ class Foo(ABC): @overload @abstractmethod - def func1(self, a: str) -> str: - ... + def func1(self, a: str) -> str: ... # This should generate an error because this overload is # missing an abstractmethod overload. @@ -27,8 +26,7 @@ class Foo(ABC): raise NotImplementedError() @overload - def func2(self, a: str) -> str: - ... + def func2(self, a: str) -> str: ... @overload @abstractmethod diff --git a/packages/pyright-internal/src/tests/samples/abstractClass8.py b/packages/pyright-internal/src/tests/samples/abstractClass8.py index 286d4650e..e12f1ddf7 100644 --- a/packages/pyright-internal/src/tests/samples/abstractClass8.py +++ b/packages/pyright-internal/src/tests/samples/abstractClass8.py @@ -23,5 +23,4 @@ class Bar(Foo): @final # This should generate an error because Foo.foo, Bar.bar, and Bar.bar1 # are abstract. -class Baz(Bar): - ... +class Baz(Bar): ... diff --git a/packages/pyright-internal/src/tests/samples/abstractClass9.py b/packages/pyright-internal/src/tests/samples/abstractClass9.py index 13396d71c..9335c96ec 100644 --- a/packages/pyright-internal/src/tests/samples/abstractClass9.py +++ b/packages/pyright-internal/src/tests/samples/abstractClass9.py @@ -9,8 +9,7 @@ from typing import NamedTuple class ClassA(ABC): @property @abstractmethod - def myproperty(self) -> str: - ... + def myproperty(self) -> str: ... MixinB = NamedTuple("MixinB", [("myproperty", str)]) diff --git a/packages/pyright-internal/src/tests/samples/annotated2.py b/packages/pyright-internal/src/tests/samples/annotated2.py index b854c12f3..a9226f80b 100644 --- a/packages/pyright-internal/src/tests/samples/annotated2.py +++ b/packages/pyright-internal/src/tests/samples/annotated2.py @@ -10,9 +10,7 @@ v1: Annotated[str, ClassA, func1(), v2[0]] = "" v2 = [1, 2, 3] -class ClassA: - ... +class ClassA: ... -def func1(): - ... +def func1(): ... diff --git a/packages/pyright-internal/src/tests/samples/annotations1.py b/packages/pyright-internal/src/tests/samples/annotations1.py index 480e9b84a..b331dacbc 100644 --- a/packages/pyright-internal/src/tests/samples/annotations1.py +++ b/packages/pyright-internal/src/tests/samples/annotations1.py @@ -64,8 +64,7 @@ class ClassD: str: "str" - def int(self): - ... + def int(self): ... foo: "int" @@ -147,4 +146,3 @@ x12: b"int" # This should generate an error because format strings aren't allowed. x13: f"int" - diff --git a/packages/pyright-internal/src/tests/samples/annotations3.py b/packages/pyright-internal/src/tests/samples/annotations3.py index dfec6d99e..a05db66b9 100644 --- a/packages/pyright-internal/src/tests/samples/annotations3.py +++ b/packages/pyright-internal/src/tests/samples/annotations3.py @@ -27,8 +27,7 @@ class ClassB(ClassA): def func5(self, x: ClassA): x.func0() - class ClassA: - ... + class ClassA: ... def func6(self, x: ClassC): x.my_int diff --git a/packages/pyright-internal/src/tests/samples/annotations4.py b/packages/pyright-internal/src/tests/samples/annotations4.py index 4c6d97160..2ed6621ee 100644 --- a/packages/pyright-internal/src/tests/samples/annotations4.py +++ b/packages/pyright-internal/src/tests/samples/annotations4.py @@ -53,8 +53,7 @@ e = [3] e: list[int] -def register(fn: Callable[[], None]) -> None: - ... +def register(fn: Callable[[], None]) -> None: ... # These should be be fine because they use the "_" name. diff --git a/packages/pyright-internal/src/tests/samples/any1.py b/packages/pyright-internal/src/tests/samples/any1.py index 60da8c2fd..8991245f3 100644 --- a/packages/pyright-internal/src/tests/samples/any1.py +++ b/packages/pyright-internal/src/tests/samples/any1.py @@ -11,12 +11,10 @@ v1 = cast(Any, 0) v2 = cast(typing.Any, 0) -class A(Any): - ... +class A(Any): ... -class B(typing.Any): - ... +class B(typing.Any): ... # This should generate an error because Any is not callable. diff --git a/packages/pyright-internal/src/tests/samples/assignment10.py b/packages/pyright-internal/src/tests/samples/assignment10.py index 56f5e3416..5ed2786d7 100644 --- a/packages/pyright-internal/src/tests/samples/assignment10.py +++ b/packages/pyright-internal/src/tests/samples/assignment10.py @@ -20,8 +20,7 @@ class A: T = TypeVar("T") -class B(Generic[T]): - ... +class B(Generic[T]): ... def func1(v1: list[Any | None], v2: list[int | str]): diff --git a/packages/pyright-internal/src/tests/samples/assignment3.py b/packages/pyright-internal/src/tests/samples/assignment3.py index 712c18757..be4b83a21 100644 --- a/packages/pyright-internal/src/tests/samples/assignment3.py +++ b/packages/pyright-internal/src/tests/samples/assignment3.py @@ -38,8 +38,7 @@ d4: dict[str, tuple[int, Callable[[int], int]]] = { class Adder(Protocol): - def __call__(self, x: int, y: dict[str, int]) -> int: - ... + def __call__(self, x: int, y: dict[str, int]) -> int: ... v1: Adder = lambda x, y: x + y["hi"] diff --git a/packages/pyright-internal/src/tests/samples/assignment8.py b/packages/pyright-internal/src/tests/samples/assignment8.py index ae1cd76b5..59c5cf4db 100644 --- a/packages/pyright-internal/src/tests/samples/assignment8.py +++ b/packages/pyright-internal/src/tests/samples/assignment8.py @@ -7,12 +7,10 @@ from typing import Any, TypeVar, overload class Foo: @overload - def bar(self, obj: None) -> object: - ... + def bar(self, obj: None) -> object: ... @overload - def bar(self, obj: object) -> Any: - ... + def bar(self, obj: object) -> Any: ... def bar(self, obj: object | None) -> Any: pass diff --git a/packages/pyright-internal/src/tests/samples/assignmentExpr5.py b/packages/pyright-internal/src/tests/samples/assignmentExpr5.py index 59854fcbf..95ecd82d7 100644 --- a/packages/pyright-internal/src/tests/samples/assignmentExpr5.py +++ b/packages/pyright-internal/src/tests/samples/assignmentExpr5.py @@ -17,8 +17,7 @@ def func1() -> Tuple[str, int]: return (a, y) -def get_value(x: int) -> int: - ... +def get_value(x: int) -> int: ... x = sum(max(value for x in range(10) if (value := get_value(x))) for _ in range(10)) diff --git a/packages/pyright-internal/src/tests/samples/assignmentExpr9.py b/packages/pyright-internal/src/tests/samples/assignmentExpr9.py index cf6b680ef..867cbe496 100644 --- a/packages/pyright-internal/src/tests/samples/assignmentExpr9.py +++ b/packages/pyright-internal/src/tests/samples/assignmentExpr9.py @@ -7,8 +7,7 @@ from typing import Any, Callable, TypeVar, overload _T = TypeVar("_T") -def decorator(*args: Any, **kwargs: Any) -> Callable[[_T], _T]: - ... +def decorator(*args: Any, **kwargs: Any) -> Callable[[_T], _T]: ... @decorator( @@ -19,7 +18,7 @@ def decorator(*args: Any, **kwargs: Any) -> Callable[[_T], _T]: ], ) def decorated( - x: list[str] = [x for x in ["a", "b"] if x in (walrus_target_2 := ["a", "b"])] + x: list[str] = [x for x in ["a", "b"] if x in (walrus_target_2 := ["a", "b"])], ): pass @@ -29,13 +28,11 @@ reveal_type(walrus_target_2, expected_text="list[str]") @overload -def func1(value: None = None) -> None: - ... +def func1(value: None = None) -> None: ... @overload -def func1(value: str) -> str: - ... +def func1(value: str) -> str: ... def func1(value: str | None = None) -> str | None: diff --git a/packages/pyright-internal/src/tests/samples/autoVariance2.py b/packages/pyright-internal/src/tests/samples/autoVariance2.py index b8ab5dd70..de200cf07 100644 --- a/packages/pyright-internal/src/tests/samples/autoVariance2.py +++ b/packages/pyright-internal/src/tests/samples/autoVariance2.py @@ -19,15 +19,12 @@ class MyPartial[**P, R]: self.first = first self.func = func - def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: - ... + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ... class CallbackKeyed[*Ts](Protocol): - def __call__(self, *args: *Ts, keyed: bool) -> tuple[*Ts]: - ... + def __call__(self, *args: *Ts, keyed: bool) -> tuple[*Ts]: ... + def invoke_keyed[*Ts](fn: CallbackKeyed[*Ts], *args: *Ts) -> tuple[*Ts]: return fn(*args, keyed=True) - - \ No newline at end of file diff --git a/packages/pyright-internal/src/tests/samples/autoVariance4.py b/packages/pyright-internal/src/tests/samples/autoVariance4.py index ef0924269..795d6d5ce 100644 --- a/packages/pyright-internal/src/tests/samples/autoVariance4.py +++ b/packages/pyright-internal/src/tests/samples/autoVariance4.py @@ -7,12 +7,15 @@ T = TypeVar("T") T_co = TypeVar("T_co", covariant=True) T_contra = TypeVar("T_contra", contravariant=True) + class Parent_Invariant(Generic[T]): pass + class ShouldBeInvariant[T](Parent_Invariant[T]): pass + # This should generate an error. a1: ShouldBeInvariant[int] = ShouldBeInvariant[float]() @@ -23,9 +26,11 @@ a2: ShouldBeInvariant[float] = ShouldBeInvariant[int]() class Parent_Covariant(Generic[T_co]): pass + class ShouldBeCovariant[T](Parent_Covariant[T]): pass + # This should generate an error. b1: ShouldBeCovariant[int] = ShouldBeCovariant[float]() @@ -35,11 +40,12 @@ b2: ShouldBeCovariant[float] = ShouldBeCovariant[int]() class Parent_Contravariant(Generic[T_contra]): pass + class ShouldBeContravariant[T](Parent_Contravariant[T]): pass + c1: ShouldBeContravariant[int] = ShouldBeContravariant[float]() # This should generate an error. c2: ShouldBeContravariant[float] = ShouldBeContravariant[int]() - diff --git a/packages/pyright-internal/src/tests/samples/call10.py b/packages/pyright-internal/src/tests/samples/call10.py index 25178a102..41605545f 100644 --- a/packages/pyright-internal/src/tests/samples/call10.py +++ b/packages/pyright-internal/src/tests/samples/call10.py @@ -4,12 +4,10 @@ from typing import Any, Hashable, Mapping, Protocol -def requires_hashable_tuple(p1: tuple[Hashable, ...]): - ... +def requires_hashable_tuple(p1: tuple[Hashable, ...]): ... -def requires_hashable_dict(p1: dict[str, Hashable]): - ... +def requires_hashable_dict(p1: dict[str, Hashable]): ... def test_args(*args: Hashable): @@ -24,8 +22,7 @@ def test_kwargs(**kwargs: Hashable): requires_hashable_dict(kwargs) -class StrSubclass(str): - ... +class StrSubclass(str): ... def test_kwargs2( @@ -51,30 +48,26 @@ def test_kwargs2( class Callback1(Protocol): - def __call__(self) -> None: - ... + def __call__(self) -> None: ... def func1( value: str = ..., *args: object, -) -> None: - ... +) -> None: ... def func2( value: str = ..., **kwargs: object, -) -> None: - ... +) -> None: ... def func3( value: str = ..., *args: object, **kwargs: object, -) -> None: - ... +) -> None: ... v1: Callback1 = func1 diff --git a/packages/pyright-internal/src/tests/samples/call5.py b/packages/pyright-internal/src/tests/samples/call5.py index a3a078f07..eba6913f1 100644 --- a/packages/pyright-internal/src/tests/samples/call5.py +++ b/packages/pyright-internal/src/tests/samples/call5.py @@ -71,8 +71,7 @@ for a, b in zip(*q6): reveal_type(b, expected_text="int") -def func1(a: list[str], c: list[int]): - ... +def func1(a: list[str], c: list[int]): ... func1(*q6) diff --git a/packages/pyright-internal/src/tests/samples/call9.py b/packages/pyright-internal/src/tests/samples/call9.py index a6033f83b..dcdf655d0 100644 --- a/packages/pyright-internal/src/tests/samples/call9.py +++ b/packages/pyright-internal/src/tests/samples/call9.py @@ -5,31 +5,25 @@ from typing import Any, Generic, TypeVar, Mapping, KeysView -class MyMapping(Mapping[str, Any]): - ... +class MyMapping(Mapping[str, Any]): ... class StrRecord: - def __getitem__(self, __key: str) -> str: - ... + def __getitem__(self, __key: str) -> str: ... - def keys(self) -> KeysView[str]: - ... + def keys(self) -> KeysView[str]: ... T = TypeVar("T") class GenericRecord(Generic[T]): - def __getitem__(self, __key: str) -> T: - ... + def __getitem__(self, __key: str) -> T: ... - def keys(self) -> KeysView[T]: - ... + def keys(self) -> KeysView[T]: ... -def func1(**kwargs: Any) -> None: - ... +def func1(**kwargs: Any) -> None: ... m = MyMapping() diff --git a/packages/pyright-internal/src/tests/samples/callable2.py b/packages/pyright-internal/src/tests/samples/callable2.py index 05cc1b815..b4edd3b5e 100644 --- a/packages/pyright-internal/src/tests/samples/callable2.py +++ b/packages/pyright-internal/src/tests/samples/callable2.py @@ -9,16 +9,14 @@ from typing import Any, Awaitable, Callable, Iterable, Sequence, TypeVar _T1 = TypeVar("_T1") -def func1(__iterable: Iterable[_T1]) -> _T1: - ... +def func1(__iterable: Iterable[_T1]) -> _T1: ... a: Callable[[Sequence[float]], float] = func1 b: Callable[[Sequence[Any]], Any] = func1 -def func2(__iterable: Sequence[_T1]) -> _T1: - ... +def func2(__iterable: Sequence[_T1]) -> _T1: ... # This should generate an error because an Iterable parameter @@ -29,8 +27,7 @@ c: Callable[[Iterable[float]], float] = func2 _T2 = TypeVar("_T2", bound=float) -def func3(__iterable: Iterable[_T2]) -> _T2: - ... +def func3(__iterable: Iterable[_T2]) -> _T2: ... d: Callable[[Sequence[int]], int] = func3 diff --git a/packages/pyright-internal/src/tests/samples/callable3.py b/packages/pyright-internal/src/tests/samples/callable3.py index b27020741..a04d3ee6c 100644 --- a/packages/pyright-internal/src/tests/samples/callable3.py +++ b/packages/pyright-internal/src/tests/samples/callable3.py @@ -8,8 +8,7 @@ T = TypeVar("T") R = TypeVar("R") -class ClassA(Generic[R]): - ... +class ClassA(Generic[R]): ... class ClassB(Generic[T]): diff --git a/packages/pyright-internal/src/tests/samples/callable5.py b/packages/pyright-internal/src/tests/samples/callable5.py index ef92dd9c2..bf6bc5b17 100644 --- a/packages/pyright-internal/src/tests/samples/callable5.py +++ b/packages/pyright-internal/src/tests/samples/callable5.py @@ -8,17 +8,14 @@ T = TypeVar("T") @overload -def func1(real: float): - ... +def func1(real: float): ... @overload -def func1(real: str): - ... +def func1(real: str): ... -def func1(real: float | str) -> None: - ... +def func1(real: float | str) -> None: ... def func2(f: Callable[[T], Any], p: T): diff --git a/packages/pyright-internal/src/tests/samples/callable7.py b/packages/pyright-internal/src/tests/samples/callable7.py index 767c4246f..4845cfedc 100644 --- a/packages/pyright-internal/src/tests/samples/callable7.py +++ b/packages/pyright-internal/src/tests/samples/callable7.py @@ -1,5 +1,6 @@ # This sample tests the handling of the `__call__` attribute. + class A: def __init__(self): self.__call__ = self.method1 diff --git a/packages/pyright-internal/src/tests/samples/callbackProtocol1.py b/packages/pyright-internal/src/tests/samples/callbackProtocol1.py index 23958f747..acdf943ba 100644 --- a/packages/pyright-internal/src/tests/samples/callbackProtocol1.py +++ b/packages/pyright-internal/src/tests/samples/callbackProtocol1.py @@ -140,7 +140,7 @@ class TestClass7: pass -def test_func7(*args: * tuple[int, *tuple[int, ...]]) -> int: +def test_func7(*args: *tuple[int, *tuple[int, ...]]) -> int: return 123 diff --git a/packages/pyright-internal/src/tests/samples/callbackProtocol2.py b/packages/pyright-internal/src/tests/samples/callbackProtocol2.py index f242240d8..8a794105f 100644 --- a/packages/pyright-internal/src/tests/samples/callbackProtocol2.py +++ b/packages/pyright-internal/src/tests/samples/callbackProtocol2.py @@ -9,8 +9,7 @@ OutputT = TypeVar("OutputT", covariant=True) class MyCallable(Protocol[InputT, OutputT]): - def __call__(self, inputs: InputT) -> OutputT: - ... + def __call__(self, inputs: InputT) -> OutputT: ... class Class1: diff --git a/packages/pyright-internal/src/tests/samples/callbackProtocol3.py b/packages/pyright-internal/src/tests/samples/callbackProtocol3.py index 1f786790f..f3e316c9d 100644 --- a/packages/pyright-internal/src/tests/samples/callbackProtocol3.py +++ b/packages/pyright-internal/src/tests/samples/callbackProtocol3.py @@ -7,17 +7,14 @@ TE = TypeVar("TE", bound=Exception) class CallbackProtocol1(Protocol[TE]): - def __call__(self, s_exc: Exception, t_exc_class: Type[TE]) -> TE: - ... + def __call__(self, s_exc: Exception, t_exc_class: Type[TE]) -> TE: ... -def func1(s_exc: Exception, t_exc_class: Type[TE]) -> TE: - ... +def func1(s_exc: Exception, t_exc_class: Type[TE]) -> TE: ... def func2( s_exc_class: Exception, t_exc_class: Type[TE], mapper: CallbackProtocol1[TE] = func1, -): - ... +): ... diff --git a/packages/pyright-internal/src/tests/samples/callbackProtocol4.py b/packages/pyright-internal/src/tests/samples/callbackProtocol4.py index 77fbc3369..ac35da9c9 100644 --- a/packages/pyright-internal/src/tests/samples/callbackProtocol4.py +++ b/packages/pyright-internal/src/tests/samples/callbackProtocol4.py @@ -6,15 +6,12 @@ from typing import Any, Protocol, overload class P1(Protocol): @overload - def __call__(self, x: int) -> int: - ... + def __call__(self, x: int) -> int: ... @overload - def __call__(self, x: str) -> str: - ... + def __call__(self, x: str) -> str: ... - def __call__(self, x: Any) -> Any: - ... + def __call__(self, x: Any) -> Any: ... def func0(x: Any) -> Any: @@ -32,13 +29,11 @@ a1: P1 = func1 @overload -def of1(x: int) -> int: - ... +def of1(x: int) -> int: ... @overload -def of1(x: str) -> str: - ... +def of1(x: str) -> str: ... def of1(x: Any) -> Any: @@ -46,13 +41,11 @@ def of1(x: Any) -> Any: @overload -def of2(x: int) -> complex: - ... +def of2(x: int) -> complex: ... @overload -def of2(x: str) -> str: - ... +def of2(x: str) -> str: ... def of2(x: Any) -> Any: @@ -66,8 +59,7 @@ b1: P1 = of2 class P2(Protocol): - def __call__(self, *args: int) -> Any: - ... + def __call__(self, *args: int) -> Any: ... a: P2 = lambda *args: map(lambda arg: arg + 0, args) diff --git a/packages/pyright-internal/src/tests/samples/callbackProtocol6.py b/packages/pyright-internal/src/tests/samples/callbackProtocol6.py index 095df7e5a..5b465aeea 100644 --- a/packages/pyright-internal/src/tests/samples/callbackProtocol6.py +++ b/packages/pyright-internal/src/tests/samples/callbackProtocol6.py @@ -6,22 +6,18 @@ from typing import Protocol # Callback with positional parameter with default arg value. class Callback1(Protocol): - def __call__(self, path: str = ...) -> str: - ... + def __call__(self, path: str = ...) -> str: ... # Callback with positional parameter without default arg value. class Callback2(Protocol): - def __call__(self, path: str) -> str: - ... + def __call__(self, path: str) -> str: ... -def func1_1(path: str = "") -> str: - ... +def func1_1(path: str = "") -> str: ... -def func1_2(path: str) -> str: - ... +def func1_2(path: str) -> str: ... val1_1: Callback1 = func1_1 @@ -36,22 +32,18 @@ val2_2: Callback2 = func1_2 # Callback with keyword parameter with default arg value. class Callback3(Protocol): - def __call__(self, *, path: str = ...) -> str: - ... + def __call__(self, *, path: str = ...) -> str: ... # Callback with keyword parameter without default arg value. class Callback4(Protocol): - def __call__(self, *, path: str) -> str: - ... + def __call__(self, *, path: str) -> str: ... -def func3_1(*, path: str = "") -> str: - ... +def func3_1(*, path: str = "") -> str: ... -def func3_2(*, path: str) -> str: - ... +def func3_2(*, path: str) -> str: ... val3_1: Callback3 = func3_1 diff --git a/packages/pyright-internal/src/tests/samples/callbackProtocol7.py b/packages/pyright-internal/src/tests/samples/callbackProtocol7.py index 7656aaf5d..ccf414603 100644 --- a/packages/pyright-internal/src/tests/samples/callbackProtocol7.py +++ b/packages/pyright-internal/src/tests/samples/callbackProtocol7.py @@ -5,11 +5,10 @@ from typing import Any, Protocol class X(Protocol): - def __call__(self, x: int, /, y: str) -> Any: - ... + def __call__(self, x: int, /, y: str) -> Any: ... -def f1(x: int, /, y: str, z: None = None) -> Any: - ... + +def f1(x: int, /, y: str, z: None = None) -> Any: ... x: X = f1 diff --git a/packages/pyright-internal/src/tests/samples/callbackProtocol8.py b/packages/pyright-internal/src/tests/samples/callbackProtocol8.py index 4025689c2..644540421 100644 --- a/packages/pyright-internal/src/tests/samples/callbackProtocol8.py +++ b/packages/pyright-internal/src/tests/samples/callbackProtocol8.py @@ -5,12 +5,10 @@ from typing import Any, Protocol class P(Protocol): - def __call__(self, *args: Any, kwarg0: Any, kwarg1: Any) -> None: - ... + def __call__(self, *args: Any, kwarg0: Any, kwarg1: Any) -> None: ... -def f(*args: Any, kwarg0: Any, kwarg1: Any) -> None: - ... +def f(*args: Any, kwarg0: Any, kwarg1: Any) -> None: ... p: P = f diff --git a/packages/pyright-internal/src/tests/samples/circular2.py b/packages/pyright-internal/src/tests/samples/circular2.py index 50cf6cbc9..bada1c518 100644 --- a/packages/pyright-internal/src/tests/samples/circular2.py +++ b/packages/pyright-internal/src/tests/samples/circular2.py @@ -15,8 +15,7 @@ class A: _T = TypeVar("_T", bound=A) -class B(Generic[_T]): - ... +class B(Generic[_T]): ... class C(A): diff --git a/packages/pyright-internal/src/tests/samples/classGetItem1.py b/packages/pyright-internal/src/tests/samples/classGetItem1.py index 194e16aff..fa2cca68f 100644 --- a/packages/pyright-internal/src/tests/samples/classGetItem1.py +++ b/packages/pyright-internal/src/tests/samples/classGetItem1.py @@ -9,8 +9,7 @@ class ClassA: # This should generate a warning because __class_getitem__ # is implicitly a classmethod and should use cls rather than # self. - def __class_getitem__(self, args: tuple[int, ...]) -> None: - ... + def __class_getitem__(self, args: tuple[int, ...]) -> None: ... reveal_type(ClassA[10, 63], expected_text="type[ClassA]") @@ -23,8 +22,7 @@ _S = TypeVar("_S") class ClassB(Generic[_T, _S]): # Even though this class has a __class_getitem__ method, # it will be assumed to follow normal generic class semantics. - def __class_getitem__(cls, args: tuple[int, ...]) -> None: - ... + def __class_getitem__(cls, args: tuple[int, ...]) -> None: ... reveal_type(ClassB[int, str], expected_text="type[ClassB[int, str]]") diff --git a/packages/pyright-internal/src/tests/samples/classes10.py b/packages/pyright-internal/src/tests/samples/classes10.py index bbd8ff210..7a412549e 100644 --- a/packages/pyright-internal/src/tests/samples/classes10.py +++ b/packages/pyright-internal/src/tests/samples/classes10.py @@ -19,7 +19,6 @@ def dynamic_subclass1(cls: type[T_A]): def dynamic_subclass2(base: type[A] | None): - class SubClass(base or A): - ... + class SubClass(base or A): ... return SubClass diff --git a/packages/pyright-internal/src/tests/samples/classes11.py b/packages/pyright-internal/src/tests/samples/classes11.py index e0d390b79..ec68153a0 100644 --- a/packages/pyright-internal/src/tests/samples/classes11.py +++ b/packages/pyright-internal/src/tests/samples/classes11.py @@ -6,34 +6,27 @@ from typing import Collection, Iterator, Mapping, Sequence, TypeVar # This should generate an error. class A(Mapping[str, int], Collection[int]): - def __len__(self) -> int: - ... + def __len__(self) -> int: ... - def __iter__(self) -> Iterator[str]: - ... + def __iter__(self) -> Iterator[str]: ... # This should generate an error. -class B(Mapping[str, int], Sequence[int]): - ... +class B(Mapping[str, int], Sequence[int]): ... # This should generate an error. -class C(Sequence[int], Mapping[str, int]): - ... +class C(Sequence[int], Mapping[str, int]): ... -class D(Sequence[float], Mapping[float, int]): - ... +class D(Sequence[float], Mapping[float, int]): ... -class E(Sequence[float], Mapping[int, int]): - ... +class E(Sequence[float], Mapping[int, int]): ... # This should generate an error. -class F(Mapping[int, int], Sequence[float]): - ... +class F(Mapping[int, int], Sequence[float]): ... T = TypeVar("T") @@ -41,16 +34,13 @@ S = TypeVar("S") class G(Mapping[T, S], Collection[T]): - def __len__(self) -> int: - ... + def __len__(self) -> int: ... + + def __iter__(self) -> Iterator[T]: ... - def __iter__(self) -> Iterator[T]: - ... # This should generate an error. class H(Mapping[T, S], Collection[S]): - def __len__(self) -> int: - ... + def __len__(self) -> int: ... - def __iter__(self) -> Iterator[T]: - ... + def __iter__(self) -> Iterator[T]: ... diff --git a/packages/pyright-internal/src/tests/samples/classes5.py b/packages/pyright-internal/src/tests/samples/classes5.py index cfa26dde4..394d982b3 100644 --- a/packages/pyright-internal/src/tests/samples/classes5.py +++ b/packages/pyright-internal/src/tests/samples/classes5.py @@ -215,8 +215,7 @@ class SubclassTuple2(ParentClass2): cv_decl_1, cv_decl_2, cv_decl_3 = (3, 4.5, None) -class ConfigBase: - ... +class ConfigBase: ... class ParentClass3(Protocol): @@ -225,13 +224,11 @@ class ParentClass3(Protocol): class ChildClass3(ParentClass3): - class Config1(ConfigBase): - ... + class Config1(ConfigBase): ... # This should generate an error if reportIncompatibleVariableOverride # is enabled. - class Config2: - ... + class Config2: ... class PeerClass1: diff --git a/packages/pyright-internal/src/tests/samples/classes9.py b/packages/pyright-internal/src/tests/samples/classes9.py index 81e398bce..747950952 100644 --- a/packages/pyright-internal/src/tests/samples/classes9.py +++ b/packages/pyright-internal/src/tests/samples/classes9.py @@ -66,5 +66,4 @@ class TD_A2(TypedDict): # This should generate an error for x but not y. -class TD_A(TD_A1, TD_A2): - ... +class TD_A(TD_A1, TD_A2): ... diff --git a/packages/pyright-internal/src/tests/samples/codeFlow6.py b/packages/pyright-internal/src/tests/samples/codeFlow6.py index e8894d0ce..0e229af74 100644 --- a/packages/pyright-internal/src/tests/samples/codeFlow6.py +++ b/packages/pyright-internal/src/tests/samples/codeFlow6.py @@ -5,31 +5,25 @@ from typing import Any, Callable, overload -class C: - ... +class C: ... @overload -def func1(v: Callable[[], int]) -> int: - ... +def func1(v: Callable[[], int]) -> int: ... @overload -def func1(v: Callable[[], list[C]]) -> list[C]: - ... +def func1(v: Callable[[], list[C]]) -> list[C]: ... -def func1(v: Any) -> Any: - ... +def func1(v: Any) -> Any: ... -def func2(v: list[C]): - ... +def func2(v: list[C]): ... t = func1(lambda: func3()) t.append(C()) -def func3() -> list[C]: - ... +def func3() -> list[C]: ... diff --git a/packages/pyright-internal/src/tests/samples/codeFlow7.py b/packages/pyright-internal/src/tests/samples/codeFlow7.py index e8894d0ce..0e229af74 100644 --- a/packages/pyright-internal/src/tests/samples/codeFlow7.py +++ b/packages/pyright-internal/src/tests/samples/codeFlow7.py @@ -5,31 +5,25 @@ from typing import Any, Callable, overload -class C: - ... +class C: ... @overload -def func1(v: Callable[[], int]) -> int: - ... +def func1(v: Callable[[], int]) -> int: ... @overload -def func1(v: Callable[[], list[C]]) -> list[C]: - ... +def func1(v: Callable[[], list[C]]) -> list[C]: ... -def func1(v: Any) -> Any: - ... +def func1(v: Any) -> Any: ... -def func2(v: list[C]): - ... +def func2(v: list[C]): ... t = func1(lambda: func3()) t.append(C()) -def func3() -> list[C]: - ... +def func3() -> list[C]: ... diff --git a/packages/pyright-internal/src/tests/samples/comparison1.py b/packages/pyright-internal/src/tests/samples/comparison1.py index 4df859c0e..20bc755d9 100644 --- a/packages/pyright-internal/src/tests/samples/comparison1.py +++ b/packages/pyright-internal/src/tests/samples/comparison1.py @@ -30,12 +30,10 @@ def func1(os: OS, val: Literal[1, "linux"]): return True -class ClassA: - ... +class ClassA: ... -class ClassB: - ... +class ClassB: ... _T1 = TypeVar("_T1") diff --git a/packages/pyright-internal/src/tests/samples/complex1.py b/packages/pyright-internal/src/tests/samples/complex1.py index f61b227ab..91d8762b7 100644 --- a/packages/pyright-internal/src/tests/samples/complex1.py +++ b/packages/pyright-internal/src/tests/samples/complex1.py @@ -8,8 +8,7 @@ b = a + 4 c = 1.2 * a -def requires_complex(val: complex): - ... +def requires_complex(val: complex): ... requires_complex(a) diff --git a/packages/pyright-internal/src/tests/samples/constrainedTypeVar11.py b/packages/pyright-internal/src/tests/samples/constrainedTypeVar11.py index 09c8ba1b0..b85717573 100644 --- a/packages/pyright-internal/src/tests/samples/constrainedTypeVar11.py +++ b/packages/pyright-internal/src/tests/samples/constrainedTypeVar11.py @@ -18,8 +18,7 @@ def add1(value: _T1) -> _T1: class IntSubclass2(int): - def __add__(self, value: object) -> "IntSubclass2": - ... + def __add__(self, value: object) -> "IntSubclass2": ... _T2 = TypeVar("_T2", int, IntSubclass2) diff --git a/packages/pyright-internal/src/tests/samples/constrainedTypeVar12.py b/packages/pyright-internal/src/tests/samples/constrainedTypeVar12.py index aa4233d23..63653972f 100644 --- a/packages/pyright-internal/src/tests/samples/constrainedTypeVar12.py +++ b/packages/pyright-internal/src/tests/samples/constrainedTypeVar12.py @@ -6,8 +6,7 @@ from os import PathLike from typing import AnyStr -def func1(path: AnyStr | PathLike[AnyStr]) -> AnyStr: - ... +def func1(path: AnyStr | PathLike[AnyStr]) -> AnyStr: ... def func2(value: AnyStr) -> AnyStr: diff --git a/packages/pyright-internal/src/tests/samples/constrainedTypeVar14.py b/packages/pyright-internal/src/tests/samples/constrainedTypeVar14.py index fab9b93c1..53c74bc52 100644 --- a/packages/pyright-internal/src/tests/samples/constrainedTypeVar14.py +++ b/packages/pyright-internal/src/tests/samples/constrainedTypeVar14.py @@ -5,16 +5,13 @@ from typing import TypeVar, Generic -class A: - ... +class A: ... -class B: - ... +class B: ... -class A2(A): - ... +class A2(A): ... T = TypeVar("T", A, B) diff --git a/packages/pyright-internal/src/tests/samples/constrainedTypeVar15.py b/packages/pyright-internal/src/tests/samples/constrainedTypeVar15.py index f47ea2283..be2691a1c 100644 --- a/packages/pyright-internal/src/tests/samples/constrainedTypeVar15.py +++ b/packages/pyright-internal/src/tests/samples/constrainedTypeVar15.py @@ -5,8 +5,7 @@ from typing import AnyStr, Iterable, TypeVar, Generic from dataclasses import dataclass -class ClassA: - ... +class ClassA: ... _T = TypeVar("_T", int | float, ClassA) diff --git a/packages/pyright-internal/src/tests/samples/constrainedTypeVar16.py b/packages/pyright-internal/src/tests/samples/constrainedTypeVar16.py index 188ae0d2a..b4913a072 100644 --- a/packages/pyright-internal/src/tests/samples/constrainedTypeVar16.py +++ b/packages/pyright-internal/src/tests/samples/constrainedTypeVar16.py @@ -13,12 +13,10 @@ _T1 = TypeVar("_T1") AnyStr = TypeVar("AnyStr", str, bytes) -def exists2(path: AnyStr) -> bool: - ... +def exists2(path: AnyStr) -> bool: ... -def filter2(f: Callable[[_T1], Any], i: Iterable[_T1]) -> Iterator[_T1]: - ... +def filter2(f: Callable[[_T1], Any], i: Iterable[_T1]) -> Iterator[_T1]: ... result = filter2(exists2, ["hello", "world"]) diff --git a/packages/pyright-internal/src/tests/samples/constrainedTypeVar17.py b/packages/pyright-internal/src/tests/samples/constrainedTypeVar17.py index 4e34226c4..002f583ba 100644 --- a/packages/pyright-internal/src/tests/samples/constrainedTypeVar17.py +++ b/packages/pyright-internal/src/tests/samples/constrainedTypeVar17.py @@ -8,12 +8,10 @@ from typing import Any, AnyStr, Optional, Protocol, TypeVar, Union -class Array: - ... +class Array: ... -class MMap: - ... +class MMap: ... # Note that this union contains types that are not compatible @@ -25,29 +23,24 @@ _T_co = TypeVar("_T_co", covariant=True) class BufferedWriter: - def write(self, __buffer: ReadableBuffer) -> int: - ... + def write(self, __buffer: ReadableBuffer) -> int: ... class SupportsWrite(Protocol[_T_contra]): - def write(self, __s: _T_contra) -> Any: - ... + def write(self, __s: _T_contra) -> Any: ... class SupportsRead(Protocol[_T_co]): - def read(self, __length: int = ...) -> _T_co: - ... + def read(self, __length: int = ...) -> _T_co: ... class BufferedReader: - def read(self, __size: Optional[int] = ...) -> bytes: - ... + def read(self, __size: Optional[int] = ...) -> bytes: ... def copyfileobj( fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = ... -) -> AnyStr: - ... +) -> AnyStr: ... def f(fr: BufferedReader, fw: BufferedWriter): diff --git a/packages/pyright-internal/src/tests/samples/constrainedTypeVar18.py b/packages/pyright-internal/src/tests/samples/constrainedTypeVar18.py index 3750d03b1..c561734f3 100644 --- a/packages/pyright-internal/src/tests/samples/constrainedTypeVar18.py +++ b/packages/pyright-internal/src/tests/samples/constrainedTypeVar18.py @@ -9,13 +9,11 @@ T = TypeVar("T") class Async: - def fn(self, returnable: T) -> Awaitable[T]: - ... + def fn(self, returnable: T) -> Awaitable[T]: ... class Sync: - def fn(self, returnable: T) -> T: - ... + def fn(self, returnable: T) -> T: ... T = TypeVar("T", Async, Sync) diff --git a/packages/pyright-internal/src/tests/samples/constrainedTypeVar2.py b/packages/pyright-internal/src/tests/samples/constrainedTypeVar2.py index 4b6dfcb63..40c35e03f 100644 --- a/packages/pyright-internal/src/tests/samples/constrainedTypeVar2.py +++ b/packages/pyright-internal/src/tests/samples/constrainedTypeVar2.py @@ -42,8 +42,7 @@ archive_path = data_dir / "hello" shutil.rmtree(archive_path) -def func1(a: AnyStr, b: AnyStr) -> None: - ... +def func1(a: AnyStr, b: AnyStr) -> None: ... def func2(a: Union[str, bytes], b: Union[str, bytes]): @@ -51,27 +50,22 @@ def func2(a: Union[str, bytes], b: Union[str, bytes]): func1(a, b) -class A: - ... +class A: ... -class B: - ... +class B: ... -class C: - ... +class C: ... -class D: - ... +class D: ... T3 = TypeVar("T3", A, B, Union[C, D]) -def do_something(value: T3) -> T3: - ... +def do_something(value: T3) -> T3: ... def func10(value: Union[C, D]): diff --git a/packages/pyright-internal/src/tests/samples/constrainedTypeVar7.py b/packages/pyright-internal/src/tests/samples/constrainedTypeVar7.py index 9a124b2ec..3537785c6 100644 --- a/packages/pyright-internal/src/tests/samples/constrainedTypeVar7.py +++ b/packages/pyright-internal/src/tests/samples/constrainedTypeVar7.py @@ -4,8 +4,7 @@ from typing import Iterator, Optional, Sequence, TypeVar, Union -def func0(a: Union[int, float]): - ... +def func0(a: Union[int, float]): ... _T1 = TypeVar("_T1", int, float) @@ -39,12 +38,10 @@ def func5(xs: Sequence[Optional[_T2]]) -> Iterator[_T2]: return func3(xs) -class A: - ... +class A: ... -class B(A): - ... +class B(A): ... _T4 = TypeVar("_T4", A, B) diff --git a/packages/pyright-internal/src/tests/samples/constructor10.py b/packages/pyright-internal/src/tests/samples/constructor10.py index 3ae40e0bc..e3df1abc4 100644 --- a/packages/pyright-internal/src/tests/samples/constructor10.py +++ b/packages/pyright-internal/src/tests/samples/constructor10.py @@ -10,8 +10,7 @@ _T = TypeVar("_T") class A(Iterator[_T_co]): - def __new__(cls, __iterable: Iterable[_T]) -> "A[tuple[_T, _T]]": - ... + def __new__(cls, __iterable: Iterable[_T]) -> "A[tuple[_T, _T]]": ... def __next__(self) -> _T_co: ... @@ -22,8 +21,7 @@ def func1(iterable: Iterable[_T]) -> Iterator[tuple[_T, _T, _T]]: class B(Generic[_T_co]): - def __new__(cls, __iter1: Iterable[_T]) -> "B[_T]": - ... + def __new__(cls, __iter1: Iterable[_T]) -> "B[_T]": ... def func2(p1: list[dict]): diff --git a/packages/pyright-internal/src/tests/samples/constructor15.py b/packages/pyright-internal/src/tests/samples/constructor15.py index caad8a4c9..08ac7ed21 100644 --- a/packages/pyright-internal/src/tests/samples/constructor15.py +++ b/packages/pyright-internal/src/tests/samples/constructor15.py @@ -9,38 +9,32 @@ _M = TypeVar("_M") class A(Generic[_M, _N]): - def __new__(cls, m: _M, n: _N) -> "A[_M, _N]": - ... + def __new__(cls, m: _M, n: _N) -> "A[_M, _N]": ... a: A[Literal[3], Literal[4]] = A(3, 4) class B(Generic[_M, _N]): - def __new__(cls, m: _M, n: _N) -> "B[_M, _N]": - ... + def __new__(cls, m: _M, n: _N) -> "B[_M, _N]": ... - def __init__(self, *args: Any, **kwargs: Any) -> None: - ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... b: B[Literal[3], Literal[4]] = B(3, 4) class C(Generic[_M, _N]): - def __new__(cls, m: _M, n: _N) -> "C[_M, _N]": - ... + def __new__(cls, m: _M, n: _N) -> "C[_M, _N]": ... - def __init__(self, m: _M, n: _N) -> None: - ... + def __init__(self, m: _M, n: _N) -> None: ... c: C[Literal[3], Literal[4]] = C(3, 4) class D(Generic[_M, _N]): - def __new__(cls, m: _M, n: _N) -> Self: - ... + def __new__(cls, m: _M, n: _N) -> Self: ... d: D[Literal[3], Literal[4]] = D(3, 4) diff --git a/packages/pyright-internal/src/tests/samples/constructor17.py b/packages/pyright-internal/src/tests/samples/constructor17.py index 2de95a72d..4970521c7 100644 --- a/packages/pyright-internal/src/tests/samples/constructor17.py +++ b/packages/pyright-internal/src/tests/samples/constructor17.py @@ -13,24 +13,21 @@ class A(Generic[T]): class B(Generic[T]): - def __init__(self): - ... + def __init__(self): ... class C(Generic[T]): def __new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs) - def __init__(self): - ... + def __init__(self): ... class D(Generic[T]): def __new__(cls, *args, **kwargs): return super().__new__(cls, *args, **kwargs) - def __init__(self, a: T): - ... + def __init__(self, a: T): ... class E(Generic[T]): diff --git a/packages/pyright-internal/src/tests/samples/constructor2.py b/packages/pyright-internal/src/tests/samples/constructor2.py index bfd7f6a24..fbace1c15 100644 --- a/packages/pyright-internal/src/tests/samples/constructor2.py +++ b/packages/pyright-internal/src/tests/samples/constructor2.py @@ -178,8 +178,7 @@ def s18(): class Plant(Generic[_T1]): - def __new__(cls, o: _T1) -> Self: - ... + def __new__(cls, o: _T1) -> Self: ... plant: Plant[float] = Plant(0) diff --git a/packages/pyright-internal/src/tests/samples/constructor22.py b/packages/pyright-internal/src/tests/samples/constructor22.py index f4f23e731..ea4b433ae 100644 --- a/packages/pyright-internal/src/tests/samples/constructor22.py +++ b/packages/pyright-internal/src/tests/samples/constructor22.py @@ -9,14 +9,11 @@ T = TypeVar("T", covariant=True) class A(Protocol[T]): - def a(self) -> "A[Tuple[T]]": - ... + def a(self) -> "A[Tuple[T]]": ... - def b(self) -> "A[Tuple[T]]": - ... + def b(self) -> "A[Tuple[T]]": ... - def c(self) -> "T": - ... + def c(self) -> "T": ... class B(Generic[T]): diff --git a/packages/pyright-internal/src/tests/samples/constructor24.py b/packages/pyright-internal/src/tests/samples/constructor24.py index 603a7363f..e544189cf 100644 --- a/packages/pyright-internal/src/tests/samples/constructor24.py +++ b/packages/pyright-internal/src/tests/samples/constructor24.py @@ -72,20 +72,17 @@ def func1(obv: Container[T], default_value: T = None) -> None: obv.on_next(default_value) -class A: - ... +class A: ... T_A = TypeVar("T_A", bound=A) class B(Generic[T]): - def __init__(self, c: Callable[[], T]): - ... + def __init__(self, c: Callable[[], T]): ... -def func2(cls: type[T_A] = A) -> Callable[[], T_A]: - ... +def func2(cls: type[T_A] = A) -> Callable[[], T_A]: ... B(func2()) diff --git a/packages/pyright-internal/src/tests/samples/constructor27.py b/packages/pyright-internal/src/tests/samples/constructor27.py index 31552441d..b34f9d27d 100644 --- a/packages/pyright-internal/src/tests/samples/constructor27.py +++ b/packages/pyright-internal/src/tests/samples/constructor27.py @@ -11,22 +11,18 @@ T = TypeVar("T", contravariant=True) S = TypeVar("S", contravariant=True) -class ClassA(Generic[T]): - ... +class ClassA(Generic[T]): ... -class ClassB(Generic[S, T], ClassA[T]): - ... +class ClassB(Generic[S, T], ClassA[T]): ... class ClassC(ClassB[S, T]): - def __new__(cls, subcon: ClassA[S]) -> ClassC[S, list[S]]: - ... + def __new__(cls, subcon: ClassA[S]) -> ClassC[S, list[S]]: ... class ClassD(ClassB[S, T]): - def __new__(cls, subcon: ClassA[S]) -> ClassD[S, list[S]]: - ... + def __new__(cls, subcon: ClassA[S]) -> ClassD[S, list[S]]: ... c = ClassA[int]() diff --git a/packages/pyright-internal/src/tests/samples/constructor30.py b/packages/pyright-internal/src/tests/samples/constructor30.py index 4ede66b65..e2bae00b4 100644 --- a/packages/pyright-internal/src/tests/samples/constructor30.py +++ b/packages/pyright-internal/src/tests/samples/constructor30.py @@ -29,3 +29,11 @@ def func1(t: type[TA]) -> TA: ... b = B(func1, A) reveal_type(b, expected_text="B[(t: type[A]), A]") + + +class C(Generic[TA]): + def __init__(self, _type: type[TA]) -> None: ... + + +c = B(C, A) +reveal_type(c, expected_text="B[(_type: type[A]), C[A]]") diff --git a/packages/pyright-internal/src/tests/samples/constructor9.py b/packages/pyright-internal/src/tests/samples/constructor9.py index b4501e96a..6ca11eab5 100644 --- a/packages/pyright-internal/src/tests/samples/constructor9.py +++ b/packages/pyright-internal/src/tests/samples/constructor9.py @@ -9,8 +9,7 @@ T_A = TypeVar("T_A", bound="A") class A(ABC): @abstractmethod - def some_method(self) -> str: - ... + def some_method(self) -> str: ... def some_factory_method_1(self): return type(self)() diff --git a/packages/pyright-internal/src/tests/samples/coroutines4.py b/packages/pyright-internal/src/tests/samples/coroutines4.py new file mode 100644 index 000000000..32967916a --- /dev/null +++ b/packages/pyright-internal/src/tests/samples/coroutines4.py @@ -0,0 +1,17 @@ +# This sample tests the case where an inner coroutine with an inferred +# return type is referenced in a manner that results in recursion. + +import asyncio + + +def func1(replace_inner: bool) -> None: + inner = lambda: None + + async def wrapper(): + inner() + + wrapped_fn = wrapper() + asyncio.create_task(wrapped_fn) + + if replace_inner: + inner = lambda: None diff --git a/packages/pyright-internal/src/tests/samples/dataclass9.py b/packages/pyright-internal/src/tests/samples/dataclass9.py index 324a3af0d..d6fa5f481 100644 --- a/packages/pyright-internal/src/tests/samples/dataclass9.py +++ b/packages/pyright-internal/src/tests/samples/dataclass9.py @@ -12,8 +12,9 @@ class IsDataclass(Protocol): __dataclass_fields__: ClassVar[dict[str, Any]] -def dataclass_only(x: IsDataclass): - ... # do something that only makes sense with a dataclass +def dataclass_only( + x: IsDataclass, +): ... # do something that only makes sense with a dataclass @dataclass diff --git a/packages/pyright-internal/src/tests/samples/dataclassDescriptors1.py b/packages/pyright-internal/src/tests/samples/dataclassDescriptors1.py index bd3bfe1c4..43a368cf9 100644 --- a/packages/pyright-internal/src/tests/samples/dataclassDescriptors1.py +++ b/packages/pyright-internal/src/tests/samples/dataclassDescriptors1.py @@ -7,12 +7,10 @@ from typing import Any, cast, overload class MyDescriptor: @overload - def __get__(self, __obj: None, __owner: Any) -> "MyDescriptor": - ... + def __get__(self, __obj: None, __owner: Any) -> "MyDescriptor": ... @overload - def __get__(self, __obj: object, __owner: Any) -> int: - ... + def __get__(self, __obj: object, __owner: Any) -> int: ... def __get__(self, __obj: object | None, __owner: Any) -> "int | MyDescriptor": if __obj is None: diff --git a/packages/pyright-internal/src/tests/samples/dataclassPostInit1.py b/packages/pyright-internal/src/tests/samples/dataclassPostInit1.py index 871dbf67b..297371ffc 100644 --- a/packages/pyright-internal/src/tests/samples/dataclassPostInit1.py +++ b/packages/pyright-internal/src/tests/samples/dataclassPostInit1.py @@ -12,8 +12,7 @@ class A: b: InitVar[str] c: InitVar[bool] - def __post_init__(self, x: float, y: str, z: int, xx: int = 3) -> None: - ... + def __post_init__(self, x: float, y: str, z: int, xx: int = 3) -> None: ... @dataclass @@ -21,8 +20,7 @@ class B: items: list[int] # This should generate an error because the number of InitVars is zero. - def __post_init__(self, x: list[int]) -> None: - ... + def __post_init__(self, x: list[int]) -> None: ... @dataclass @@ -32,8 +30,7 @@ class C: items: list[int] = field(init=False) # This should generate an error because the number of InitVars is 1. - def __post_init__(self) -> None: - ... + def __post_init__(self) -> None: ... @dataclass @@ -41,8 +38,7 @@ class D: iterable: InitVar[Iterable[int]] # This should generate an error because the type is incompatible. - def __post_init__(self, iterable: Iterable[str]) -> None: - ... + def __post_init__(self, iterable: Iterable[str]) -> None: ... @dataclass @@ -50,8 +46,7 @@ class E: _name: InitVar[str] = field() name: str = field(init=False) - def __post_init__(self, _name: str): - ... + def __post_init__(self, _name: str): ... @dataclass @@ -59,5 +54,4 @@ class F(E): _age: InitVar[int] = field() age: int = field(init=False) - def __post_init__(self, _name: str, _age: int): - ... + def __post_init__(self, _name: str, _age: int): ... diff --git a/packages/pyright-internal/src/tests/samples/dataclassTransform3.py b/packages/pyright-internal/src/tests/samples/dataclassTransform3.py index 4f2a5edbf..6b72b366d 100644 --- a/packages/pyright-internal/src/tests/samples/dataclassTransform3.py +++ b/packages/pyright-internal/src/tests/samples/dataclassTransform3.py @@ -18,14 +18,12 @@ def __dataclass_transform__( class ModelField: - def __init__(self, *, init: bool = True, default: Any | None = None) -> None: - ... + def __init__(self, *, init: bool = True, default: Any | None = None) -> None: ... def model_field( *, init: bool = True, default: Any | None = None, alias: str | None = None -) -> Any: - ... +) -> Any: ... @__dataclass_transform__( @@ -41,8 +39,7 @@ class ModelBase: frozen: bool = False, kw_only: bool = True, order: bool = True, - ) -> None: - ... + ) -> None: ... class Customer1(ModelBase, frozen=True): @@ -102,8 +99,7 @@ class GenericModelBase(Generic[_T]): frozen: bool = False, kw_only: bool = True, order: bool = True, - ) -> None: - ... + ) -> None: ... class GenericCustomer(GenericModelBase[int]): diff --git a/packages/pyright-internal/src/tests/samples/dataclassTransform4.py b/packages/pyright-internal/src/tests/samples/dataclassTransform4.py index 449ef2f42..d36f3797e 100644 --- a/packages/pyright-internal/src/tests/samples/dataclassTransform4.py +++ b/packages/pyright-internal/src/tests/samples/dataclassTransform4.py @@ -18,8 +18,7 @@ def field1( default: str | None = None, resolver: Callable[[], Any], init: Literal[False] = False, -) -> Any: - ... +) -> Any: ... @overload @@ -28,8 +27,7 @@ def field1( default: str | None = None, resolver: None = None, init: Literal[True] = True, -) -> Any: - ... +) -> Any: ... def field1( @@ -37,12 +35,10 @@ def field1( default: str | None = None, resolver: Callable[[], Any] | None = None, init: bool = True, -) -> Any: - ... +) -> Any: ... -def field2(*, init=False, kw_only=True) -> Any: - ... +def field2(*, init=False, kw_only=True) -> Any: ... def __dataclass_transform__( @@ -58,8 +54,7 @@ def __dataclass_transform__( @__dataclass_transform__(kw_only_default=True, field_specifiers=(field1, field2)) -def create_model(*, init: bool = True) -> Callable[[type[T]], type[T]]: - ... +def create_model(*, init: bool = True) -> Callable[[type[T]], type[T]]: ... @create_model() diff --git a/packages/pyright-internal/src/tests/samples/decorator2.py b/packages/pyright-internal/src/tests/samples/decorator2.py index d25f1c720..c199b9874 100644 --- a/packages/pyright-internal/src/tests/samples/decorator2.py +++ b/packages/pyright-internal/src/tests/samples/decorator2.py @@ -6,26 +6,21 @@ F = TypeVar("F", bound=Callable[[], None]) @overload -def atomic(__func: F) -> F: - ... +def atomic(__func: F) -> F: ... @overload -def atomic(*, savepoint: bool = True) -> Callable[[F], F]: - ... +def atomic(*, savepoint: bool = True) -> Callable[[F], F]: ... def atomic( __func: Optional[Callable[..., None]] = None, *, savepoint: bool = True -) -> Union[Callable[[], None], Callable[[Callable[[], None]], Callable[[], None]]]: - ... +) -> Union[Callable[[], None], Callable[[Callable[[], None]], Callable[[], None]]]: ... @atomic -def func1() -> None: - ... +def func1() -> None: ... @atomic(savepoint=False) -def func2() -> None: - ... +def func2() -> None: ... diff --git a/packages/pyright-internal/src/tests/samples/decorator7.py b/packages/pyright-internal/src/tests/samples/decorator7.py index 56a91ed28..324920225 100644 --- a/packages/pyright-internal/src/tests/samples/decorator7.py +++ b/packages/pyright-internal/src/tests/samples/decorator7.py @@ -8,8 +8,7 @@ FuncType = Callable[..., Any] FT = TypeVar("FT", bound=FuncType) -def decorate() -> Callable[[FT], FT]: - ... +def decorate() -> Callable[[FT], FT]: ... @decorate() diff --git a/packages/pyright-internal/src/tests/samples/del1.py b/packages/pyright-internal/src/tests/samples/del1.py index 631839fcc..79d08fdd3 100644 --- a/packages/pyright-internal/src/tests/samples/del1.py +++ b/packages/pyright-internal/src/tests/samples/del1.py @@ -50,16 +50,13 @@ reveal_type(x2[0], expected_text="str | int") class ClassC: @property - def x(self) -> str: - ... + def x(self) -> str: ... @x.setter - def x(self, value: str) -> None: - ... + def x(self, value: str) -> None: ... @x.deleter - def x(self) -> None: - ... + def x(self) -> None: ... c = ClassC() diff --git a/packages/pyright-internal/src/tests/samples/descriptor1.py b/packages/pyright-internal/src/tests/samples/descriptor1.py index b7f10f040..a76d952d5 100644 --- a/packages/pyright-internal/src/tests/samples/descriptor1.py +++ b/packages/pyright-internal/src/tests/samples/descriptor1.py @@ -6,36 +6,28 @@ from typing import Any, Literal class A: @property - def prop1(self) -> int | None: - ... + def prop1(self) -> int | None: ... @prop1.setter - def prop1(self, val: int | None) -> None: - ... + def prop1(self, val: int | None) -> None: ... @property - def prop2(self) -> int | None: - ... + def prop2(self) -> int | None: ... @prop2.setter - def prop2(self, val: int) -> None: - ... + def prop2(self, val: int) -> None: ... @prop2.deleter - def prop2(self) -> None: - ... + def prop2(self) -> None: ... @property - def prop3(self) -> int: - ... + def prop3(self) -> int: ... @prop3.setter - def prop3(self, val: int | None) -> None: - ... + def prop3(self, val: int | None) -> None: ... @prop3.deleter - def prop3(self) -> None: - ... + def prop3(self) -> None: ... def func1(obj: A) -> Literal[3]: @@ -72,27 +64,21 @@ def func3(obj: A) -> Literal[3]: class Descriptor1: - def __get__(self, instance: Any, owner: Any) -> int | None: - ... + def __get__(self, instance: Any, owner: Any) -> int | None: ... - def __set__(self, owner: Any, value: int | None) -> None: - ... + def __set__(self, owner: Any, value: int | None) -> None: ... class Descriptor2: - def __get__(self, instance: Any, owner: Any) -> int | None: - ... + def __get__(self, instance: Any, owner: Any) -> int | None: ... - def __set__(self, owner: Any, value: int) -> None: - ... + def __set__(self, owner: Any, value: int) -> None: ... class Descriptor3: - def __get__(self, instance: Any, owner: Any) -> int: - ... + def __get__(self, instance: Any, owner: Any) -> int: ... - def __set__(self, owner: Any, value: int | None) -> None: - ... + def __set__(self, owner: Any, value: int | None) -> None: ... class B: diff --git a/packages/pyright-internal/src/tests/samples/descriptor3.py b/packages/pyright-internal/src/tests/samples/descriptor3.py index 08dd3f3bd..0ae13b460 100644 --- a/packages/pyright-internal/src/tests/samples/descriptor3.py +++ b/packages/pyright-internal/src/tests/samples/descriptor3.py @@ -10,15 +10,14 @@ T = TypeVar("T") class Desc1(Generic[T]): - def __get__(self, instance: object | None, owner: type | None = None) -> list[T]: - ... + def __get__( + self, instance: object | None, owner: type | None = None + ) -> list[T]: ... - def __set__(self, instance: object, value: list[T]) -> None: - ... + def __set__(self, instance: object, value: list[T]) -> None: ... -def func1(factory: Callable[[], list[T]]) -> Desc1[T]: - ... +def func1(factory: Callable[[], list[T]]) -> Desc1[T]: ... class ClassA: diff --git a/packages/pyright-internal/src/tests/samples/duplicateDeclaration1.py b/packages/pyright-internal/src/tests/samples/duplicateDeclaration1.py index 4e335aaa7..89977c37b 100644 --- a/packages/pyright-internal/src/tests/samples/duplicateDeclaration1.py +++ b/packages/pyright-internal/src/tests/samples/duplicateDeclaration1.py @@ -40,13 +40,11 @@ class C: @overload -def a() -> None: - ... +def a() -> None: ... @overload -def a(x: int) -> None: - ... +def a(x: int) -> None: ... # This should generate an error. diff --git a/packages/pyright-internal/src/tests/samples/enum6.py b/packages/pyright-internal/src/tests/samples/enum6.py index 31d965837..d0346919f 100644 --- a/packages/pyright-internal/src/tests/samples/enum6.py +++ b/packages/pyright-internal/src/tests/samples/enum6.py @@ -20,8 +20,7 @@ class Color(Enum): self.foo = True -class NonEnum: - ... +class NonEnum: ... # This should generate an error because enums cannot diff --git a/packages/pyright-internal/src/tests/samples/expression7.py b/packages/pyright-internal/src/tests/samples/expression7.py index 3c687f5be..5b7f52cab 100644 --- a/packages/pyright-internal/src/tests/samples/expression7.py +++ b/packages/pyright-internal/src/tests/samples/expression7.py @@ -1,16 +1,13 @@ # This sample tests various conditions with AND and OR operators. -def func1() -> bool: - ... +def func1() -> bool: ... -def func2() -> int: - ... +def func2() -> int: ... -def func3() -> str: - ... +def func3() -> str: ... reveal_type(func1() and func2(), expected_text="int | Literal[False]") @@ -24,21 +21,17 @@ reveal_type(func2() or func1(), expected_text="int | bool") reveal_type(func3() or func1(), expected_text="str | bool") -class ClassA: - ... +class ClassA: ... -class ClassB: - ... +class ClassB: ... # This should generate an error because binary operators are not allowed # in type annotations. -def func4(a: ClassA and ClassB): - ... +def func4(a: ClassA and ClassB): ... # This should generate an error because binary operators are not allowed # in type annotations. -def func5(a: ClassA or ClassB): - ... +def func5(a: ClassA or ClassB): ... diff --git a/packages/pyright-internal/src/tests/samples/final2.py b/packages/pyright-internal/src/tests/samples/final2.py index ce19e1569..ad5be619b 100644 --- a/packages/pyright-internal/src/tests/samples/final2.py +++ b/packages/pyright-internal/src/tests/samples/final2.py @@ -29,30 +29,24 @@ class ClassA: pass @overload - def func7(self, x: int) -> int: - ... + def func7(self, x: int) -> int: ... @overload - def func7(self, x: str) -> str: - ... + def func7(self, x: str) -> str: ... @final - def func7(self, x: int | str) -> int | str: - ... + def func7(self, x: int | str) -> int | str: ... # This should generate an error because the implementation # of func8 is marked as not final but this overload is. @overload @final - def func8(self, x: int) -> int: - ... + def func8(self, x: int) -> int: ... @overload - def func8(self, x: str) -> str: - ... + def func8(self, x: str) -> str: ... - def func8(self, x: int | str) -> int | str: - ... + def func8(self, x: int | str) -> int | str: ... # This should generate an error because func3 is final. @@ -102,35 +96,29 @@ class ClassB(ClassA): pass @overload - def func7(self, x: int) -> int: - ... + def func7(self, x: int) -> int: ... @overload - def func7(self, x: str) -> str: - ... + def func7(self, x: str) -> str: ... @final # This should generate an error because func7 is # defined as final. - def func7(self, x: int | str) -> int | str: - ... + def func7(self, x: int | str) -> int | str: ... -class Base4: - ... +class Base4: ... class Base5: @final - def __init__(self, v: int) -> None: - ... + def __init__(self, v: int) -> None: ... class C(Base4, Base5): # This should generate an error because it overrides Base5, # and __init__ is marked final there. - def __init__(self) -> None: - ... + def __init__(self) -> None: ... # This should generate an error because @final isn't allowed on diff --git a/packages/pyright-internal/src/tests/samples/function10.py b/packages/pyright-internal/src/tests/samples/function10.py index 6ad606be1..38bb6441c 100644 --- a/packages/pyright-internal/src/tests/samples/function10.py +++ b/packages/pyright-internal/src/tests/samples/function10.py @@ -17,8 +17,7 @@ class Thing2: class ClassA(Generic[T_contra]): - def __init__(self, callback: Callable[[T_contra], Any]) -> None: - ... + def __init__(self, callback: Callable[[T_contra], Any]) -> None: ... def func1(cb: Callable[[Thing1], Any] | Callable[[Thing1 | Thing2], Any]): diff --git a/packages/pyright-internal/src/tests/samples/function6.py b/packages/pyright-internal/src/tests/samples/function6.py index 0c4cc7554..45f5db6ec 100644 --- a/packages/pyright-internal/src/tests/samples/function6.py +++ b/packages/pyright-internal/src/tests/samples/function6.py @@ -5,25 +5,20 @@ from typing import Callable, overload @overload -def func1(a: str) -> str: - ... +def func1(a: str) -> str: ... @overload -def func1(a: int) -> int: - ... +def func1(a: int) -> int: ... -def func1(a: str | int) -> str | int: - ... +def func1(a: str | int) -> str | int: ... -def func2(a: str | int) -> str | int: - ... +def func2(a: str | int) -> str | int: ... -def takes_object(val: object) -> None: - ... +def takes_object(val: object) -> None: ... takes_object(func1) diff --git a/packages/pyright-internal/src/tests/samples/function9.py b/packages/pyright-internal/src/tests/samples/function9.py index 9402d479d..1d08f3ea3 100644 --- a/packages/pyright-internal/src/tests/samples/function9.py +++ b/packages/pyright-internal/src/tests/samples/function9.py @@ -7,19 +7,16 @@ from typing import Callable, TypeVar, Literal _A = TypeVar("_A") -def wrapper1(fn: Callable[[_A], int]) -> _A: - ... +def wrapper1(fn: Callable[[_A], int]) -> _A: ... -def f1(a: Literal[0]) -> int: - ... +def f1(a: Literal[0]) -> int: ... reveal_type(wrapper1(f1), expected_text="Literal[0]") -def wrapper2(fn: Callable[..., _A]) -> Callable[..., _A]: - ... +def wrapper2(fn: Callable[..., _A]) -> Callable[..., _A]: ... def f2() -> Literal["Foo"]: diff --git a/packages/pyright-internal/src/tests/samples/functionMember2.py b/packages/pyright-internal/src/tests/samples/functionMember2.py index 5efb8e453..d4dd93271 100644 --- a/packages/pyright-internal/src/tests/samples/functionMember2.py +++ b/packages/pyright-internal/src/tests/samples/functionMember2.py @@ -4,8 +4,7 @@ # pyright: reportFunctionMemberAccess=error -def func1(a: int) -> str: - ... +def func1(a: int) -> str: ... # This should generate an error because func1 isn't @@ -14,16 +13,13 @@ s1 = func1.__self__ class A: - def method1(self) -> None: - ... + def method1(self) -> None: ... @classmethod - def method2(cls) -> None: - ... + def method2(cls) -> None: ... @staticmethod - def method3() -> None: - ... + def method3() -> None: ... s2 = A().method1.__self__ diff --git a/packages/pyright-internal/src/tests/samples/futureImport1.py b/packages/pyright-internal/src/tests/samples/futureImport1.py index 172c4bc32..5c864d951 100644 --- a/packages/pyright-internal/src/tests/samples/futureImport1.py +++ b/packages/pyright-internal/src/tests/samples/futureImport1.py @@ -2,4 +2,5 @@ # only at the beginning of a file. """ Doc String """ "Extension" -from __future__ import annotations; from __future__ import with_statement +from __future__ import annotations +from __future__ import with_statement diff --git a/packages/pyright-internal/src/tests/samples/futureImport2.py b/packages/pyright-internal/src/tests/samples/futureImport2.py index 0b13be072..f2bb34e25 100644 --- a/packages/pyright-internal/src/tests/samples/futureImport2.py +++ b/packages/pyright-internal/src/tests/samples/futureImport2.py @@ -1,7 +1,8 @@ # This sample tests that __future__ imports are found # only at the beginning of a file. -""" Doc String """ +"""Doc String""" + "Extension" from __future__ import annotations # This should generate an error diff --git a/packages/pyright-internal/src/tests/samples/futureImport3.py b/packages/pyright-internal/src/tests/samples/futureImport3.py index 301113846..7f09203e1 100644 --- a/packages/pyright-internal/src/tests/samples/futureImport3.py +++ b/packages/pyright-internal/src/tests/samples/futureImport3.py @@ -1,4 +1,5 @@ # This sample tests that __future__ imports are found # only at the beginning of a file. -from typing import Any; from __future__ import annotations # This should generate an error +from typing import Any +from __future__ import annotations # This should generate an error diff --git a/packages/pyright-internal/src/tests/samples/generator1.py b/packages/pyright-internal/src/tests/samples/generator1.py index 4f647b882..35257e9fd 100644 --- a/packages/pyright-internal/src/tests/samples/generator1.py +++ b/packages/pyright-internal/src/tests/samples/generator1.py @@ -130,8 +130,7 @@ def generator14() -> Iterator[TD1]: class IntIterator(Protocol): - def __next__(self, /) -> int: - ... + def __next__(self, /) -> int: ... def generator15() -> IntIterator: @@ -139,8 +138,7 @@ def generator15() -> IntIterator: class AsyncIntIterator(Protocol): - def __anext__(self, /) -> Awaitable[int]: - ... + def __anext__(self, /) -> Awaitable[int]: ... async def generator16() -> AsyncIntIterator: diff --git a/packages/pyright-internal/src/tests/samples/generator10.py b/packages/pyright-internal/src/tests/samples/generator10.py index 8d439850f..d2fc62697 100644 --- a/packages/pyright-internal/src/tests/samples/generator10.py +++ b/packages/pyright-internal/src/tests/samples/generator10.py @@ -16,4 +16,3 @@ async def func1(): loop = get_event_loop() loop.run_until_complete(func1()) - diff --git a/packages/pyright-internal/src/tests/samples/generator2.py b/packages/pyright-internal/src/tests/samples/generator2.py index 8bca7e346..c0d41d836 100644 --- a/packages/pyright-internal/src/tests/samples/generator2.py +++ b/packages/pyright-internal/src/tests/samples/generator2.py @@ -34,7 +34,7 @@ def generator2() -> Iterator[ClassB]: def generator3( - arg: Generator[int, None, T] | Generator[str, None, T] + arg: Generator[int, None, T] | Generator[str, None, T], ) -> Generator[int | str, None, T]: x = yield from arg reveal_type(x, expected_text="T@generator3") @@ -42,7 +42,7 @@ def generator3( def generator4( - arg: Generator[int, None, int] | Generator[str, None, str] + arg: Generator[int, None, int] | Generator[str, None, str], ) -> Generator[int | str, None, int | str]: x = yield from arg reveal_type(x, expected_text="int | str") @@ -56,6 +56,7 @@ def generator5() -> Generator[None, float, None]: def generator6() -> Generator[None, int, None]: yield from generator5() + def generator7() -> Generator[None, int, None]: x: float = yield diff --git a/packages/pyright-internal/src/tests/samples/generic2.py b/packages/pyright-internal/src/tests/samples/generic2.py index 0463bdf07..8dee0af40 100644 --- a/packages/pyright-internal/src/tests/samples/generic2.py +++ b/packages/pyright-internal/src/tests/samples/generic2.py @@ -12,22 +12,18 @@ class ClassA(Generic[_T1]): # This should generate an error. -def func1(a: _T1) -> Generic[_T1]: - ... +def func1(a: _T1) -> Generic[_T1]: ... # This should generate an error. -def func2(p1: Generic[_T1]) -> _T1: - ... +def func2(p1: Generic[_T1]) -> _T1: ... TA1 = Generic # This should generate an error. -def func3(a: _T1) -> TA1[_T1]: - ... +def func3(a: _T1) -> TA1[_T1]: ... -class ClassB(TA1[_T1]): - ... +class ClassB(TA1[_T1]): ... diff --git a/packages/pyright-internal/src/tests/samples/generic3.py b/packages/pyright-internal/src/tests/samples/generic3.py index 6c7d77346..f0de256ea 100644 --- a/packages/pyright-internal/src/tests/samples/generic3.py +++ b/packages/pyright-internal/src/tests/samples/generic3.py @@ -18,8 +18,7 @@ class Foo(Iterable[_T2], Generic[_T1, _T2]): def foo(self, a: _T1, b: _T2) -> _T2: return b - def __iter__(self) -> Iterator[int]: - ... + def __iter__(self) -> Iterator[int]: ... a: Foo[int, str] = Foo(2, "") @@ -38,5 +37,4 @@ 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]): - ... +class A(Mapping[K, V], Generic[K]): ... diff --git a/packages/pyright-internal/src/tests/samples/genericType10.py b/packages/pyright-internal/src/tests/samples/genericType10.py index 2731628ad..b8984e860 100644 --- a/packages/pyright-internal/src/tests/samples/genericType10.py +++ b/packages/pyright-internal/src/tests/samples/genericType10.py @@ -8,8 +8,9 @@ _Configuration = TypeVar("_Configuration", bound="Configuration") class Configuration: @classmethod - def _create(cls: Type[_Configuration], data: Mapping[str, Any]) -> _Configuration: - ... + def _create( + cls: Type[_Configuration], data: Mapping[str, Any] + ) -> _Configuration: ... @classmethod def _from_dict( diff --git a/packages/pyright-internal/src/tests/samples/genericType11.py b/packages/pyright-internal/src/tests/samples/genericType11.py index d95cbf310..0b09bdf29 100644 --- a/packages/pyright-internal/src/tests/samples/genericType11.py +++ b/packages/pyright-internal/src/tests/samples/genericType11.py @@ -30,8 +30,7 @@ v5 = func2("test") reveal_type(v5, expected_text="List[str]") -def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: - ... +def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ... dicts = [{"a": "b"}, {"c": "d"}] diff --git a/packages/pyright-internal/src/tests/samples/genericType12.py b/packages/pyright-internal/src/tests/samples/genericType12.py index bb63c2c9e..d489425ec 100644 --- a/packages/pyright-internal/src/tests/samples/genericType12.py +++ b/packages/pyright-internal/src/tests/samples/genericType12.py @@ -48,8 +48,7 @@ reveal_type(v4(""), expected_text="str") _U = TypeVar("_U") -def dec() -> Callable[[_U], _U]: - ... +def dec() -> Callable[[_U], _U]: ... @dec() diff --git a/packages/pyright-internal/src/tests/samples/genericType13.py b/packages/pyright-internal/src/tests/samples/genericType13.py index 2d7386caa..f48497d9e 100644 --- a/packages/pyright-internal/src/tests/samples/genericType13.py +++ b/packages/pyright-internal/src/tests/samples/genericType13.py @@ -3,8 +3,7 @@ from typing import Any, Type, TypeVar -class ClassA: - ... +class ClassA: ... T = TypeVar("T") diff --git a/packages/pyright-internal/src/tests/samples/genericType15.py b/packages/pyright-internal/src/tests/samples/genericType15.py index 7cff10ec1..a44c379b8 100644 --- a/packages/pyright-internal/src/tests/samples/genericType15.py +++ b/packages/pyright-internal/src/tests/samples/genericType15.py @@ -10,8 +10,7 @@ T2 = TypeVar("T2") T3 = TypeVar("T3") -class ClassA(Generic[T1]): - ... +class ClassA(Generic[T1]): ... class ClassB(Generic[T2]): @@ -22,5 +21,4 @@ class ClassB(Generic[T2]): def func( p0: ClassA[T3], p1: Callable[[T3], object], -): - ... +): ... diff --git a/packages/pyright-internal/src/tests/samples/genericType18.py b/packages/pyright-internal/src/tests/samples/genericType18.py index 6676e64b4..c404acb49 100644 --- a/packages/pyright-internal/src/tests/samples/genericType18.py +++ b/packages/pyright-internal/src/tests/samples/genericType18.py @@ -8,8 +8,7 @@ _T = TypeVar("_T") def func1(val1: _T) -> Callable[[_T], None]: - def f(a: str): - ... + def f(a: str): ... # This should generate an error because str isn't # compatible with _T. @@ -17,7 +16,6 @@ def func1(val1: _T) -> Callable[[_T], None]: def func2(val1: _T) -> Callable[[_T], None]: - def f(a: _T): - ... + def f(a: _T): ... return f diff --git a/packages/pyright-internal/src/tests/samples/genericType19.py b/packages/pyright-internal/src/tests/samples/genericType19.py index 6a2d3a6ac..d3881e7ba 100644 --- a/packages/pyright-internal/src/tests/samples/genericType19.py +++ b/packages/pyright-internal/src/tests/samples/genericType19.py @@ -6,6 +6,7 @@ from typing import Any, TypeVar T = TypeVar("T") + def foo(self, obj: T, foo: Any) -> T: # NotImplemented is an instance of a class that derives from Any. return NotImplemented diff --git a/packages/pyright-internal/src/tests/samples/genericType24.py b/packages/pyright-internal/src/tests/samples/genericType24.py index 5ab318d3c..1663aa7c3 100644 --- a/packages/pyright-internal/src/tests/samples/genericType24.py +++ b/packages/pyright-internal/src/tests/samples/genericType24.py @@ -7,13 +7,11 @@ T = TypeVar("T") class IterableProxy(Iterable[T]): - def __iter__(self) -> Iterator[T]: - ... + def __iter__(self) -> Iterator[T]: ... class Parent(Generic[T]): - def m1(self, v: Iterable[T] = IterableProxy()) -> None: - ... + def m1(self, v: Iterable[T] = IterableProxy()) -> None: ... class Child(Parent[T]): diff --git a/packages/pyright-internal/src/tests/samples/genericType26.py b/packages/pyright-internal/src/tests/samples/genericType26.py index fe9cf0e31..cd1a981e5 100644 --- a/packages/pyright-internal/src/tests/samples/genericType26.py +++ b/packages/pyright-internal/src/tests/samples/genericType26.py @@ -35,14 +35,17 @@ class ClassB(Generic[T]): # This should generate an error. return ClassB(self.value) + @dataclass class DC1(Generic[T]): value: T + @dataclass class DC2(Generic[S]): value: S + @dataclass class ClassC(Generic[T, S]): value: DC1[T] | DC2[S] @@ -57,20 +60,17 @@ class ClassC(Generic[T, S]): T_co = TypeVar("T_co", covariant=True) + class ClassD(Generic[T_co]): @overload - def __init__(self, arg: Iterable[T_co]) -> None: - ... + def __init__(self, arg: Iterable[T_co]) -> None: ... @overload - def __init__(self, arg: Callable[[], Iterable[T_co]]) -> None: - ... + def __init__(self, arg: Callable[[], Iterable[T_co]]) -> None: ... - def __init__(self, arg: Iterable[T_co] | Callable[[], Iterable[T_co]]) -> None: - ... + def __init__(self, arg: Iterable[T_co] | Callable[[], Iterable[T_co]]) -> None: ... - def __iter__(self) -> Iterator[T_co]: - ... + def __iter__(self) -> Iterator[T_co]: ... class ClassE(ClassD[T_co]): diff --git a/packages/pyright-internal/src/tests/samples/genericType27.py b/packages/pyright-internal/src/tests/samples/genericType27.py index 37adda276..e76972fbf 100644 --- a/packages/pyright-internal/src/tests/samples/genericType27.py +++ b/packages/pyright-internal/src/tests/samples/genericType27.py @@ -4,8 +4,7 @@ from typing import TypeVar -class ClassA: - ... +class ClassA: ... T = TypeVar("T", bound=ClassA) @@ -14,7 +13,5 @@ T = TypeVar("T", bound=ClassA) def func1(cls: type[T]) -> list[type[T]]: result = [cls] for c in cls.__subclasses__(): - result.extend(func1(c)) + result.extend(func1(c)) return result - - diff --git a/packages/pyright-internal/src/tests/samples/genericType28.py b/packages/pyright-internal/src/tests/samples/genericType28.py index a363a7b20..5cefac83e 100644 --- a/packages/pyright-internal/src/tests/samples/genericType28.py +++ b/packages/pyright-internal/src/tests/samples/genericType28.py @@ -8,6 +8,7 @@ T = TypeVar("T") T_co = TypeVar("T_co", covariant=True) T_contra = TypeVar("T_contra", contravariant=True) + # This should generate an error because the type parameter for list # is invariant, so T_co here cannot be covariant. class Class1(list[T_co]): @@ -20,205 +21,163 @@ class Class2(list[T_contra]): pass -class Class3(Generic[T_co]): - ... +class Class3(Generic[T_co]): ... -class Class3_Child1(Class3[T_co]): - ... +class Class3_Child1(Class3[T_co]): ... -class Class3_Child2(Class3[T]): - ... +class Class3_Child2(Class3[T]): ... # This should generate an error because T_contra isn't # compatible with T_co. -class Class3_Child3(Class3[T_contra]): - ... +class Class3_Child3(Class3[T_contra]): ... -class Class4(Generic[T_contra]): - ... +class Class4(Generic[T_contra]): ... -class Class4_Child1(Class4[T_contra]): - ... +class Class4_Child1(Class4[T_contra]): ... -class Class4_Child2(Class4[T]): - ... +class Class4_Child2(Class4[T]): ... # This should generate an error because T_co isn't # compatible with T_contra. -class Class4_Child3(Class4[T_co]): - ... +class Class4_Child3(Class4[T_co]): ... -class Class5(Generic[T_contra]): - ... +class Class5(Generic[T_contra]): ... -class Class5_Child1(Class5[frozenset[T_contra]]): - ... +class Class5_Child1(Class5[frozenset[T_contra]]): ... # This should generate an error because Sequence[T_co] # is covariant and is therefore not compatible with # a contravariant type parameter. -class Class5_Child2(Class5[Sequence[T_co]]): - ... +class Class5_Child2(Class5[Sequence[T_co]]): ... -class Class5_Child3(Class5[Sequence[T]]): - ... +class Class5_Child3(Class5[Sequence[T]]): ... -class Class6(Generic[T_co, T_contra]): - ... +class Class6(Generic[T_co, T_contra]): ... -class Class6_Child1(Class6[T_co, T_contra]): - ... +class Class6_Child1(Class6[T_co, T_contra]): ... # This should generate an error because T_co isn't # compatible with T_contra. -class Class6_Child2(Class6[T_co, T_co]): - ... +class Class6_Child2(Class6[T_co, T_co]): ... # This should generate an error because T_contra isn't # compatible with T_co. -class Class6_Child3(Class6[T_contra, T_contra]): - ... +class Class6_Child3(Class6[T_contra, T_contra]): ... -class Class6_Child4(Class6[T, T]): - ... +class Class6_Child4(Class6[T, T]): ... # This should generate an error because Sequence[T_co] isn't # compatible with T_contra. -class Class6_Child5(Class6[Sequence[T_co], Sequence[T_co]]): - ... +class Class6_Child5(Class6[Sequence[T_co], Sequence[T_co]]): ... -class Co(Generic[T_co]): - ... +class Co(Generic[T_co]): ... -class Contra(Generic[T_contra]): - ... +class Contra(Generic[T_contra]): ... -class CoToContra(Contra[Co[T_contra]]): - ... +class CoToContra(Contra[Co[T_contra]]): ... -class ContraToContra(Contra[Contra[T_co]]): - ... +class ContraToContra(Contra[Contra[T_co]]): ... -class CoToCo(Co[Co[T_co]]): - ... +class CoToCo(Co[Co[T_co]]): ... -class ContraToCo(Co[Contra[T_contra]]): - ... +class ContraToCo(Co[Contra[T_contra]]): ... # This should generate an error. -class CoToContraToContra(Contra[Co[Contra[T_contra]]]): - ... +class CoToContraToContra(Contra[Co[Contra[T_contra]]]): ... # This should generate an error. -class ContraToContraToContra(Contra[Contra[Contra[T_co]]]): - ... +class ContraToContraToContra(Contra[Contra[Contra[T_co]]]): ... Co_TA = Co[T_co] Contra_TA = Contra[T_contra] -class CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): - ... +class CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): ... -class ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): - ... +class ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): ... -class CoToCo_WithTA(Co_TA[Co_TA[T_co]]): - ... +class CoToCo_WithTA(Co_TA[Co_TA[T_co]]): ... -class ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): - ... +class ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): ... # This should generate an error. -class CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): - ... +class CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): ... # This should generate an error. -class ContraToContraToContra_WithTA(Contra_TA[Contra_TA[Contra_TA[T_co]]]): - ... +class ContraToContraToContra_WithTA(Contra_TA[Contra_TA[Contra_TA[T_co]]]): ... Ts = TypeVarTuple("Ts") -class Variadic(Generic[Unpack[Ts]]): - ... +class Variadic(Generic[Unpack[Ts]]): ... -class VariadicChild(Variadic[T]): - ... +class VariadicChild(Variadic[T]): ... # This should generate an error. -class VariadicChildCo(Variadic[T_co]): - ... +class VariadicChildCo(Variadic[T_co]): ... # This should generate an error. -class VariadicChildContra(Variadic[T_contra]): - ... +class VariadicChildContra(Variadic[T_contra]): ... Variadic_TA = Variadic[Unpack[tuple[int, Unpack[Ts]]]] -class VariadicChild_WithTA(Variadic_TA[T]): - ... +class VariadicChild_WithTA(Variadic_TA[T]): ... # This should generate an error. -class VariadicChildCo_WithTA(Variadic_TA[T_co]): - ... +class VariadicChildCo_WithTA(Variadic_TA[T_co]): ... # This should generate an error. -class VariadicChildContra_WithTA(Variadic_TA[T_contra]): - ... +class VariadicChildContra_WithTA(Variadic_TA[T_contra]): ... Variadic_TA2 = Variadic[Unpack[tuple[int, T]]] -class VariadicChild_WithTA2(Variadic_TA2[T]): - ... +class VariadicChild_WithTA2(Variadic_TA2[T]): ... # This should generate an error. -class VariadicChildCo_WithTA2(Variadic_TA2[T_co]): - ... +class VariadicChildCo_WithTA2(Variadic_TA2[T_co]): ... # This should generate an error. -class VariadicChildContra_WithTA2(Variadic_TA2[T_contra]): - ... +class VariadicChildContra_WithTA2(Variadic_TA2[T_contra]): ... diff --git a/packages/pyright-internal/src/tests/samples/genericType29.py b/packages/pyright-internal/src/tests/samples/genericType29.py index ea9f9ec65..7652125ab 100644 --- a/packages/pyright-internal/src/tests/samples/genericType29.py +++ b/packages/pyright-internal/src/tests/samples/genericType29.py @@ -8,12 +8,10 @@ T1 = TypeVar("T1", contravariant=True) T2 = TypeVar("T2") -class A(Generic[T1]): - ... +class A(Generic[T1]): ... -def func1(x: A[T2]) -> A[T2 | None]: - ... +def func1(x: A[T2]) -> A[T2 | None]: ... x1: A[int | None] = func1(A[int]()) diff --git a/packages/pyright-internal/src/tests/samples/genericType30.py b/packages/pyright-internal/src/tests/samples/genericType30.py index 7d48b7643..7defeea93 100644 --- a/packages/pyright-internal/src/tests/samples/genericType30.py +++ b/packages/pyright-internal/src/tests/samples/genericType30.py @@ -5,14 +5,12 @@ from typing import Iterator, Generic, TypeVar A = TypeVar("A") -class Iter(Generic[A]): - def __iter__(self) -> Iterator[A]: - ... - def enumerate(self) -> "Iter[tuple[int, A]]": - ... +class Iter(Generic[A]): + def __iter__(self) -> Iterator[A]: ... + + def enumerate(self) -> "Iter[tuple[int, A]]": ... def method1(self) -> None: for x in self.enumerate(): reveal_type(x, expected_text="tuple[int, A@Iter]") - diff --git a/packages/pyright-internal/src/tests/samples/genericType32.py b/packages/pyright-internal/src/tests/samples/genericType32.py index 3ff17e2aa..e8df863a9 100644 --- a/packages/pyright-internal/src/tests/samples/genericType32.py +++ b/packages/pyright-internal/src/tests/samples/genericType32.py @@ -7,16 +7,13 @@ T = TypeVar("T") T_contra = TypeVar("T_contra", contravariant=True) -class Contra(Generic[T_contra]): - ... +class Contra(Generic[T_contra]): ... -class Foo(Generic[T]): - ... +class Foo(Generic[T]): ... -class Bar(Foo[T]): - ... +class Bar(Foo[T]): ... def func(x: Contra[Foo[int]]): diff --git a/packages/pyright-internal/src/tests/samples/genericType33.py b/packages/pyright-internal/src/tests/samples/genericType33.py index 1731d0505..5a6f623e3 100644 --- a/packages/pyright-internal/src/tests/samples/genericType33.py +++ b/packages/pyright-internal/src/tests/samples/genericType33.py @@ -5,21 +5,17 @@ from typing import Generic, Protocol, TypeVar T_contra = TypeVar("T_contra", contravariant=True) -class Contra(Generic[T_contra]): - ... +class Contra(Generic[T_contra]): ... class Foo(Protocol[T_contra]): - def f(self) -> Contra[T_contra]: - ... + def f(self) -> Contra[T_contra]: ... -def t1(x: Foo[T_contra]) -> list[T_contra] | None: - ... +def t1(x: Foo[T_contra]) -> list[T_contra] | None: ... -def t2(x: Foo[object]) -> None: - ... +def t2(x: Foo[object]) -> None: ... def func1(x: Foo[T_contra]) -> list[T_contra] | None: diff --git a/packages/pyright-internal/src/tests/samples/genericType34.py b/packages/pyright-internal/src/tests/samples/genericType34.py index 3a82e2988..2cc390008 100644 --- a/packages/pyright-internal/src/tests/samples/genericType34.py +++ b/packages/pyright-internal/src/tests/samples/genericType34.py @@ -9,12 +9,10 @@ _T_co = TypeVar("_T_co", covariant=True) _N = TypeVar("_N", bound=int) -class ClassA(Generic[_T_co, _N]): - ... +class ClassA(Generic[_T_co, _N]): ... -def func1(n: _N) -> ClassA[Literal[0], _N]: - ... +def func1(n: _N) -> ClassA[Literal[0], _N]: ... v1: ClassA[int, Literal[1]] = func1(1) diff --git a/packages/pyright-internal/src/tests/samples/genericType35.py b/packages/pyright-internal/src/tests/samples/genericType35.py index d5519a69f..e58f3a1af 100644 --- a/packages/pyright-internal/src/tests/samples/genericType35.py +++ b/packages/pyright-internal/src/tests/samples/genericType35.py @@ -8,24 +8,20 @@ X = TypeVar("X") Y = TypeVar("Y") -def deco1(func: Callable[[tuple[X]], Y]) -> Callable[[X], Y]: - ... +def deco1(func: Callable[[tuple[X]], Y]) -> Callable[[X], Y]: ... -def func1(x: tuple[str]) -> int: - ... +def func1(x: tuple[str]) -> int: ... v1 = deco1(func1) reveal_type(v1, expected_text="(str) -> int") -def deco2(func: Callable[[tuple[X, ...]], Y]) -> Callable[[X], Y]: - ... +def deco2(func: Callable[[tuple[X, ...]], Y]) -> Callable[[X], Y]: ... -def func2(x: tuple[str]) -> int: - ... +def func2(x: tuple[str]) -> int: ... # This should generate an error because of a tuple size mismatch. diff --git a/packages/pyright-internal/src/tests/samples/genericType36.py b/packages/pyright-internal/src/tests/samples/genericType36.py index 32f532d44..255df5f2e 100644 --- a/packages/pyright-internal/src/tests/samples/genericType36.py +++ b/packages/pyright-internal/src/tests/samples/genericType36.py @@ -9,8 +9,7 @@ ABC = Literal["a", "b", "c"] T = TypeVar("T") -def func1(x: T | Callable[[], T]) -> Callable[[], T]: - ... +def func1(x: T | Callable[[], T]) -> Callable[[], T]: ... def func2(a: Callable[[], ABC] | ABC, b: ABC | Callable[[], ABC]): diff --git a/packages/pyright-internal/src/tests/samples/genericType38.py b/packages/pyright-internal/src/tests/samples/genericType38.py index 46103acc1..d4cbd05d4 100644 --- a/packages/pyright-internal/src/tests/samples/genericType38.py +++ b/packages/pyright-internal/src/tests/samples/genericType38.py @@ -8,20 +8,16 @@ _T = TypeVar("_T") class ClassA(Generic[_T]): @overload - def __init__(self, _: _T): - ... + def __init__(self, _: _T): ... @overload - def __init__(self, _: Any): - ... + def __init__(self, _: Any): ... - def __init__(self, _: Any): - ... + def __init__(self, _: Any): ... class ClassB(Generic[_T]): - def __init__(self, _: ClassA[_T]): - ... + def __init__(self, _: ClassA[_T]): ... v1 = ClassA(0) diff --git a/packages/pyright-internal/src/tests/samples/genericType39.py b/packages/pyright-internal/src/tests/samples/genericType39.py index e897a5f6a..f2bc199ba 100644 --- a/packages/pyright-internal/src/tests/samples/genericType39.py +++ b/packages/pyright-internal/src/tests/samples/genericType39.py @@ -2,6 +2,7 @@ # constructor that is passed an argument expression that contains a # binary operator. + def func1(x: list[str] | None): for _, v in enumerate(x or []): reveal_type(v, expected_text="str") diff --git a/packages/pyright-internal/src/tests/samples/genericType40.py b/packages/pyright-internal/src/tests/samples/genericType40.py index ee5d6762a..948044700 100644 --- a/packages/pyright-internal/src/tests/samples/genericType40.py +++ b/packages/pyright-internal/src/tests/samples/genericType40.py @@ -8,24 +8,21 @@ from typing import Callable, TypeVar _T1 = TypeVar("_T1") -def func1(a: _T1 | None) -> Callable[[_T1], _T1]: - ... +def func1(a: _T1 | None) -> Callable[[_T1], _T1]: ... v1 = func1(None) reveal_type(v1, expected_text="(Unknown) -> Unknown") -def func2(a: None) -> Callable[[_T1], _T1]: - ... +def func2(a: None) -> Callable[[_T1], _T1]: ... v2 = func2(None) reveal_type(v2, expected_text="(_T1@func2) -> _T1@func2") -def func3(a: None) -> Callable[[type[_T1]], type[_T1]]: - ... +def func3(a: None) -> Callable[[type[_T1]], type[_T1]]: ... v3 = func3(None) diff --git a/packages/pyright-internal/src/tests/samples/genericType42.py b/packages/pyright-internal/src/tests/samples/genericType42.py index facfb5b7e..b009c9f7f 100644 --- a/packages/pyright-internal/src/tests/samples/genericType42.py +++ b/packages/pyright-internal/src/tests/samples/genericType42.py @@ -23,31 +23,25 @@ def func1(): class A(Protocol[T, P]): - def __init__(self, *args: P.args, **kwds: P.kwargs): - ... + def __init__(self, *args: P.args, **kwds: P.kwargs): ... -def make_a(x: Callable[P, R]) -> Type[A[R, P]]: - ... +def make_a(x: Callable[P, R]) -> Type[A[R, P]]: ... @overload -def func2(x: Type[A[R, P]]) -> Type[A[R, P]]: - ... +def func2(x: Type[A[R, P]]) -> Type[A[R, P]]: ... @overload -def func2(x: Callable[P, R]) -> Type[A[R, P]]: - ... +def func2(x: Callable[P, R]) -> Type[A[R, P]]: ... -def func2(x: Union[Type[A[R, P]], Callable[P, R]]) -> Type[A[R, P]]: - ... +def func2(x: Union[Type[A[R, P]], Callable[P, R]]) -> Type[A[R, P]]: ... def func3(): - def foo(x: int) -> str: - ... + def foo(x: int) -> str: ... x = make_a(foo) y = func2(x) diff --git a/packages/pyright-internal/src/tests/samples/genericType43.py b/packages/pyright-internal/src/tests/samples/genericType43.py index dfb7b23e7..addbfe41c 100644 --- a/packages/pyright-internal/src/tests/samples/genericType43.py +++ b/packages/pyright-internal/src/tests/samples/genericType43.py @@ -4,24 +4,21 @@ from typing import Iterable, Sequence -def func1(points: tuple[float, float] | Iterable[tuple[float, float]]) -> None: - ... +def func1(points: tuple[float, float] | Iterable[tuple[float, float]]) -> None: ... def test1(val: tuple[float, float]): func1(tuple((val, val))) -def func2(points: tuple[float, float] | Sequence[tuple[float, float]]) -> None: - ... +def func2(points: tuple[float, float] | Sequence[tuple[float, float]]) -> None: ... def test2(val: tuple[float, float]): func2(tuple([val, val])) -def func3(points: tuple[float, float] | tuple[str, str]) -> None: - ... +def func3(points: tuple[float, float] | tuple[str, str]) -> None: ... def test3(val: tuple[float, float]): diff --git a/packages/pyright-internal/src/tests/samples/genericType44.py b/packages/pyright-internal/src/tests/samples/genericType44.py index 7a72fb5e0..3ff2786ef 100644 --- a/packages/pyright-internal/src/tests/samples/genericType44.py +++ b/packages/pyright-internal/src/tests/samples/genericType44.py @@ -9,20 +9,16 @@ _T = TypeVar("_T") class Future(Awaitable[_T]): - def __await__(self) -> Generator[Any, None, _T]: - ... + def __await__(self) -> Generator[Any, None, _T]: ... -def func1(future: Future[_T]) -> Future[_T]: - ... +def func1(future: Future[_T]) -> Future[_T]: ... -def func2(cb: Awaitable[_T]) -> Future[_T]: - ... +def func2(cb: Awaitable[_T]) -> Future[_T]: ... -def func3() -> Awaitable[Literal[True]]: - ... +def func3() -> Awaitable[Literal[True]]: ... v1 = func1(func2(func3())) diff --git a/packages/pyright-internal/src/tests/samples/genericType5.py b/packages/pyright-internal/src/tests/samples/genericType5.py index 76c6bfe83..7c57bab8f 100644 --- a/packages/pyright-internal/src/tests/samples/genericType5.py +++ b/packages/pyright-internal/src/tests/samples/genericType5.py @@ -28,12 +28,10 @@ _X = TypeVar("_X") class A(Generic[_KT, _VT]): @classmethod - def method1(cls, i: Iterable[_T], v: _S) -> "A[_T, _S]": - ... + def method1(cls, i: Iterable[_T], v: _S) -> "A[_T, _S]": ... -def func1(__x: A[int, _X] | A[str, _X] | A[str | int, _X]) -> A[int, _X]: - ... +def func1(__x: A[int, _X] | A[str, _X] | A[str | int, _X]) -> A[int, _X]: ... v3 = func1(A.method1("a", "b")) diff --git a/packages/pyright-internal/src/tests/samples/genericType6.py b/packages/pyright-internal/src/tests/samples/genericType6.py index 6427d7395..fbf1b3341 100644 --- a/packages/pyright-internal/src/tests/samples/genericType6.py +++ b/packages/pyright-internal/src/tests/samples/genericType6.py @@ -4,8 +4,7 @@ from typing import Any, Generic, TypeVar -class ClassA: - ... +class ClassA: ... _T = TypeVar("_T", bound=ClassA) diff --git a/packages/pyright-internal/src/tests/samples/hashability1.py b/packages/pyright-internal/src/tests/samples/hashability1.py index 330e344c4..dbe2419cd 100644 --- a/packages/pyright-internal/src/tests/samples/hashability1.py +++ b/packages/pyright-internal/src/tests/samples/hashability1.py @@ -15,8 +15,7 @@ s2: set[Any] = {{}, 2, dict, frozenset(), []} class StrList(list[str]): - def __hash__(self) -> int: - ... + def __hash__(self) -> int: ... s3 = {StrList()} diff --git a/packages/pyright-internal/src/tests/samples/hashability2.py b/packages/pyright-internal/src/tests/samples/hashability2.py index c4ebe5d68..44cce052a 100644 --- a/packages/pyright-internal/src/tests/samples/hashability2.py +++ b/packages/pyright-internal/src/tests/samples/hashability2.py @@ -3,8 +3,7 @@ # pyright: reportIncompatibleMethodOverride=false -class A: - ... +class A: ... s1 = {A()} @@ -12,8 +11,7 @@ d1 = {A(): 100} class B: - def __eq__(self, other): - ... + def __eq__(self, other): ... # Both of these should generate an error because a class that @@ -26,8 +24,7 @@ class C: __hash__: None = None -class D(B, C): - ... +class D(B, C): ... # Both of these should generate an error because B is unhashable. @@ -36,12 +33,10 @@ d3 = {D(): 100} class E: - def __hash__(self): - ... + def __hash__(self): ... -class F(D, E): - ... +class F(D, E): ... # Both of these should generate an error because D is unhashable. @@ -49,8 +44,7 @@ s4 = {F()} d4 = {F(): 100} -class G(E, D): - ... +class G(E, D): ... s5 = {G()} diff --git a/packages/pyright-internal/src/tests/samples/hashability3.py b/packages/pyright-internal/src/tests/samples/hashability3.py index cc69ed854..ae74edfc3 100644 --- a/packages/pyright-internal/src/tests/samples/hashability3.py +++ b/packages/pyright-internal/src/tests/samples/hashability3.py @@ -2,16 +2,14 @@ # __hash__ isn't set but __eq__ is. -class A: - ... +class A: ... A().__hash__() class B: - def __eq__(self, value: object) -> bool: - ... + def __eq__(self, value: object) -> bool: ... ... diff --git a/packages/pyright-internal/src/tests/samples/import13.py b/packages/pyright-internal/src/tests/samples/import13.py index 051cf5bbe..435ff8f44 100644 --- a/packages/pyright-internal/src/tests/samples/import13.py +++ b/packages/pyright-internal/src/tests/samples/import13.py @@ -2,5 +2,4 @@ # PEP 562 (module-level __getattr__) support. -def __getattr__(name: str) -> int: - ... +def __getattr__(name: str) -> int: ... diff --git a/packages/pyright-internal/src/tests/samples/inconsistentConstructor1.py b/packages/pyright-internal/src/tests/samples/inconsistentConstructor1.py index 1612b0024..e3d9a792d 100644 --- a/packages/pyright-internal/src/tests/samples/inconsistentConstructor1.py +++ b/packages/pyright-internal/src/tests/samples/inconsistentConstructor1.py @@ -2,22 +2,18 @@ class Parent1: - def __init__(self, a: int) -> None: - ... + def __init__(self, a: int) -> None: ... class Child1(Parent1): # This should generate an error if reportInconsistentConstructor is enabled. - def __new__(cls, a: int | str): - ... + def __new__(cls, a: int | str): ... class Parent2: - def __init__(self, b: int) -> None: - ... + def __init__(self, b: int) -> None: ... class Child2(Parent2): # This should generate an error if reportInconsistentConstructor is enabled. - def __new__(cls, b: str): - ... + def __new__(cls, b: str): ... diff --git a/packages/pyright-internal/src/tests/samples/index1.py b/packages/pyright-internal/src/tests/samples/index1.py index 62e764a47..38c3423d3 100644 --- a/packages/pyright-internal/src/tests/samples/index1.py +++ b/packages/pyright-internal/src/tests/samples/index1.py @@ -54,13 +54,11 @@ ClassA["1"] class ClassB: - def __setitem__(self, index: int, value: "ClassB"): - ... + def __setitem__(self, index: int, value: "ClassB"): ... class ClassC: - def __setitem__(self, index: int, value: "ClassC"): - ... + def __setitem__(self, index: int, value: "ClassC"): ... B_or_C = TypeVar("B_or_C", ClassB, ClassC) @@ -75,8 +73,7 @@ TD = TypeVar("TD", bound="ClassD[Any]") class ClassD(Generic[TD]): - def __setitem__(self, index: int, value: TD): - ... + def __setitem__(self, index: int, value: TD): ... def func2(container: ClassD[TD], value: TD): @@ -98,8 +95,7 @@ e["test"] = 3 class ClassF(Generic[T]): - def __getitem__(self, args: int) -> Self: - ... + def __getitem__(self, args: int) -> Self: ... def get(self, index: int) -> Self: reveal_type(self[index], expected_text="Self@ClassF[T@ClassF]") diff --git a/packages/pyright-internal/src/tests/samples/inferredTypes3.py b/packages/pyright-internal/src/tests/samples/inferredTypes3.py index 3cd9f4905..23ed555d2 100644 --- a/packages/pyright-internal/src/tests/samples/inferredTypes3.py +++ b/packages/pyright-internal/src/tests/samples/inferredTypes3.py @@ -4,8 +4,7 @@ from abc import ABC, abstractmethod -class OtherError(NotImplementedError): - ... +class OtherError(NotImplementedError): ... class A(ABC): diff --git a/packages/pyright-internal/src/tests/samples/isinstance2.py b/packages/pyright-internal/src/tests/samples/isinstance2.py index e280b8abd..f99fcf124 100644 --- a/packages/pyright-internal/src/tests/samples/isinstance2.py +++ b/packages/pyright-internal/src/tests/samples/isinstance2.py @@ -4,7 +4,7 @@ # pyright: reportUnnecessaryIsInstance=true -from typing import Union +from typing import TypeVar, Union # This should generate an error because "dummy" can't be resolved. # The symbol Document should have an unknown type. @@ -33,3 +33,13 @@ def func3(obj: float): reveal_type(obj, expected_text="float") else: reveal_type(obj, expected_text="int") + + +T = TypeVar("T", bound=float) + + +def func4(t: type[T]): + if issubclass(t, float): + reveal_type(t, expected_text="type[float]*") + else: + reveal_type(t, expected_text="type[int]*") diff --git a/packages/pyright-internal/src/tests/samples/isinstance5.py b/packages/pyright-internal/src/tests/samples/isinstance5.py index ccef70eb8..c8b9bfc44 100644 --- a/packages/pyright-internal/src/tests/samples/isinstance5.py +++ b/packages/pyright-internal/src/tests/samples/isinstance5.py @@ -11,20 +11,17 @@ from typing import Any, Protocol, runtime_checkable class DataProtocol(Protocol): name: str - def method1(self) -> int: - ... + def method1(self) -> int: ... @runtime_checkable class DataProtocol2(DataProtocol, Protocol): - def method2(self) -> int: - ... + def method2(self) -> int: ... @runtime_checkable class NonDataProtocol(Protocol): - def method1(self) -> int: - ... + def method1(self) -> int: ... def func2(a: Any): diff --git a/packages/pyright-internal/src/tests/samples/isinstance6.py b/packages/pyright-internal/src/tests/samples/isinstance6.py index 32a884fcc..e0d27fc9a 100644 --- a/packages/pyright-internal/src/tests/samples/isinstance6.py +++ b/packages/pyright-internal/src/tests/samples/isinstance6.py @@ -11,8 +11,7 @@ from typing import Protocol, runtime_checkable @runtime_checkable class Proto3(Protocol): - def method1(self, a: int) -> int: - ... + def method1(self, a: int) -> int: ... class Concrete3A: @@ -22,8 +21,7 @@ class Concrete3A: @runtime_checkable class Proto2(Protocol): - def other(self) -> None: - ... + def other(self) -> None: ... class Concrete3B: diff --git a/packages/pyright-internal/src/tests/samples/lambda11.py b/packages/pyright-internal/src/tests/samples/lambda11.py index afeac5552..8f30ca920 100644 --- a/packages/pyright-internal/src/tests/samples/lambda11.py +++ b/packages/pyright-internal/src/tests/samples/lambda11.py @@ -12,9 +12,8 @@ class Callback(Generic[T]): self, func: Callable[Concatenate[T, P], object], *args: P.args, - **kwargs: P.kwargs - ) -> None: - ... + **kwargs: P.kwargs, + ) -> None: ... v1: Callback[tuple[int, int]] = Callback(lambda p: (p[1], p[0])) @@ -22,8 +21,7 @@ v1: Callback[tuple[int, int]] = Callback(lambda p: (p[1], p[0])) def func1( func: Callable[Concatenate[int, P], T], *args: P.args, **kwargs: P.kwargs -) -> T: - ... +) -> T: ... v2 = func1(lambda p: p) diff --git a/packages/pyright-internal/src/tests/samples/lambda14.py b/packages/pyright-internal/src/tests/samples/lambda14.py index 31425eb04..c238d5ae1 100644 --- a/packages/pyright-internal/src/tests/samples/lambda14.py +++ b/packages/pyright-internal/src/tests/samples/lambda14.py @@ -6,4 +6,3 @@ reveal_type(lambda1, expected_text='(x: str = "") -> str') lambda2 = lambda x=None: x reveal_type(lambda2, expected_text="(x: Unknown | None = None) -> (Unknown | None)") - diff --git a/packages/pyright-internal/src/tests/samples/lambda3.py b/packages/pyright-internal/src/tests/samples/lambda3.py index df415ad36..4765f7330 100644 --- a/packages/pyright-internal/src/tests/samples/lambda3.py +++ b/packages/pyright-internal/src/tests/samples/lambda3.py @@ -22,8 +22,7 @@ def test3(): class MyCallback(Protocol): - def __call__(self, y: int, a: int = 0) -> bool: - ... + def __call__(self, y: int, a: int = 0) -> bool: ... lambda1: Callable[[int, int], bool] = lambda y, a=0: a == y diff --git a/packages/pyright-internal/src/tests/samples/lambda4.py b/packages/pyright-internal/src/tests/samples/lambda4.py index be1735343..95269e677 100644 --- a/packages/pyright-internal/src/tests/samples/lambda4.py +++ b/packages/pyright-internal/src/tests/samples/lambda4.py @@ -35,23 +35,19 @@ accepts_u1(lambda a, b, c: True) class Callable1(Protocol): - def __call__(self, p0: int, p1: str) -> bool: - ... + def __call__(self, p0: int, p1: str) -> bool: ... class Callable2(Protocol): - def __call__(self, p0: str) -> bool: - ... + def __call__(self, p0: str) -> bool: ... class Callable3(Protocol): - def __call__(self, *p0: str) -> bool: - ... + def __call__(self, *p0: str) -> bool: ... class Callable4(Protocol): - def __call__(self, p0: int, p1: str, *p2: str) -> bool: - ... + def __call__(self, p0: int, p1: str, *p2: str) -> bool: ... U2 = Callable1 | Callable2 | Callable3 | Callable4 diff --git a/packages/pyright-internal/src/tests/samples/lambda5.py b/packages/pyright-internal/src/tests/samples/lambda5.py index 478fa761e..e750073df 100644 --- a/packages/pyright-internal/src/tests/samples/lambda5.py +++ b/packages/pyright-internal/src/tests/samples/lambda5.py @@ -12,12 +12,10 @@ class Msg(Generic[T]): body: T -class Request: - ... +class Request: ... -def check(func: "Callable[[MsgT, int], object]") -> MsgT: - ... +def check(func: "Callable[[MsgT, int], object]") -> MsgT: ... notification: Msg[Request] = check(lambda msg, foo: (msg.body, foo)) diff --git a/packages/pyright-internal/src/tests/samples/lambda8.py b/packages/pyright-internal/src/tests/samples/lambda8.py index e35ab9852..ff5117679 100644 --- a/packages/pyright-internal/src/tests/samples/lambda8.py +++ b/packages/pyright-internal/src/tests/samples/lambda8.py @@ -8,13 +8,11 @@ R = TypeVar("R") class A(Generic[T, R]): - def __init__(self, x: Callable[[T], R], y: T): - ... + def __init__(self, x: Callable[[T], R], y: T): ... class B(Generic[R]): - def __init__(self, x: Callable[[T], R], y: T): - ... + def __init__(self, x: Callable[[T], R], y: T): ... reveal_type(A(lambda x: x, 123), expected_text="A[int, int]") diff --git a/packages/pyright-internal/src/tests/samples/lambda9.py b/packages/pyright-internal/src/tests/samples/lambda9.py index c44e08802..722096da1 100644 --- a/packages/pyright-internal/src/tests/samples/lambda9.py +++ b/packages/pyright-internal/src/tests/samples/lambda9.py @@ -10,19 +10,16 @@ _Out2T = TypeVar("_Out2T") class Flow(Generic[_OutT]): @overload - def map(self, func: Callable[[_OutT], Exception], /) -> "Flow[None]": - ... + def map(self, func: Callable[[_OutT], Exception], /) -> "Flow[None]": ... @overload - def map(self, func: Callable[[_OutT], _Out2T], /) -> "Flow[_Out2T]": - ... + def map(self, func: Callable[[_OutT], _Out2T], /) -> "Flow[_Out2T]": ... def map(self, obj, /): return cast("Flow", self) -class Data: - ... +class Data: ... x1 = Flow[Data]().map(lambda aa: _get_date(reveal_type(aa, expected_text="Data"))) @@ -35,5 +32,4 @@ x3 = x2.map(lambda cc: "any value") reveal_type(x3, expected_text="Flow[str]") -def _get_date(d: Data) -> str: - ... +def _get_date(d: Data) -> str: ... diff --git a/packages/pyright-internal/src/tests/samples/literalString3.py b/packages/pyright-internal/src/tests/samples/literalString3.py index cbca25438..619636477 100644 --- a/packages/pyright-internal/src/tests/samples/literalString3.py +++ b/packages/pyright-internal/src/tests/samples/literalString3.py @@ -8,8 +8,7 @@ T_LS = TypeVar("T_LS", bound=LiteralString) class ClassA(Generic[T]): - def __init__(self, val: T) -> None: - ... + def __init__(self, val: T) -> None: ... def func1(x: T) -> ClassA[T]: diff --git a/packages/pyright-internal/src/tests/samples/literals2.py b/packages/pyright-internal/src/tests/samples/literals2.py index 54731e8df..857a39ba6 100644 --- a/packages/pyright-internal/src/tests/samples/literals2.py +++ b/packages/pyright-internal/src/tests/samples/literals2.py @@ -23,8 +23,7 @@ LetterGrade = Literal["A", "B", "C", "D", "F"] _T = TypeVar("_T") -def func1(x: _T) -> _T: - ... +def func1(x: _T) -> _T: ... grade: LetterGrade = func1("A") diff --git a/packages/pyright-internal/src/tests/samples/literals6.py b/packages/pyright-internal/src/tests/samples/literals6.py index f10fca5d8..a4c7eff5e 100644 --- a/packages/pyright-internal/src/tests/samples/literals6.py +++ b/packages/pyright-internal/src/tests/samples/literals6.py @@ -38,8 +38,7 @@ Wrong10 = Literal[Any] Wrong11 = Literal[...] -def func(): - ... +def func(): ... # This should generate an error. diff --git a/packages/pyright-internal/src/tests/samples/literals7.py b/packages/pyright-internal/src/tests/samples/literals7.py index 96fc89173..a9524260c 100644 --- a/packages/pyright-internal/src/tests/samples/literals7.py +++ b/packages/pyright-internal/src/tests/samples/literals7.py @@ -6,13 +6,13 @@ from typing import Literal big_int: Literal[9223372036854775808] = 0x8000000000000000 # This should generate an error. -y1: Literal[ - 900001231231231456487987456452132130000000000000000000000000000001 -] = 900001231231231456487987456452132130000000000000000000000000000000 +y1: Literal[900001231231231456487987456452132130000000000000000000000000000001] = ( + 900001231231231456487987456452132130000000000000000000000000000000 +) -y2: Literal[ +y2: Literal[900001231231231456487987456452132130000000000000000000000000000001] = ( 900001231231231456487987456452132130000000000000000000000000000001 -] = 900001231231231456487987456452132130000000000000000000000000000001 +) reveal_type( y2, diff --git a/packages/pyright-internal/src/tests/samples/loop12.py b/packages/pyright-internal/src/tests/samples/loop12.py index 1da804ee1..685dda52a 100644 --- a/packages/pyright-internal/src/tests/samples/loop12.py +++ b/packages/pyright-internal/src/tests/samples/loop12.py @@ -3,8 +3,7 @@ class ClassA: - def non_property(self) -> int: - ... + def non_property(self) -> int: ... def do_stuff(self, x: int | None): while True: diff --git a/packages/pyright-internal/src/tests/samples/loop17.py b/packages/pyright-internal/src/tests/samples/loop17.py index 53698bacc..663eb4c75 100644 --- a/packages/pyright-internal/src/tests/samples/loop17.py +++ b/packages/pyright-internal/src/tests/samples/loop17.py @@ -1,6 +1,7 @@ # This sample tests the case where a loop involves an unannotated parameter # and therefore an "unknown" that propagates through the loop. + def f(x): e = 0 for _ in [0]: diff --git a/packages/pyright-internal/src/tests/samples/loop19.py b/packages/pyright-internal/src/tests/samples/loop19.py index 2ed65a685..d68b9e329 100644 --- a/packages/pyright-internal/src/tests/samples/loop19.py +++ b/packages/pyright-internal/src/tests/samples/loop19.py @@ -1,5 +1,6 @@ # This sample tests a loop that references instance variables. + class Results: zzz: int diff --git a/packages/pyright-internal/src/tests/samples/loop2.py b/packages/pyright-internal/src/tests/samples/loop2.py index fa49cd972..05edac953 100644 --- a/packages/pyright-internal/src/tests/samples/loop2.py +++ b/packages/pyright-internal/src/tests/samples/loop2.py @@ -2,8 +2,7 @@ # of cyclical dependencies for type resolution. -def needs_str(a: str) -> tuple[str, str]: - ... +def needs_str(a: str) -> tuple[str, str]: ... def xxx(): diff --git a/packages/pyright-internal/src/tests/samples/loop20.py b/packages/pyright-internal/src/tests/samples/loop20.py index 310c43883..d46a66c23 100644 --- a/packages/pyright-internal/src/tests/samples/loop20.py +++ b/packages/pyright-internal/src/tests/samples/loop20.py @@ -21,21 +21,20 @@ def find_zero(f: Callable[[float], float]) -> float: f_x_0 = 0 f_x_1 = 0 while True: - if not(isnan(f_x_0)) and isnan(f_x_1): + if not (isnan(f_x_0)) and isnan(f_x_1): x_tests = list(linspace(x_1, x_0, 25)) f_x_tests = (f(x) for x in x_tests) for x, f_x in zip(x_tests, f_x_tests): - if not(isnan(f_x)): + if not (isnan(f_x)): x_1 = x f_x_1 = f_x break - elif isnan(f_x_0) and not(isnan(f_x_1)): + elif isnan(f_x_0) and not (isnan(f_x_1)): x_tests = list(linspace(x_0, x_1, 25)) f_x_tests = (f(x) for x in x_tests) for x, f_x in zip(x_tests, f_x_tests): - if not(isnan(f_x)): + if not (isnan(f_x)): x_0 = x - f_x_0 = f_x + f_x_0 = f_x break - \ No newline at end of file diff --git a/packages/pyright-internal/src/tests/samples/loop24.py b/packages/pyright-internal/src/tests/samples/loop24.py index 6ad8911e2..45942c395 100644 --- a/packages/pyright-internal/src/tests/samples/loop24.py +++ b/packages/pyright-internal/src/tests/samples/loop24.py @@ -9,4 +9,3 @@ while True: break else: var, _ = var + 1, 0 - diff --git a/packages/pyright-internal/src/tests/samples/loop28.py b/packages/pyright-internal/src/tests/samples/loop28.py index b522a04d2..87500b563 100644 --- a/packages/pyright-internal/src/tests/samples/loop28.py +++ b/packages/pyright-internal/src/tests/samples/loop28.py @@ -26,4 +26,3 @@ class A: future_id.result() if self.foo: pass - \ No newline at end of file diff --git a/packages/pyright-internal/src/tests/samples/loop31.py b/packages/pyright-internal/src/tests/samples/loop31.py index fae7e73a3..9eebe2b86 100644 --- a/packages/pyright-internal/src/tests/samples/loop31.py +++ b/packages/pyright-internal/src/tests/samples/loop31.py @@ -1,8 +1,9 @@ # This sample tests the case where an unannotated local variable # has a dependency on itself when evaluating its effective type. -def func1(arg: str): - ... + +def func1(arg: str): ... + def func2(arg: int): for _ in range(1): diff --git a/packages/pyright-internal/src/tests/samples/loop32.py b/packages/pyright-internal/src/tests/samples/loop32.py index 56c2dd2db..36b97c830 100644 --- a/packages/pyright-internal/src/tests/samples/loop32.py +++ b/packages/pyright-internal/src/tests/samples/loop32.py @@ -1,9 +1,10 @@ # This sample tests type narrowing of instance variables in the presence # of a double nested loop. + def func1(x: str | None): assert x is not None for i in range(10): for j in range(10): - x = x + "" + x = x + "" diff --git a/packages/pyright-internal/src/tests/samples/loop33.py b/packages/pyright-internal/src/tests/samples/loop33.py index b6b003a9b..607ef4264 100644 --- a/packages/pyright-internal/src/tests/samples/loop33.py +++ b/packages/pyright-internal/src/tests/samples/loop33.py @@ -6,5 +6,4 @@ for x in range(1): for y in range(1): count += 1 -reveal_type(count, expected_text='int') - +reveal_type(count, expected_text="int") diff --git a/packages/pyright-internal/src/tests/samples/loop34.py b/packages/pyright-internal/src/tests/samples/loop34.py index ea60645b3..136da58ac 100644 --- a/packages/pyright-internal/src/tests/samples/loop34.py +++ b/packages/pyright-internal/src/tests/samples/loop34.py @@ -7,13 +7,11 @@ _T_contra = TypeVar("_T_contra", contravariant=True) class SupportsDunderGT(Protocol[_T_contra]): - def __gt__(self, __other: _T_contra) -> bool: - ... + def __gt__(self, __other: _T_contra) -> bool: ... class SupportsDunderLT(Protocol[_T_contra]): - def __lt__(self, __other: _T_contra) -> bool: - ... + def __lt__(self, __other: _T_contra) -> bool: ... SupportsRichComparison: TypeAlias = SupportsDunderLT[Any] | SupportsDunderGT[Any] @@ -25,8 +23,7 @@ SupportsRichComparisonT = TypeVar( def max( __arg1: SupportsRichComparisonT, __arg2: SupportsRichComparisonT -) -> SupportsRichComparisonT: - ... +) -> SupportsRichComparisonT: ... a: int = 1 diff --git a/packages/pyright-internal/src/tests/samples/loop38.py b/packages/pyright-internal/src/tests/samples/loop38.py index 4dd9ecb80..22767163a 100644 --- a/packages/pyright-internal/src/tests/samples/loop38.py +++ b/packages/pyright-internal/src/tests/samples/loop38.py @@ -18,5 +18,3 @@ def func1(nodes: list[int]): break else: return - - diff --git a/packages/pyright-internal/src/tests/samples/loop39.py b/packages/pyright-internal/src/tests/samples/loop39.py index 7d4d0d5ac..43015435e 100644 --- a/packages/pyright-internal/src/tests/samples/loop39.py +++ b/packages/pyright-internal/src/tests/samples/loop39.py @@ -4,8 +4,7 @@ # pyright: strict -def func1() -> str | None: - ... +def func1() -> str | None: ... s1: str | None = None diff --git a/packages/pyright-internal/src/tests/samples/loop40.py b/packages/pyright-internal/src/tests/samples/loop40.py index afb3990cf..494853e32 100644 --- a/packages/pyright-internal/src/tests/samples/loop40.py +++ b/packages/pyright-internal/src/tests/samples/loop40.py @@ -3,6 +3,7 @@ # pyright: strict + def func1(a: int, b: str, c: str): v1: list[tuple[str, str, str]] = [] for _ in range(0): diff --git a/packages/pyright-internal/src/tests/samples/loop41.py b/packages/pyright-internal/src/tests/samples/loop41.py index 6a4669711..21e2c8830 100644 --- a/packages/pyright-internal/src/tests/samples/loop41.py +++ b/packages/pyright-internal/src/tests/samples/loop41.py @@ -6,12 +6,10 @@ from typing import TypeVar, Any T = TypeVar("T") -def func1(x: T) -> T: - ... +def func1(x: T) -> T: ... -def func2(schema: bool): - ... +def func2(schema: bool): ... def func3(v1: list[bool], v2: int | str): diff --git a/packages/pyright-internal/src/tests/samples/loop42.py b/packages/pyright-internal/src/tests/samples/loop42.py index 696d1ae44..6805e85d3 100644 --- a/packages/pyright-internal/src/tests/samples/loop42.py +++ b/packages/pyright-internal/src/tests/samples/loop42.py @@ -4,6 +4,7 @@ # pyright: reportUnnecessaryComparison=true + def func1(): a = None b = "" diff --git a/packages/pyright-internal/src/tests/samples/match2.py b/packages/pyright-internal/src/tests/samples/match2.py index 98b638aa9..fefcba87f 100644 --- a/packages/pyright-internal/src/tests/samples/match2.py +++ b/packages/pyright-internal/src/tests/samples/match2.py @@ -4,7 +4,7 @@ def func1(subj: int | dict[str, str] | tuple[int] | str, cond: bool): match subj: - case (3 | "hi"): + case 3 | "hi": reveal_type(subj, expected_text="Literal[3, 'hi']") return diff --git a/packages/pyright-internal/src/tests/samples/matchClass2.py b/packages/pyright-internal/src/tests/samples/matchClass2.py index 835ca4d54..1439a3c77 100644 --- a/packages/pyright-internal/src/tests/samples/matchClass2.py +++ b/packages/pyright-internal/src/tests/samples/matchClass2.py @@ -3,6 +3,7 @@ from dataclasses import dataclass, field + @dataclass class Point: optional: int | None = field(default=None, kw_only=True) @@ -16,5 +17,4 @@ match obj: reveal_type(x, expected_text="int") reveal_type(y, expected_text="int") reveal_type(opt, expected_text="int | None") - distance = (x ** 2 + y ** 2) ** 0.5 - + distance = (x**2 + y**2) ** 0.5 diff --git a/packages/pyright-internal/src/tests/samples/matchClass5.py b/packages/pyright-internal/src/tests/samples/matchClass5.py index 1503305ae..c1ad57512 100644 --- a/packages/pyright-internal/src/tests/samples/matchClass5.py +++ b/packages/pyright-internal/src/tests/samples/matchClass5.py @@ -15,11 +15,12 @@ class B: __match_args__ = ("a", "b") -class C(B): - ... +class C(B): ... + class D(int): ... + def func1(subj: A | B): match subj: # This should generate an error because A accepts only diff --git a/packages/pyright-internal/src/tests/samples/matchLiteral1.py b/packages/pyright-internal/src/tests/samples/matchLiteral1.py index f6ecf04b4..73504c9af 100644 --- a/packages/pyright-internal/src/tests/samples/matchLiteral1.py +++ b/packages/pyright-internal/src/tests/samples/matchLiteral1.py @@ -67,8 +67,7 @@ def test_none(value_to_match: int | None): reveal_type(a2, expected_text="int") -class A(str): - ... +class A(str): ... def test_subclass(a: A): diff --git a/packages/pyright-internal/src/tests/samples/matchLiteral2.py b/packages/pyright-internal/src/tests/samples/matchLiteral2.py index 35080da46..e7e65de11 100644 --- a/packages/pyright-internal/src/tests/samples/matchLiteral2.py +++ b/packages/pyright-internal/src/tests/samples/matchLiteral2.py @@ -30,4 +30,3 @@ def g(d: A | B | C) -> None: case "b": reveal_type(d.tag, expected_text="Literal['b']") reveal_type(d, expected_text="B") - diff --git a/packages/pyright-internal/src/tests/samples/matchValue1.py b/packages/pyright-internal/src/tests/samples/matchValue1.py index 0144be986..18c3b1207 100644 --- a/packages/pyright-internal/src/tests/samples/matchValue1.py +++ b/packages/pyright-internal/src/tests/samples/matchValue1.py @@ -27,8 +27,7 @@ class MyEnum(Enum): class MyClass: class_var_1: "MyClass" - def __eq__(self, object: "MyClass") -> bool: - ... + def __eq__(self, object: "MyClass") -> bool: ... def test_unknown(value_to_match): diff --git a/packages/pyright-internal/src/tests/samples/maxParseDepth2.py b/packages/pyright-internal/src/tests/samples/maxParseDepth2.py index 202ca7d28..203a34b01 100644 --- a/packages/pyright-internal/src/tests/samples/maxParseDepth2.py +++ b/packages/pyright-internal/src/tests/samples/maxParseDepth2.py @@ -1,16 +1,51 @@ - from typing import Any def func(x: dict[int, Any], y: Any): - x[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0] - + x[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][ + 0 + ][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0] y.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x - y()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()() - - y.x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]() - + y.x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[ + 0 + ]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[ + 0 + ]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[ + 0 + ]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[ + 0 + ]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[ + 0 + ]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[ + 0 + ]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[ + 0 + ]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]().x[0]() diff --git a/packages/pyright-internal/src/tests/samples/memberAccess1.py b/packages/pyright-internal/src/tests/samples/memberAccess1.py index 4a3f9b8c3..7e7cfb4c6 100644 --- a/packages/pyright-internal/src/tests/samples/memberAccess1.py +++ b/packages/pyright-internal/src/tests/samples/memberAccess1.py @@ -26,8 +26,7 @@ class DescriptorA(Generic[_T]): ... @overload - def __get__(self, instance: Any, owner: Any) -> _T: - ... + def __get__(self, instance: Any, owner: Any) -> _T: ... class ClassA: @@ -67,11 +66,9 @@ reveal_type(ClassC.instance, expected_text="ClassC") class DescriptorD(Generic[_T]): value: _T - def __get__(self, instance: object | None, cls: type[object]) -> _T: - ... + def __get__(self, instance: object | None, cls: type[object]) -> _T: ... - def __set__(self, instance: object, value: _T) -> None: - ... + def __set__(self, instance: object, value: _T) -> None: ... class ClassD: @@ -110,23 +107,21 @@ class Decorator(Generic[_T, _P, _R]): self.func = func @overload - def __get__(self, obj: None, objtype: type[_T]) -> "Decorator[_T, _P, _R]": - ... + def __get__(self, obj: None, objtype: type[_T]) -> "Decorator[_T, _P, _R]": ... @overload - def __get__(self, obj: _T, objtype: type[_T] | None) -> Callable[_P, Awaitable[_R]]: - ... + def __get__( + self, obj: _T, objtype: type[_T] | None + ) -> Callable[_P, Awaitable[_R]]: ... def __get__( self, obj: _T | None, objtype: type[_T] | None = None - ) -> "Decorator[_T, _P, _R] | Callable[_P, Awaitable[_R]]": - ... + ) -> "Decorator[_T, _P, _R] | Callable[_P, Awaitable[_R]]": ... class ClassF: @Decorator - async def method1(self, a: int, *, b: str) -> str: - ... + async def method1(self, a: int, *, b: str) -> str: ... def method2(self): reveal_type(self.method1, expected_text="(a: int, *, b: str) -> Awaitable[str]") @@ -137,5 +132,3 @@ class ClassF: cls.method1, expected_text="Decorator[Self@ClassF, (a: int, *, b: str), str]", ) - - diff --git a/packages/pyright-internal/src/tests/samples/memberAccess10.py b/packages/pyright-internal/src/tests/samples/memberAccess10.py index 5fee99a96..36b5d98c3 100644 --- a/packages/pyright-internal/src/tests/samples/memberAccess10.py +++ b/packages/pyright-internal/src/tests/samples/memberAccess10.py @@ -13,8 +13,7 @@ class _IntDescriptorMeta(type): pass -class IntDescriptorClass(metaclass=_IntDescriptorMeta): - ... +class IntDescriptorClass(metaclass=_IntDescriptorMeta): ... class X: diff --git a/packages/pyright-internal/src/tests/samples/memberAccess12.py b/packages/pyright-internal/src/tests/samples/memberAccess12.py index 0bf4ba09d..dc85c2e1a 100644 --- a/packages/pyright-internal/src/tests/samples/memberAccess12.py +++ b/packages/pyright-internal/src/tests/samples/memberAccess12.py @@ -9,12 +9,10 @@ T = TypeVar("T") class MetaClass(type): @overload - def __get__(self: type[T], instance: None, owner: Any) -> type[T]: - ... + def __get__(self: type[T], instance: None, owner: Any) -> type[T]: ... @overload - def __get__(self: type[T], instance: object, owner: Any) -> T: - ... + def __get__(self: type[T], instance: object, owner: Any) -> T: ... def __get__(self: type[T], instance: object | None, owner: Any) -> type[T] | T: if instance is None: @@ -22,8 +20,7 @@ class MetaClass(type): return self() -class A(metaclass=MetaClass): - ... +class A(metaclass=MetaClass): ... class B: diff --git a/packages/pyright-internal/src/tests/samples/memberAccess17.py b/packages/pyright-internal/src/tests/samples/memberAccess17.py index 212dbd727..fb7514c6a 100644 --- a/packages/pyright-internal/src/tests/samples/memberAccess17.py +++ b/packages/pyright-internal/src/tests/samples/memberAccess17.py @@ -6,12 +6,10 @@ from typing import Any, overload, Literal class Obj: @overload - def __getattr__(self, name: Literal["foo"]) -> int: - ... + def __getattr__(self, name: Literal["foo"]) -> int: ... @overload - def __getattr__(self, name: Literal["bar"]) -> str: - ... + def __getattr__(self, name: Literal["bar"]) -> str: ... def __getattr__(self, name: str) -> Any: if name == "foo": diff --git a/packages/pyright-internal/src/tests/samples/memberAccess19.py b/packages/pyright-internal/src/tests/samples/memberAccess19.py index 059d4e1db..a6e5b0ace 100644 --- a/packages/pyright-internal/src/tests/samples/memberAccess19.py +++ b/packages/pyright-internal/src/tests/samples/memberAccess19.py @@ -8,42 +8,33 @@ T = TypeVar("T") class A: @overload - def __getattr__(self, key: Literal["a"]) -> Literal["x"]: - ... + def __getattr__(self, key: Literal["a"]) -> Literal["x"]: ... @overload - def __getattr__(self, key: Literal["b"]) -> Literal[4]: - ... + def __getattr__(self, key: Literal["b"]) -> Literal[4]: ... @overload - def __getattr__(self, key: Literal["c"]) -> Literal["y"]: - ... + def __getattr__(self, key: Literal["c"]) -> Literal["y"]: ... @overload - def __getattr__(self: T, key: Literal["d"]) -> T: - ... + def __getattr__(self: T, key: Literal["d"]) -> T: ... - def __getattr__(self, key: Literal["a", "b", "c", "d"]) -> Any: - ... + def __getattr__(self, key: Literal["a", "b", "c", "d"]) -> Any: ... @overload - def __setattr__(self, key: Literal["e"], val: str): - ... + def __setattr__(self, key: Literal["e"], val: str): ... @overload - def __setattr__(self, key: Literal["f"], val: int): - ... + def __setattr__(self, key: Literal["f"], val: int): ... def __setattr__(self, key: str, val: str | int): pass @overload - def __delattr__(self, key: Literal["g"]): - ... + def __delattr__(self, key: Literal["g"]): ... @overload - def __delattr__(self, key: Literal["h"]): - ... + def __delattr__(self, key: Literal["h"]): ... def __delattr__(self, key: str): pass diff --git a/packages/pyright-internal/src/tests/samples/memberAccess21.py b/packages/pyright-internal/src/tests/samples/memberAccess21.py index 42c115c87..416c8fb15 100644 --- a/packages/pyright-internal/src/tests/samples/memberAccess21.py +++ b/packages/pyright-internal/src/tests/samples/memberAccess21.py @@ -10,21 +10,16 @@ T = TypeVar("T") class Descriptor(Generic[T]): @overload - def __get__(self, instance: None, owner) -> Self: - ... + def __get__(self, instance: None, owner) -> Self: ... @overload - def __get__(self, instance: object, owner) -> T: - ... + def __get__(self, instance: object, owner) -> T: ... - def __get__(self, instance: object | None, owner) -> Self | T: - ... + def __get__(self, instance: object | None, owner) -> Self | T: ... - def __set__(self, instance: object, value: T) -> None: - ... + def __set__(self, instance: object, value: T) -> None: ... - def is_null(self) -> bool: - ... + def is_null(self) -> bool: ... class Example: diff --git a/packages/pyright-internal/src/tests/samples/memberAccess23.py b/packages/pyright-internal/src/tests/samples/memberAccess23.py index 9135ca41b..12ec6f275 100644 --- a/packages/pyright-internal/src/tests/samples/memberAccess23.py +++ b/packages/pyright-internal/src/tests/samples/memberAccess23.py @@ -23,8 +23,7 @@ class MyMeta(type): attr6 = 6 - def __getattr__(self, name: str) -> complex: - ... + def __getattr__(self, name: str) -> complex: ... class A(metaclass=MyMeta): diff --git a/packages/pyright-internal/src/tests/samples/memberAccess24.py b/packages/pyright-internal/src/tests/samples/memberAccess24.py index 554e10957..125fd4e22 100644 --- a/packages/pyright-internal/src/tests/samples/memberAccess24.py +++ b/packages/pyright-internal/src/tests/samples/memberAccess24.py @@ -7,15 +7,12 @@ from dummy import UnknownX # type: ignore class Desc: @overload - def __get__(self, instance: None, owner: Any) -> "Desc": - ... + def __get__(self, instance: None, owner: Any) -> "Desc": ... @overload - def __get__(self, instance: object, owner: Any) -> int: - ... + def __get__(self, instance: object, owner: Any) -> int: ... - def __get__(self, instance: object | None, owner: Any) -> "Desc | int": - ... + def __get__(self, instance: object | None, owner: Any) -> "Desc | int": ... class DerivesFromUnknown(UnknownX): diff --git a/packages/pyright-internal/src/tests/samples/memberAccess4.py b/packages/pyright-internal/src/tests/samples/memberAccess4.py index 0a46b109e..aba9c7899 100644 --- a/packages/pyright-internal/src/tests/samples/memberAccess4.py +++ b/packages/pyright-internal/src/tests/samples/memberAccess4.py @@ -79,8 +79,7 @@ TFoo2 = TypeVar("TFoo2", bound="Foo2") class Foo2: @classmethod - def bar(cls: type[TFoo2]) -> TFoo2: - ... + def bar(cls: type[TFoo2]) -> TFoo2: ... def baz(self) -> None: self.bar() diff --git a/packages/pyright-internal/src/tests/samples/memberAccess8.py b/packages/pyright-internal/src/tests/samples/memberAccess8.py index 7bd249e66..d26f9477b 100644 --- a/packages/pyright-internal/src/tests/samples/memberAccess8.py +++ b/packages/pyright-internal/src/tests/samples/memberAccess8.py @@ -8,14 +8,11 @@ _T_co = TypeVar("_T_co", covariant=True) class Column(Generic[_T]): - def __get__(self, instance: object, type: Any) -> _T: - ... + def __get__(self, instance: object, type: Any) -> _T: ... - def __set__(self, instance: object, value: _T) -> _T: - ... + def __set__(self, instance: object, value: _T) -> _T: ... - def __delete__(self, instance: object) -> None: - ... + def __delete__(self, instance: object) -> None: ... class Foo: @@ -40,19 +37,15 @@ del foo.baz class Minimal(Generic[_T, _T_co]): - def __init__(self, name: str, func: Callable[[_T], _T_co]): - ... + def __init__(self, name: str, func: Callable[[_T], _T_co]): ... @overload - def __get__(self, instance: None, owner: type[_T]) -> "Minimal[_T, _T_co]": - ... + def __get__(self, instance: None, owner: type[_T]) -> "Minimal[_T, _T_co]": ... @overload - def __get__(self, instance: _T, owner: type[_T]) -> _T_co: - ... + def __get__(self, instance: _T, owner: type[_T]) -> _T_co: ... - def __get__(self, instance: _T | None, owner: type[_T]) -> Any: - ... + def __get__(self, instance: _T | None, owner: type[_T]) -> Any: ... def minimal_property( diff --git a/packages/pyright-internal/src/tests/samples/memberAccess9.py b/packages/pyright-internal/src/tests/samples/memberAccess9.py index aa8d6888d..46930b204 100644 --- a/packages/pyright-internal/src/tests/samples/memberAccess9.py +++ b/packages/pyright-internal/src/tests/samples/memberAccess9.py @@ -3,8 +3,7 @@ class GetAttrTest: - def __getattr__(self, name: str) -> int: - ... + def __getattr__(self, name: str) -> int: ... def test_get_attr() -> None: diff --git a/packages/pyright-internal/src/tests/samples/metaclass1.py b/packages/pyright-internal/src/tests/samples/metaclass1.py index 661805101..928876917 100644 --- a/packages/pyright-internal/src/tests/samples/metaclass1.py +++ b/packages/pyright-internal/src/tests/samples/metaclass1.py @@ -12,16 +12,13 @@ T = TypeVar("T") class CustomMeta(type): - def __getitem__(self, key: Any) -> "type[int]": - ... + def __getitem__(self, key: Any) -> "type[int]": ... -class Custom(metaclass=CustomMeta): - ... +class Custom(metaclass=CustomMeta): ... -class OtherMeta(type): - ... +class OtherMeta(type): ... # This should generate an error because the class isn't diff --git a/packages/pyright-internal/src/tests/samples/metaclass10.py b/packages/pyright-internal/src/tests/samples/metaclass10.py index 562e52011..b69eac397 100644 --- a/packages/pyright-internal/src/tests/samples/metaclass10.py +++ b/packages/pyright-internal/src/tests/samples/metaclass10.py @@ -15,8 +15,7 @@ class EnumMeta2(EnumMeta): class MyMeta(type): @classmethod - def meta_method(cls) -> None: - ... + def meta_method(cls) -> None: ... MyMeta.meta_method() diff --git a/packages/pyright-internal/src/tests/samples/metaclass11.py b/packages/pyright-internal/src/tests/samples/metaclass11.py index 98963b25f..90d186cfb 100644 --- a/packages/pyright-internal/src/tests/samples/metaclass11.py +++ b/packages/pyright-internal/src/tests/samples/metaclass11.py @@ -29,8 +29,7 @@ ClassA().var1 = "hi" class MetaB(type): - def __setattr__(cls, key: str, value: Any) -> None: - ... + def __setattr__(cls, key: str, value: Any) -> None: ... class ClassB(metaclass=MetaB): diff --git a/packages/pyright-internal/src/tests/samples/metaclass8.py b/packages/pyright-internal/src/tests/samples/metaclass8.py index 8c6cf99ba..41a74cbed 100644 --- a/packages/pyright-internal/src/tests/samples/metaclass8.py +++ b/packages/pyright-internal/src/tests/samples/metaclass8.py @@ -7,14 +7,11 @@ from typing import Any, Generic, TypeVar T = TypeVar("T") -class A(type, Generic[T]): - ... +class A(type, Generic[T]): ... # This should generate an error because generic metaclasses are not allowed. -class B(Generic[T], metaclass=A[T]): - ... +class B(Generic[T], metaclass=A[T]): ... -class C(metaclass=A[Any]): - ... +class C(metaclass=A[Any]): ... diff --git a/packages/pyright-internal/src/tests/samples/metaclass9.py b/packages/pyright-internal/src/tests/samples/metaclass9.py index f56269963..86c5d594d 100644 --- a/packages/pyright-internal/src/tests/samples/metaclass9.py +++ b/packages/pyright-internal/src/tests/samples/metaclass9.py @@ -15,31 +15,25 @@ class Meta1(type): param1: int, param2: str, param3: str = "", - ) -> T: - ... + ) -> T: ... -class Class1_1(metaclass=Meta1, param1=1, param2="", param3=""): - ... +class Class1_1(metaclass=Meta1, param1=1, param2="", param3=""): ... -class Class1_2(metaclass=Meta1, param2="", param1=1): - ... +class Class1_2(metaclass=Meta1, param2="", param1=1): ... # This should generate an error because param1 is the wrong type. -class Class1_3(metaclass=Meta1, param1="", param2=""): - ... +class Class1_3(metaclass=Meta1, param1="", param2=""): ... # This should generate an error because param1 and param2 are missing. -class Class1_4(metaclass=Meta1): - ... +class Class1_4(metaclass=Meta1): ... # This should generate an error because param4 doesn't exist. -class Class1_5(metaclass=Meta1, param2="", param1=1, param4=3): - ... +class Class1_5(metaclass=Meta1, param2="", param1=1, param4=3): ... class Meta2(type): @@ -51,28 +45,22 @@ class Meta2(type): *, param1: int, **kwargs: str, - ) -> T: - ... + ) -> T: ... -class Class2_1(metaclass=Meta2, param1=1, param2="", param3=""): - ... +class Class2_1(metaclass=Meta2, param1=1, param2="", param3=""): ... -class Class2_2(metaclass=Meta2, param2="", param1=1, param20=""): - ... +class Class2_2(metaclass=Meta2, param2="", param1=1, param20=""): ... # This should generate an error because param1 is the wrong type. -class Class2_3(metaclass=Meta2, param1="", param2=""): - ... +class Class2_3(metaclass=Meta2, param1="", param2=""): ... # This should generate an error because param1 is missing. -class Class2_4(metaclass=Meta2): - ... +class Class2_4(metaclass=Meta2): ... # This should generate an error because param4 is the wrong type. -class Class2_5(metaclass=Meta2, param2="", param1=1, param4=3): - ... +class Class2_5(metaclass=Meta2, param2="", param1=1, param4=3): ... diff --git a/packages/pyright-internal/src/tests/samples/methodOverride2.py b/packages/pyright-internal/src/tests/samples/methodOverride2.py index ad9b4671d..cff536fb8 100644 --- a/packages/pyright-internal/src/tests/samples/methodOverride2.py +++ b/packages/pyright-internal/src/tests/samples/methodOverride2.py @@ -6,75 +6,54 @@ from typing import Any, Generic, ParamSpec, Self, TypeVar class Base1: - def f1(self, *, kwarg0: int) -> None: - ... + def f1(self, *, kwarg0: int) -> None: ... - def f2(self, *, kwarg0: int) -> None: - ... + def f2(self, *, kwarg0: int) -> None: ... - def f3(self, *, kwarg0: int) -> None: - ... + def f3(self, *, kwarg0: int) -> None: ... - def f4(self, *, kwarg0: int) -> None: - ... + def f4(self, *, kwarg0: int) -> None: ... - def g1(self, a: int, /, b: str, *, kwarg0: int) -> None: - ... + def g1(self, a: int, /, b: str, *, kwarg0: int) -> None: ... - def g2(self, a: int, /, b: str, *, kwarg0: int) -> None: - ... + def g2(self, a: int, /, b: str, *, kwarg0: int) -> None: ... - def g3(self, a: int, /, b: str, *, kwarg0: int) -> None: - ... + def g3(self, a: int, /, b: str, *, kwarg0: int) -> None: ... - def g4(self, a: int, /, b: str, *, kwarg0: int) -> None: - ... + def g4(self, a: int, /, b: str, *, kwarg0: int) -> None: ... - def g5(self, a: int, /, b: str, *, kwarg0: int) -> None: - ... + def g5(self, a: int, /, b: str, *, kwarg0: int) -> None: ... - def g6(self, a: int, /, b: str, *, kwarg0: int) -> None: - ... + def g6(self, a: int, /, b: str, *, kwarg0: int) -> None: ... - def h1(self, a: int, *args: int) -> None: - ... + def h1(self, a: int, *args: int) -> None: ... class Derived1(Base1): - def f1(self, arg0: int = 0, *, kwarg0: int, kwarg1: int = 0) -> None: - ... + def f1(self, arg0: int = 0, *, kwarg0: int, kwarg1: int = 0) -> None: ... # This should generate an error because of a positional parameter mismatch. - def f2(self, arg0: int, *, kwarg0: int, kwarg1: int = 0) -> None: - ... + def f2(self, arg0: int, *, kwarg0: int, kwarg1: int = 0) -> None: ... # This should generate an error because of a missing kwarg1. - def f3(self, arg0: int = 0, *, kwarg0: int, kwarg1: int) -> None: - ... + def f3(self, arg0: int = 0, *, kwarg0: int, kwarg1: int) -> None: ... # This should generate an error because kwarg0 is the wrong type. - def f4(self, arg0: int = 0, *kwarg0: str) -> None: - ... + def f4(self, arg0: int = 0, *kwarg0: str) -> None: ... - def g1(self, xxx: int, /, b: str, *, kwarg0: int) -> None: - ... + def g1(self, xxx: int, /, b: str, *, kwarg0: int) -> None: ... - def g2(self, __a: int, b: str, *, kwarg0: int) -> None: - ... + def g2(self, __a: int, b: str, *, kwarg0: int) -> None: ... # This should generate an error because of a name mismatch between b and c. - def g3(self, __a: int, c: str, *, kwarg0: int) -> None: - ... + def g3(self, __a: int, c: str, *, kwarg0: int) -> None: ... # This should generate an error because of a type mismatch for b. - def g4(self, __a: int, b: int, *, kwarg0: int) -> None: - ... + def g4(self, __a: int, b: int, *, kwarg0: int) -> None: ... - def g5(self, __a: int, b: str = "hi", *, kwarg0: int) -> None: - ... + def g5(self, __a: int, b: str = "hi", *, kwarg0: int) -> None: ... - def g6(self, __a: int, b: str, c: str = "hi", *, kwarg0: int) -> None: - ... + def g6(self, __a: int, b: str, c: str = "hi", *, kwarg0: int) -> None: ... P = ParamSpec("P") @@ -82,36 +61,28 @@ R = TypeVar("R") class Base2(Generic[P, R]): - def method1(self, *args: P.args, **kwargs: P.kwargs) -> R: - ... + def method1(self, *args: P.args, **kwargs: P.kwargs) -> R: ... - def method2(self, *args: P.args, **kwargs: P.kwargs) -> R: - ... + def method2(self, *args: P.args, **kwargs: P.kwargs) -> R: ... class Derived2(Base2[P, R]): - def method1(self, *args: P.args, **kwargs: P.kwargs) -> R: - ... + def method1(self, *args: P.args, **kwargs: P.kwargs) -> R: ... - def method2(self, *args: Any, **kwargs: Any) -> R: - ... + def method2(self, *args: Any, **kwargs: Any) -> R: ... T = TypeVar("T") class Base3: - def method1(self, x: Self) -> Self: - ... + def method1(self, x: Self) -> Self: ... - def method2(self, x: Self) -> Self: - ... + def method2(self, x: Self) -> Self: ... class Derived3(Generic[T], Base3): - def method1(self, x: "Derived3[T]") -> "Derived3[T]": - ... + def method1(self, x: "Derived3[T]") -> "Derived3[T]": ... # This should generate an error. - def method2(self, x: "Derived3[int]") -> "Derived3[int]": - ... + def method2(self, x: "Derived3[int]") -> "Derived3[int]": ... diff --git a/packages/pyright-internal/src/tests/samples/methodOverride5.py b/packages/pyright-internal/src/tests/samples/methodOverride5.py index 542496333..e401c51be 100644 --- a/packages/pyright-internal/src/tests/samples/methodOverride5.py +++ b/packages/pyright-internal/src/tests/samples/methodOverride5.py @@ -10,16 +10,12 @@ Ts = TypeVarTuple("Ts") class Parent(Generic[*Ts]): - def method_1(self, *args: *Ts) -> None: - ... + def method_1(self, *args: *Ts) -> None: ... - def method_2(self, *args: * tuple[*Ts]) -> None: - ... + def method_2(self, *args: *tuple[*Ts]) -> None: ... class Child(Parent[int]): - def method_1(self, arg1: int) -> None: - ... + def method_1(self, arg1: int) -> None: ... - def method_2(self, arg1: int) -> None: - ... + def method_2(self, arg1: int) -> None: ... diff --git a/packages/pyright-internal/src/tests/samples/methodOverride6.py b/packages/pyright-internal/src/tests/samples/methodOverride6.py index 136298ed5..20b2bdbfc 100644 --- a/packages/pyright-internal/src/tests/samples/methodOverride6.py +++ b/packages/pyright-internal/src/tests/samples/methodOverride6.py @@ -7,16 +7,13 @@ _T = TypeVar("_T") class Parent1(Generic[_T]): @overload - def m1(self, x: Literal[True]) -> int: - ... + def m1(self, x: Literal[True]) -> int: ... @overload - def m1(self, x: Literal[False]) -> float: - ... + def m1(self, x: Literal[False]) -> float: ... @overload - def m1(self, x: _T) -> _T: - ... + def m1(self, x: _T) -> _T: ... def m1(self, x: bool | _T) -> int | float | _T: return x @@ -24,12 +21,10 @@ class Parent1(Generic[_T]): class Child1_1(Parent1[str]): @overload - def m1(self, x: bool) -> int: - ... + def m1(self, x: bool) -> int: ... @overload - def m1(self, x: str) -> str: - ... + def m1(self, x: str) -> str: ... def m1(self, x: bool | str) -> int | str: return x @@ -42,12 +37,10 @@ class Child1_2(Parent1[str]): class Child1_3(Parent1[str]): @overload - def m1(self, x: bool) -> int: - ... + def m1(self, x: bool) -> int: ... @overload - def m1(self, x: str) -> str: - ... + def m1(self, x: str) -> str: ... def m1(self, x: bool | str) -> int | float | str: return x @@ -55,12 +48,10 @@ class Child1_3(Parent1[str]): class Child1_4(Parent1[str]): @overload - def m1(self, x: str) -> str: - ... + def m1(self, x: str) -> str: ... @overload - def m1(self, x: bool) -> int: - ... + def m1(self, x: bool) -> int: ... # This should generate an error because the overloads are # in the wrong order. @@ -70,16 +61,13 @@ class Child1_4(Parent1[str]): class Child1_5(Parent1[str]): @overload - def m1(self, x: Literal[True]) -> int: - ... + def m1(self, x: Literal[True]) -> int: ... @overload - def m1(self, x: Literal[False]) -> float: - ... + def m1(self, x: Literal[False]) -> float: ... @overload - def m1(self, x: bytes) -> bytes: - ... + def m1(self, x: bytes) -> bytes: ... # This should generate an error because the overloads are # in the wrong order. @@ -89,16 +77,13 @@ class Child1_5(Parent1[str]): class Child1_6(Parent1[bytes]): @overload - def m1(self, x: Literal[True]) -> int: - ... + def m1(self, x: Literal[True]) -> int: ... @overload - def m1(self, x: Literal[False]) -> float: - ... + def m1(self, x: Literal[False]) -> float: ... @overload - def m1(self, x: bytes) -> bytes: - ... + def m1(self, x: bytes) -> bytes: ... def m1(self, x: bool | bytes) -> int | float | bytes: return x @@ -106,113 +91,89 @@ class Child1_6(Parent1[bytes]): class Parent2(Generic[_T]): @overload - def method1(self: "Parent2[int]", x: list[int]) -> list[int]: - ... + def method1(self: "Parent2[int]", x: list[int]) -> list[int]: ... @overload - def method1(self, x: str) -> dict[str, str]: - ... + def method1(self, x: str) -> dict[str, str]: ... - def method1(self, x: Any) -> Any: - ... + def method1(self, x: Any) -> Any: ... @overload - def method2(self: "Parent2[int]", x: list[int]) -> list[int]: - ... + def method2(self: "Parent2[int]", x: list[int]) -> list[int]: ... @overload - def method2(self, x: str) -> dict[str, str]: - ... + def method2(self, x: str) -> dict[str, str]: ... @overload - def method2(self, x: int) -> int: - ... + def method2(self, x: int) -> int: ... - def method2(self, x: Any) -> Any: - ... + def method2(self, x: Any) -> Any: ... @overload @classmethod - def method3(cls: "type[Parent2[int]]", x: list[int]) -> list[int]: - ... + def method3(cls: "type[Parent2[int]]", x: list[int]) -> list[int]: ... @overload @classmethod - def method3(cls, x: str) -> dict[str, str]: - ... + def method3(cls, x: str) -> dict[str, str]: ... @classmethod - def method3(cls, x: Any) -> Any: - ... + def method3(cls, x: Any) -> Any: ... @overload @classmethod - def method4(cls: "type[Parent2[int]]", x: list[int]) -> list[int]: - ... + def method4(cls: "type[Parent2[int]]", x: list[int]) -> list[int]: ... @overload @classmethod - def method4(cls, x: str) -> dict[str, str]: - ... + def method4(cls, x: str) -> dict[str, str]: ... @overload @classmethod - def method4(cls, x: int) -> int: - ... + def method4(cls, x: int) -> int: ... @classmethod - def method4(cls, x: Any) -> Any: - ... + def method4(cls, x: Any) -> Any: ... class Child2_1(Parent2[str]): - def method1(self, x: str) -> dict[str, str]: - ... + def method1(self, x: str) -> dict[str, str]: ... class Child2_2(Parent2[str]): @overload - def method2(self, x: str) -> dict[str, str]: - ... + def method2(self, x: str) -> dict[str, str]: ... @overload - def method2(self, x: int) -> int: - ... + def method2(self, x: int) -> int: ... - def method2(self, x: Any) -> Any: - ... + def method2(self, x: Any) -> Any: ... class Child2_3(Parent2[str]): @classmethod - def method3(cls, x: str) -> dict[str, str]: - ... + def method3(cls, x: str) -> dict[str, str]: ... class Child2_4(Parent2[str]): @overload @classmethod - def method4(cls, x: str) -> dict[str, str]: - ... + def method4(cls, x: str) -> dict[str, str]: ... @overload @classmethod - def method4(cls, x: int) -> int: - ... + def method4(cls, x: int) -> int: ... @classmethod - def method4(cls, x: Any) -> Any: - ... + def method4(cls, x: Any) -> Any: ... class Parent3: @overload - def method(self, x: int) -> int: - ... + def method(self, x: int) -> int: ... @overload - def method(self, x: str) -> str: - ... + def method(self, x: str) -> str: ... def method(self, x: int | str) -> int | str: return x @@ -220,16 +181,13 @@ class Parent3: class Child3_1(Parent3): @overload - def method(self, x: int) -> int: - ... + def method(self, x: int) -> int: ... @overload - def method(self, x: str) -> str: - ... + def method(self, x: str) -> str: ... @overload - def method(self, x: list[float]) -> list[float]: - ... + def method(self, x: list[float]) -> list[float]: ... def method(self, x: int | str | list[float]) -> int | str | list[float]: return x @@ -237,16 +195,13 @@ class Child3_1(Parent3): class Parent4(Generic[_T]): @overload - def m1(self: "Parent4[int]", a: None) -> float: - ... + def m1(self: "Parent4[int]", a: None) -> float: ... @overload - def m1(self: "Parent4[int]", a: int) -> float: - ... + def m1(self: "Parent4[int]", a: int) -> float: ... @overload - def m1(self: "Parent4[float]", a: None) -> str: - ... + def m1(self: "Parent4[float]", a: None) -> str: ... def m1(self, a: int | None = None) -> float | str: raise NotImplementedError @@ -254,12 +209,10 @@ class Parent4(Generic[_T]): class Child4_1(Parent4[int]): @overload - def function(self: Parent4[int], a: None) -> float: - ... + def function(self: Parent4[int], a: None) -> float: ... @overload - def function(self: Parent4[int], a: int) -> float: - ... + def function(self: Parent4[int], a: int) -> float: ... def function(self, a: int | None = None) -> float: return 0.0 @@ -267,27 +220,21 @@ class Child4_1(Parent4[int]): class Parent5: @overload - def m1(self, x: int) -> int: - ... + def m1(self, x: int) -> int: ... @overload - def m1(self, x: str) -> str: - ... + def m1(self, x: str) -> str: ... - def m1(self, x: int | str) -> int | str: - ... + def m1(self, x: int | str) -> int | str: ... class Parent5_1(Parent5): @overload - def m1(self, x: bytes) -> bytes: - ... + def m1(self, x: bytes) -> bytes: ... @overload - def m1(self, x: str) -> str: - ... + def m1(self, x: str) -> str: ... # This should generate an error because the overloads are # incompatible - def m1(self, x: bytes | str) -> bytes | str: - ... + def m1(self, x: bytes | str) -> bytes | str: ... diff --git a/packages/pyright-internal/src/tests/samples/methods1.py b/packages/pyright-internal/src/tests/samples/methods1.py index aa40c1b2a..4c24e9bac 100644 --- a/packages/pyright-internal/src/tests/samples/methods1.py +++ b/packages/pyright-internal/src/tests/samples/methods1.py @@ -16,7 +16,7 @@ def deco1(x: Callable[P, R]) -> Callable[P, R]: def deco2( - func: Callable[P, Any] + func: Callable[P, Any], ) -> Callable[[Callable[..., Any]], Callable[Concatenate["ClassA", P], None]]: return lambda f: f # type: ignore diff --git a/packages/pyright-internal/src/tests/samples/missingTypeArg1.py b/packages/pyright-internal/src/tests/samples/missingTypeArg1.py index 6710d5825..685a7f16e 100644 --- a/packages/pyright-internal/src/tests/samples/missingTypeArg1.py +++ b/packages/pyright-internal/src/tests/samples/missingTypeArg1.py @@ -42,8 +42,7 @@ a = Class3[int] # This should generate an error when reportMissingTypeArgument is enabled. -def func1() -> collections.deque: - ... +def func1() -> collections.deque: ... def func2(obj: object): diff --git a/packages/pyright-internal/src/tests/samples/mro4.py b/packages/pyright-internal/src/tests/samples/mro4.py index 43144e733..224dc7203 100644 --- a/packages/pyright-internal/src/tests/samples/mro4.py +++ b/packages/pyright-internal/src/tests/samples/mro4.py @@ -9,22 +9,17 @@ T1 = TypeVar("T1") T2 = TypeVar("T2") -class Foo1(Generic[T1]): - ... +class Foo1(Generic[T1]): ... -class Foo2(Generic[T1]): - ... +class Foo2(Generic[T1]): ... -class Bar1(Generic[T1, T2], Foo1[T1], Foo2[T2]): - ... +class Bar1(Generic[T1, T2], Foo1[T1], Foo2[T2]): ... -class Bar2(Generic[T1, T2], Foo1, Foo2[T2]): - ... +class Bar2(Generic[T1, T2], Foo1, Foo2[T2]): ... # This should generate an error because a consistent MRO cannot be found. -class Bar3(Generic[T1, T2], Foo1, Foo2): - ... +class Bar3(Generic[T1, T2], Foo1, Foo2): ... diff --git a/packages/pyright-internal/src/tests/samples/namedTuple8.py b/packages/pyright-internal/src/tests/samples/namedTuple8.py index d5458f6bc..8f59415e2 100644 --- a/packages/pyright-internal/src/tests/samples/namedTuple8.py +++ b/packages/pyright-internal/src/tests/samples/namedTuple8.py @@ -8,8 +8,7 @@ class GenericNT(NamedTuple, Generic[AnyStr]): class SpecializedNT(GenericNT[str]): - def geturl(self) -> str: - ... + def geturl(self) -> str: ... def func(x: SpecializedNT): diff --git a/packages/pyright-internal/src/tests/samples/newType1.py b/packages/pyright-internal/src/tests/samples/newType1.py index 0a51a0bdc..6a3dfa0dc 100644 --- a/packages/pyright-internal/src/tests/samples/newType1.py +++ b/packages/pyright-internal/src/tests/samples/newType1.py @@ -1,6 +1,7 @@ # This sample tests the type handler's handling of the # built-in NewType function. +from abc import ABC, abstractmethod from typing import Any, NewType, TypeVar, TypedDict MyString = NewType("MyString", "str") @@ -76,3 +77,17 @@ def func2(x: MyString): # with a NewType. if issubclass(type(x), (MyString, int)): pass + + +class AbstractBase(ABC): + @abstractmethod + def method1(self, /) -> int: ... + + +class DerivedBase(AbstractBase): + def method1(self, /) -> int: + return 0 + + +NewDerived = NewType("NewDerived", AbstractBase) +new_derived = NewDerived(DerivedBase()) diff --git a/packages/pyright-internal/src/tests/samples/newType3.py b/packages/pyright-internal/src/tests/samples/newType3.py index 5d6648da6..15a60a2a3 100644 --- a/packages/pyright-internal/src/tests/samples/newType3.py +++ b/packages/pyright-internal/src/tests/samples/newType3.py @@ -21,8 +21,7 @@ var3 = UserId("2") var4 = UserId(2, 3) -def require_user_id(a: UserId): - ... +def require_user_id(a: UserId): ... require_user_id(var2) diff --git a/packages/pyright-internal/src/tests/samples/newType6.py b/packages/pyright-internal/src/tests/samples/newType6.py index 7c75d0256..e4a65d44f 100644 --- a/packages/pyright-internal/src/tests/samples/newType6.py +++ b/packages/pyright-internal/src/tests/samples/newType6.py @@ -9,5 +9,4 @@ MyStr = NewType("MyStr", str) # This should generate an error. -class A(MyStr): - ... +class A(MyStr): ... diff --git a/packages/pyright-internal/src/tests/samples/none1.py b/packages/pyright-internal/src/tests/samples/none1.py index 1297fa8f4..393839831 100644 --- a/packages/pyright-internal/src/tests/samples/none1.py +++ b/packages/pyright-internal/src/tests/samples/none1.py @@ -17,8 +17,7 @@ def func1(a: int | None): a.__doc__ -def func2(x: type[None]): - ... +def func2(x: type[None]): ... func2(None.__class__) diff --git a/packages/pyright-internal/src/tests/samples/noreturn1.py b/packages/pyright-internal/src/tests/samples/noreturn1.py index 03f5565e9..0fc933d31 100644 --- a/packages/pyright-internal/src/tests/samples/noreturn1.py +++ b/packages/pyright-internal/src/tests/samples/noreturn1.py @@ -41,8 +41,7 @@ def func5(x: bool) -> NoReturn: x1: Callable[[bool], bool] = func2 -async def func6() -> NoReturn: - ... +async def func6() -> NoReturn: ... async def func7() -> NoReturn: @@ -50,8 +49,7 @@ async def func7() -> NoReturn: class A: - def __new__(cls) -> NoReturn: - ... + def __new__(cls) -> NoReturn: ... def func8() -> NoReturn: @@ -59,8 +57,7 @@ def func8() -> NoReturn: class C: - def __call__(self) -> NoReturn: - ... + def __call__(self) -> NoReturn: ... def func10() -> NoReturn: @@ -68,17 +65,14 @@ def func10() -> NoReturn: @overload -def func11() -> NoReturn: - ... +def func11() -> NoReturn: ... @overload -def func11(x: int) -> None: - ... +def func11(x: int) -> None: ... -def func11(x: int = 0) -> NoReturn | None: - ... +def func11(x: int = 0) -> NoReturn | None: ... def func12() -> NoReturn: diff --git a/packages/pyright-internal/src/tests/samples/noreturn3.py b/packages/pyright-internal/src/tests/samples/noreturn3.py index d3058f1e4..5b84e5041 100644 --- a/packages/pyright-internal/src/tests/samples/noreturn3.py +++ b/packages/pyright-internal/src/tests/samples/noreturn3.py @@ -5,8 +5,7 @@ from typing import NoReturn class MyClass: - def no_return(self) -> NoReturn: - ... + def no_return(self) -> NoReturn: ... def client_code() -> NoReturn: diff --git a/packages/pyright-internal/src/tests/samples/noreturn4.py b/packages/pyright-internal/src/tests/samples/noreturn4.py index 79b2c64d0..cbf79156e 100644 --- a/packages/pyright-internal/src/tests/samples/noreturn4.py +++ b/packages/pyright-internal/src/tests/samples/noreturn4.py @@ -7,12 +7,10 @@ from typing import Callable, NoReturn, TypeVar _T = TypeVar("_T", int, str) -def func1(x: Callable[[NoReturn], None]): - ... +def func1(x: Callable[[NoReturn], None]): ... -def func2(x: int) -> NoReturn: - ... +def func2(x: int) -> NoReturn: ... def func3(x: _T) -> _T: diff --git a/packages/pyright-internal/src/tests/samples/operator1.py b/packages/pyright-internal/src/tests/samples/operator1.py index 097020059..50749f38a 100644 --- a/packages/pyright-internal/src/tests/samples/operator1.py +++ b/packages/pyright-internal/src/tests/samples/operator1.py @@ -104,8 +104,7 @@ _ = e + e class F: - def __add__(self, other: object) -> NoReturn: - ... + def __add__(self, other: object) -> NoReturn: ... f = F() + "" diff --git a/packages/pyright-internal/src/tests/samples/operator11.py b/packages/pyright-internal/src/tests/samples/operator11.py index 317b154f4..ead436ec6 100644 --- a/packages/pyright-internal/src/tests/samples/operator11.py +++ b/packages/pyright-internal/src/tests/samples/operator11.py @@ -5,8 +5,7 @@ from typing import Protocol class ComparisonOp(Protocol): - def __call__(self, other: object, /) -> bool: - ... + def __call__(self, other: object, /) -> bool: ... class Number: diff --git a/packages/pyright-internal/src/tests/samples/operator9.py b/packages/pyright-internal/src/tests/samples/operator9.py index 2d4e3eb72..ba639a3ed 100644 --- a/packages/pyright-internal/src/tests/samples/operator9.py +++ b/packages/pyright-internal/src/tests/samples/operator9.py @@ -8,12 +8,10 @@ T2 = TypeVar("T2") class S(Generic[T1]): - def __or__(self, other: "S[T2]") -> "S[T1 | T2]": - ... + def __or__(self, other: "S[T2]") -> "S[T1 | T2]": ... -def to(x: Callable[..., T1]) -> "S[T1]": - ... +def to(x: Callable[..., T1]) -> "S[T1]": ... x1 = to(int) | to(float) diff --git a/packages/pyright-internal/src/tests/samples/optional2.py b/packages/pyright-internal/src/tests/samples/optional2.py index 8b14de9e6..998105bdb 100644 --- a/packages/pyright-internal/src/tests/samples/optional2.py +++ b/packages/pyright-internal/src/tests/samples/optional2.py @@ -7,14 +7,11 @@ from typing import Optional class Cmp: - def __eq__(self, other: "Optional[Cmp]") -> bool: - ... + def __eq__(self, other: "Optional[Cmp]") -> bool: ... - def __lt__(self, other: "Optional[Cmp]") -> bool: - ... + def __lt__(self, other: "Optional[Cmp]") -> bool: ... - def __gt__(self, other: "Cmp") -> bool: - ... + def __gt__(self, other: "Cmp") -> bool: ... def valid(value: Optional[Cmp], needed: Cmp): diff --git a/packages/pyright-internal/src/tests/samples/overload1.py b/packages/pyright-internal/src/tests/samples/overload1.py index 86b0744b8..cbddb049d 100644 --- a/packages/pyright-internal/src/tests/samples/overload1.py +++ b/packages/pyright-internal/src/tests/samples/overload1.py @@ -5,18 +5,15 @@ from datetime import datetime, timezone, timedelta @overload -def func1(ts: int) -> datetime: - ... +def func1(ts: int) -> datetime: ... @overload -def func1(ts: None) -> None: - ... +def func1(ts: None) -> None: ... @overload -def func1(ts: complex): - ... +def func1(ts: complex): ... def func1(ts: int | complex | None) -> datetime | None: @@ -33,13 +30,11 @@ reveal_type(func1(3j), expected_text="Unknown") @overload -def func2(x: int) -> int: - ... +def func2(x: int) -> int: ... @overload -def func2(x: float) -> float: - ... +def func2(x: float) -> float: ... def func2(x): diff --git a/packages/pyright-internal/src/tests/samples/overload10.py b/packages/pyright-internal/src/tests/samples/overload10.py index 742db18e5..d7938b6e8 100644 --- a/packages/pyright-internal/src/tests/samples/overload10.py +++ b/packages/pyright-internal/src/tests/samples/overload10.py @@ -10,24 +10,20 @@ _T2 = TypeVar("_T2") @overload -def func1(__iter1: Iterable[_T1]) -> Tuple[_T1]: - ... +def func1(__iter1: Iterable[_T1]) -> Tuple[_T1]: ... @overload -def func1(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Tuple[_T1, _T2]: - ... +def func1(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Tuple[_T1, _T2]: ... # This should generate an error because this overload overlaps # with the first one and returns a different type. @overload -def func1(*iterables: Iterable[_T1]) -> Tuple[_T1, ...]: - ... +def func1(*iterables: Iterable[_T1]) -> Tuple[_T1, ...]: ... -def func1(*iterables: Iterable[_T1]) -> Tuple[_T1, ...]: - ... +def func1(*iterables: Iterable[_T1]) -> Tuple[_T1, ...]: ... def func2(x: Iterable[int]): diff --git a/packages/pyright-internal/src/tests/samples/overload11.py b/packages/pyright-internal/src/tests/samples/overload11.py index 16084d054..5fb09970f 100644 --- a/packages/pyright-internal/src/tests/samples/overload11.py +++ b/packages/pyright-internal/src/tests/samples/overload11.py @@ -13,12 +13,10 @@ class Base1: class Derived1(Base1): @overload - def foo(self, x: int) -> int: - ... + def foo(self, x: int) -> int: ... @overload - def foo(self, x: str) -> str: - ... + def foo(self, x: str) -> str: ... def foo(self, x: int | str) -> int | str: return x @@ -31,12 +29,10 @@ class Base2: class Derived2(Base2): @overload - def foo(self, x: int) -> int: - ... + def foo(self, x: int) -> int: ... @overload - def foo(self, x: str) -> str: - ... + def foo(self, x: str) -> str: ... def foo(self, x: int | str) -> int | str: return x @@ -49,12 +45,10 @@ class Base3: class Derived3(Base3): @overload - def foo(self, x: float) -> float: - ... + def foo(self, x: float) -> float: ... @overload - def foo(self, x: str) -> str: - ... + def foo(self, x: str) -> str: ... # This should generate an error because no overloaded signature # is compatible with the base method, nor is the implementation. diff --git a/packages/pyright-internal/src/tests/samples/overload15.py b/packages/pyright-internal/src/tests/samples/overload15.py index 64937b759..72207d3d3 100644 --- a/packages/pyright-internal/src/tests/samples/overload15.py +++ b/packages/pyright-internal/src/tests/samples/overload15.py @@ -8,22 +8,18 @@ R = TypeVar("R") def callable1( func: Callable[P, R], *args: P.args, **kwargs: P.kwargs -) -> Callable[[], R]: - ... +) -> Callable[[], R]: ... @overload -def func1() -> None: - ... +def func1() -> None: ... @overload -def func1(a: int) -> None: - ... +def func1(a: int) -> None: ... -def func1(a: int = 1) -> None: - ... +def func1(a: int = 1) -> None: ... callable1(func1) @@ -41,27 +37,22 @@ callable1(func1, b=2) def callable2( func: Callable[Concatenate[int, P], R], *args: P.args, **kwargs: P.kwargs -) -> Callable[[], R]: - ... +) -> Callable[[], R]: ... @overload -def func2() -> None: - ... +def func2() -> None: ... @overload -def func2(a: int) -> int: - ... +def func2(a: int) -> int: ... @overload -def func2(a: int, b: str) -> str: - ... +def func2(a: int, b: str) -> str: ... -def func2(a: int = 1, b: str = "") -> None | int | str: - ... +def func2(a: int = 1, b: str = "") -> None | int | str: ... callable2(func2) @@ -73,8 +64,7 @@ callable2(func2, b="") callable2(func2, 1, "") -def callable3(func: Callable[P, R]) -> Callable[Concatenate[int, P], R]: - ... +def callable3(func: Callable[P, R]) -> Callable[Concatenate[int, P], R]: ... c3_2 = callable3(func2) @@ -92,21 +82,18 @@ c3_2(1, 1, c="") @overload -def func3(x: int) -> None: - ... +def func3(x: int) -> None: ... @overload -def func3(x: str) -> None: - ... +def func3(x: str) -> None: ... def func3(x) -> None: pass -def callable4(func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: - ... +def callable4(func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: ... callable4(func3, 1) @@ -122,13 +109,11 @@ callable4(func3, y=1) @overload -def func4(x: str) -> str: - ... +def func4(x: str) -> str: ... @overload -def func4(x: int) -> int: - ... +def func4(x: int) -> int: ... def func4(x: str | int): diff --git a/packages/pyright-internal/src/tests/samples/overload16.py b/packages/pyright-internal/src/tests/samples/overload16.py index a7b887ad7..ec2141134 100644 --- a/packages/pyright-internal/src/tests/samples/overload16.py +++ b/packages/pyright-internal/src/tests/samples/overload16.py @@ -10,12 +10,10 @@ T = TypeVar("T") class A(Generic[T]): @overload - def func1(self: "A[bool]", x: "A[bool]") -> list[LiteralString]: - ... + def func1(self: "A[bool]", x: "A[bool]") -> list[LiteralString]: ... @overload - def func1(self, x: "A[Any]") -> list[str]: - ... + def func1(self, x: "A[Any]") -> list[str]: ... def func1(self, x: "A[Any]") -> list[str] | list[LiteralString]: return [] diff --git a/packages/pyright-internal/src/tests/samples/overload17.py b/packages/pyright-internal/src/tests/samples/overload17.py index 27b05b93f..055eaa109 100644 --- a/packages/pyright-internal/src/tests/samples/overload17.py +++ b/packages/pyright-internal/src/tests/samples/overload17.py @@ -7,13 +7,11 @@ from typing import Any, overload class A: @overload # This should emit an error because @staticmethod is used inconsistently. - def method1(self, x: int) -> int: - ... + def method1(self, x: int) -> int: ... @overload @staticmethod - def method1(x: str) -> str: - ... + def method1(x: str) -> str: ... def method1(*args: Any, **kwargs: Any) -> Any: return @@ -21,24 +19,20 @@ class A: @overload @classmethod # This should emit an error because @classmethod is used inconsistently. - def method2(cls, x: str) -> str: - ... + def method2(cls, x: str) -> str: ... @overload - def method2(self, x: int) -> int: - ... + def method2(self, x: int) -> int: ... def method2(*args: Any, **kwargs: Any) -> Any: return @overload # This should emit an error because @staticmethod is used inconsistently. - def method3(self, x: str) -> str: - ... + def method3(self, x: str) -> str: ... @overload - def method3(self, x: int) -> int: - ... + def method3(self, x: int) -> int: ... @staticmethod def method3(*args: Any, **kwargs: Any) -> Any: diff --git a/packages/pyright-internal/src/tests/samples/overload2.py b/packages/pyright-internal/src/tests/samples/overload2.py index c989007ca..41886c790 100644 --- a/packages/pyright-internal/src/tests/samples/overload2.py +++ b/packages/pyright-internal/src/tests/samples/overload2.py @@ -5,13 +5,11 @@ from typing import overload @overload -async def func(x: int) -> int: - ... +async def func(x: int) -> int: ... @overload -async def func(x: str) -> str: - ... +async def func(x: str) -> str: ... async def func(x) -> int | str: diff --git a/packages/pyright-internal/src/tests/samples/overload3.py b/packages/pyright-internal/src/tests/samples/overload3.py index a95238567..fab26bfaa 100644 --- a/packages/pyright-internal/src/tests/samples/overload3.py +++ b/packages/pyright-internal/src/tests/samples/overload3.py @@ -8,13 +8,11 @@ T = TypeVar("T") @overload -def mouse_event(x1: int, y1: int) -> int: - ... +def mouse_event(x1: int, y1: int) -> int: ... @overload -def mouse_event(x1: int, y1: int, x2: int, y2: int) -> tuple[int, int]: - ... +def mouse_event(x1: int, y1: int, x2: int, y2: int) -> tuple[int, int]: ... def mouse_event( diff --git a/packages/pyright-internal/src/tests/samples/overload4.py b/packages/pyright-internal/src/tests/samples/overload4.py index c29bbd1c7..4272a3f08 100644 --- a/packages/pyright-internal/src/tests/samples/overload4.py +++ b/packages/pyright-internal/src/tests/samples/overload4.py @@ -43,7 +43,7 @@ class ClassB(Protocol): def deco1( - _origin: Callable[P, T] + _origin: Callable[P, T], ) -> Callable[[Callable[..., Any]], Callable[P, T]]: ... @@ -60,3 +60,21 @@ def func5(v: int | str) -> int | str: ... @deco1(func5) def func6(*args: Any, **kwargs: Any) -> Any: ... + + +@overload +def deco2() -> Callable[[Callable[P, T]], Callable[P, T | None]]: ... +@overload +def deco2( + x: Callable[[], T], +) -> Callable[[Callable[P, T]], Callable[P, T]]: ... + + +def deco2( + x: Callable[[], T | None] = lambda: None, +) -> Callable[[Callable[P, T]], Callable[P, T | None]]: ... + + +@deco2(x=dict) +def func7() -> dict[str, str]: + return {} diff --git a/packages/pyright-internal/src/tests/samples/overload5.py b/packages/pyright-internal/src/tests/samples/overload5.py index 9a810a0ed..bcb3da71e 100644 --- a/packages/pyright-internal/src/tests/samples/overload5.py +++ b/packages/pyright-internal/src/tests/samples/overload5.py @@ -5,30 +5,25 @@ from typing import Any, AnyStr, Generic, Literal, Protocol, Sequence, TypeVar, o @overload -def func1(a: float, b: float | None, c: bool | None = None) -> int: - ... +def func1(a: float, b: float | None, c: bool | None = None) -> int: ... # This should generate an error because the overload is obscured. @overload -def func1(a: int, b: int) -> int: - ... +def func1(a: int, b: int) -> int: ... @overload -def func1(a: int, b: int, *, named: int = 3) -> int: - ... +def func1(a: int, b: int, *, named: int = 3) -> int: ... # This should generate an error because the overload is obscured. @overload -def func1(a: int, b: int, *, named: int) -> int: - ... +def func1(a: int, b: int, *, named: int) -> int: ... @overload -def func1(a: complex, b: int) -> int: - ... +def func1(a: complex, b: int) -> int: ... def func1(*args: Any, **kwargs: Any) -> Any: @@ -51,18 +46,15 @@ def func2(*args: Any, **kwargs: Any) -> Any: @overload -def func3(a: int, b: int) -> int: - ... +def func3(a: int, b: int) -> int: ... @overload -def func3(a: int, b: int, **c: Any) -> int: - ... +def func3(a: int, b: int, **c: Any) -> int: ... @overload -def func3(a: int, b: Any) -> int: - ... +def func3(a: int, b: Any) -> int: ... def func3(*args: Any, **kwargs: Any) -> Any: @@ -70,14 +62,12 @@ def func3(*args: Any, **kwargs: Any) -> Any: @overload -def func4(a: int, *, c: int, b: int) -> int: - ... +def func4(a: int, *, c: int, b: int) -> int: ... # This should generate an error because the overload is obscured. @overload -def func4(a: int, *, b: int, c: int) -> int: - ... +def func4(a: int, *, b: int, c: int) -> int: ... def func4(*args: Any, **kwargs: Any) -> Any: @@ -87,13 +77,11 @@ def func4(*args: Any, **kwargs: Any) -> Any: # This should generate an error because the overload is overlapping # in an unsafe way (i.e. returns an incompatible type). @overload -def func5(a: int, b: int) -> int: - ... +def func5(a: int, b: int) -> int: ... @overload -def func5(a: float, b: float = 3.4, *c: int, d: float = 4.5) -> str: - ... +def func5(a: float, b: float = 3.4, *c: int, d: float = 4.5) -> str: ... def func5(*args: Any, **kwargs: Any) -> Any: @@ -106,45 +94,36 @@ _T2 = TypeVar("_T2") class GenericClass(Generic[_T1, _T2]): @overload - def method1(self, a: _T1, b: tuple[_T2, ...]) -> int: - ... + def method1(self, a: _T1, b: tuple[_T2, ...]) -> int: ... @overload - def method1(self, a: _T1, b: tuple[Any, ...]) -> int: - ... + def method1(self, a: _T1, b: tuple[Any, ...]) -> int: ... - def method1(self, *args: Any, **kwargs: Any) -> Any: - ... + def method1(self, *args: Any, **kwargs: Any) -> Any: ... @overload - def method2(self, a: _T2, b: int) -> int: - ... + def method2(self, a: _T2, b: int) -> int: ... @overload - def method2(self, a: _T1, b: _T2) -> int: - ... + def method2(self, a: _T1, b: _T2) -> int: ... def method2(self, *args: Any, **kwargs: Any) -> Any: pass -class Parent: - ... +class Parent: ... -class Child(Parent): - ... +class Child(Parent): ... # Test 1: Literal subtype @overload -def func10(x: Literal[3]) -> int: - ... +def func10(x: Literal[3]) -> int: ... @overload -def func10(x: int) -> str: - ... +def func10(x: int) -> str: ... def func10(*args: Any, **kwargs: Any) -> Any: @@ -153,13 +132,11 @@ def func10(*args: Any, **kwargs: Any) -> Any: # Test 2: Subclass subtype @overload -def func11(x: Child) -> str: - ... +def func11(x: Child) -> str: ... @overload -def func11(x: Parent) -> int: - ... +def func11(x: Parent) -> int: ... def func11(*args: Any, **kwargs: Any) -> Any: @@ -168,13 +145,11 @@ def func11(*args: Any, **kwargs: Any) -> Any: # Test 3: Implicit subtype @overload -def func12(x: int) -> str: - ... +def func12(x: int) -> str: ... @overload -def func12(x: float) -> int: - ... +def func12(x: float) -> int: ... def func12(*args: Any, **kwargs: Any) -> Any: @@ -183,13 +158,11 @@ def func12(*args: Any, **kwargs: Any) -> Any: # Test 4: Union subtype @overload -def func13(x: int) -> str: - ... +def func13(x: int) -> str: ... @overload -def func13(x: int | str) -> int: - ... +def func13(x: int | str) -> int: ... def func13(*args: Any, **kwargs: Any) -> Any: @@ -198,13 +171,11 @@ def func13(*args: Any, **kwargs: Any) -> Any: # Test 5: non-matching keyword argument @overload -def func14(x: int, *, cls: str, **kwargs: Any) -> int: - ... +def func14(x: int, *, cls: str, **kwargs: Any) -> int: ... @overload -def func14(x: int, **kwargs: Any) -> str: - ... +def func14(x: int, **kwargs: Any) -> str: ... def func14(*args: Any, **kwargs: Any) -> Any: @@ -213,13 +184,11 @@ def func14(*args: Any, **kwargs: Any) -> Any: # Test 6: non-matching keyword argument (shouldn't generate error) @overload -def func15(cls: str, **kwargs: Any) -> int: - ... +def func15(cls: str, **kwargs: Any) -> int: ... @overload -def func15(**kwargs: Any) -> str: - ... +def func15(**kwargs: Any) -> str: ... def func15(*args: Any, **kwargs: Any) -> Any: @@ -227,27 +196,22 @@ def func15(*args: Any, **kwargs: Any) -> Any: @overload -def func16(var: None) -> list[Any]: - ... +def func16(var: None) -> list[Any]: ... @overload -def func16(var: _T1) -> list[_T1]: - ... +def func16(var: _T1) -> list[_T1]: ... -def func16(var: _T1 | None) -> list[_T1] | list[Any]: - ... +def func16(var: _T1 | None) -> list[_T1] | list[Any]: ... @overload -def func17(a: int, b: list[int]) -> int: - ... +def func17(a: int, b: list[int]) -> int: ... @overload -def func17(a: int, b: list[_T1]) -> _T1: - ... +def func17(a: int, b: list[_T1]) -> _T1: ... def func17(*args: Any, **kwargs: Any) -> Any: @@ -256,94 +220,74 @@ def func17(*args: Any, **kwargs: Any) -> Any: class ClassA(Generic[_T1]): @overload - def __call__(self, f: _T1) -> _T1: - ... + def __call__(self, f: _T1) -> _T1: ... @overload - def __call__(self, f: _T1 | None) -> _T1: - ... + def __call__(self, f: _T1 | None) -> _T1: ... - def __call__(self, f: _T1 | None) -> _T1: - ... + def __call__(self, f: _T1 | None) -> _T1: ... class ClassB: @overload - def __call__(self, f: _T1) -> _T1: - ... + def __call__(self, f: _T1) -> _T1: ... # This should generate an error because the overload is overlapped. @overload - def __call__(self, f: _T1 | None) -> _T1: - ... + def __call__(self, f: _T1 | None) -> _T1: ... - def __call__(self, f: _T1 | None) -> _T1: - ... + def __call__(self, f: _T1 | None) -> _T1: ... class ClassC: @overload - def method1(self, x: type[Any]) -> bool: - ... + def method1(self, x: type[Any]) -> bool: ... @overload - def method1(self, x: Any) -> str | bool: - ... + def method1(self, x: Any) -> str | bool: ... - def method1(self, x: Any) -> Any: - ... + def method1(self, x: Any) -> Any: ... class ClassD: @overload - def method1(self, x: type) -> bool: - ... + def method1(self, x: type) -> bool: ... @overload - def method1(self, x: Any) -> str | bool: - ... + def method1(self, x: Any) -> str | bool: ... - def method1(self, x: Any) -> Any: - ... + def method1(self, x: Any) -> Any: ... @overload -def func18(s: Sequence[_T1], extra: Literal[False]) -> list[_T1]: - ... +def func18(s: Sequence[_T1], extra: Literal[False]) -> list[_T1]: ... @overload -def func18(s: Sequence[_T1], extra: Literal[True]) -> list[_T1] | tuple[_T1]: - ... +def func18(s: Sequence[_T1], extra: Literal[True]) -> list[_T1] | tuple[_T1]: ... @overload -def func18(s: Sequence[_T1], extra: bool) -> list[_T1] | tuple[_T1]: - ... +def func18(s: Sequence[_T1], extra: bool) -> list[_T1] | tuple[_T1]: ... -def func18(s: Sequence[_T1], extra: bool) -> list[_T1] | tuple[_T1]: - ... +def func18(s: Sequence[_T1], extra: bool) -> list[_T1] | tuple[_T1]: ... class DProto1(Protocol): - def __radd__(self, other: Any, /) -> Any: - ... + def __radd__(self, other: Any, /) -> Any: ... class DProto2(Protocol): - def __radd__(self: _T1, other: Any, /) -> _T1: - ... + def __radd__(self: _T1, other: Any, /) -> _T1: ... @overload -def func19(a: Any, b: DProto2) -> DProto2: - ... +def func19(a: Any, b: DProto2) -> DProto2: ... @overload -def func19(a: Any, b: DProto1) -> Any: - ... +def func19(a: Any, b: DProto1) -> Any: ... def func19(a: Any, b: Any) -> Any: @@ -354,28 +298,23 @@ AllStr = bytes | str @overload -def func20(choices: AnyStr) -> AnyStr: - ... +def func20(choices: AnyStr) -> AnyStr: ... @overload -def func20(choices: AllStr) -> AllStr: - ... +def func20(choices: AllStr) -> AllStr: ... -def func20(choices: AllStr) -> AllStr: - ... +def func20(choices: AllStr) -> AllStr: ... # This should generate an overlapping overload error. @overload -def func21(self, p1: int | set[int], /) -> str: - ... +def func21(self, p1: int | set[int], /) -> str: ... @overload -def func21(self, p1: int | list[int], /) -> int: - ... +def func21(self, p1: int | list[int], /) -> int: ... def func21(self, p1: int | set[int] | list[int], /) -> str | int: @@ -383,13 +322,11 @@ def func21(self, p1: int | set[int] | list[int], /) -> str | int: @overload -def func22(self, p1: str | set[int], /) -> str: - ... +def func22(self, p1: str | set[int], /) -> str: ... @overload -def func22(self, p1: int | list[int], /) -> int: - ... +def func22(self, p1: int | list[int], /) -> int: ... def func22(self, p1: str | int | set[int] | list[int], /) -> str | int: diff --git a/packages/pyright-internal/src/tests/samples/overload6.py b/packages/pyright-internal/src/tests/samples/overload6.py index 19242d5ed..dda9dd18e 100644 --- a/packages/pyright-internal/src/tests/samples/overload6.py +++ b/packages/pyright-internal/src/tests/samples/overload6.py @@ -16,25 +16,20 @@ _T = TypeVar("_T") class SupportsRound1(Protocol[_T_co]): @overload - def __round__(self) -> int: - ... + def __round__(self) -> int: ... @overload - def __round__(self, ndigits: int) -> _T_co: - ... + def __round__(self, ndigits: int) -> _T_co: ... # This should generate an error because the return type isn't compatible. - def __round__(self, ndigits: int = 0) -> _T_co: - ... + def __round__(self, ndigits: int = 0) -> _T_co: ... class Proto1: - def __round__(self, ndigits: int) -> "Fraction": - ... + def __round__(self, ndigits: int) -> "Fraction": ... -def round1(number: SupportsRound1[Any]) -> int: - ... +def round1(number: SupportsRound1[Any]) -> int: ... v_proto1 = Proto1() @@ -45,19 +40,15 @@ v_round1 = round1(v_proto1) class Proto2: @overload - def __round__(self, ndigits: int) -> "Fraction": - ... + def __round__(self, ndigits: int) -> "Fraction": ... @overload - def __round__(self, ndigits: None = ...) -> int: - ... + def __round__(self, ndigits: None = ...) -> int: ... - def __round__(self, ndigits: Optional[int] = None) -> "Fraction | int": - ... + def __round__(self, ndigits: Optional[int] = None) -> "Fraction | int": ... -def round2(number: SupportsRound1[Any]) -> int: - ... +def round2(number: SupportsRound1[Any]) -> int: ... v_proto2 = Proto2() diff --git a/packages/pyright-internal/src/tests/samples/overload8.py b/packages/pyright-internal/src/tests/samples/overload8.py index 958e65dd6..41006b031 100644 --- a/packages/pyright-internal/src/tests/samples/overload8.py +++ b/packages/pyright-internal/src/tests/samples/overload8.py @@ -4,33 +4,27 @@ from typing import AnyStr, Literal, TypeVar, overload -class A: - ... +class A: ... -class B: - ... +class B: ... -class C: - ... +class C: ... _T1 = TypeVar("_T1", bound=B) @overload -def overloaded1(x: A) -> str: - ... +def overloaded1(x: A) -> str: ... @overload -def overloaded1(x: _T1) -> _T1: - ... +def overloaded1(x: _T1) -> _T1: ... -def overloaded1(x: A | B) -> str | B: - ... +def overloaded1(x: A | B) -> str | B: ... def func1(a: A | B, b: A | B | C): @@ -46,32 +40,26 @@ LargeUnion = Literal["a", "b", "c", "d", "e", "f", "g", 1, 2, 3, 4, 5, 6, 7, 8] @overload -def overloaded2(a: LargeUnion, b: Literal[2]) -> str: - ... +def overloaded2(a: LargeUnion, b: Literal[2]) -> str: ... @overload -def overloaded2(a: LargeUnion, b: Literal[3]) -> str: - ... +def overloaded2(a: LargeUnion, b: Literal[3]) -> str: ... @overload -def overloaded2(a: LargeUnion, b: Literal[4]) -> float: - ... +def overloaded2(a: LargeUnion, b: Literal[4]) -> float: ... @overload -def overloaded2(a: LargeUnion, b: Literal[9]) -> float: - ... +def overloaded2(a: LargeUnion, b: Literal[9]) -> float: ... @overload -def overloaded2(a: LargeUnion, b: Literal[10]) -> float: - ... +def overloaded2(a: LargeUnion, b: Literal[10]) -> float: ... -def overloaded2(a: LargeUnion, b: LargeUnion | Literal[9, 10]) -> str | float: - ... +def overloaded2(a: LargeUnion, b: LargeUnion | Literal[9, 10]) -> str | float: ... def func2(a: LargeUnion, b: Literal[2, 3, 4], c: Literal[2, 3, 4, 9, 10]): @@ -91,17 +79,14 @@ _T2 = TypeVar("_T2", str, bytes) @overload -def overloaded3(x: str) -> str: - ... +def overloaded3(x: str) -> str: ... @overload -def overloaded3(x: bytes) -> bytes: - ... +def overloaded3(x: bytes) -> bytes: ... -def overloaded3(x: str | bytes) -> str | bytes: - ... +def overloaded3(x: str | bytes) -> str | bytes: ... def func3(y: _T2): @@ -116,17 +101,14 @@ def func5(a: _T3) -> _T3: @overload -def overloaded4(b: str) -> str: - ... +def overloaded4(b: str) -> str: ... @overload -def overloaded4(b: int) -> int: - ... +def overloaded4(b: int) -> int: ... -def overloaded4(b: str | int) -> str | int: - ... +def overloaded4(b: str | int) -> str | int: ... def func6(x: str | int) -> None: @@ -134,13 +116,11 @@ def func6(x: str | int) -> None: @overload -def overloaded5(pattern: AnyStr) -> AnyStr: - ... +def overloaded5(pattern: AnyStr) -> AnyStr: ... @overload -def overloaded5(pattern: int) -> int: - ... +def overloaded5(pattern: int) -> int: ... def overloaded5(pattern: AnyStr | int) -> AnyStr | int: diff --git a/packages/pyright-internal/src/tests/samples/paramInference1.py b/packages/pyright-internal/src/tests/samples/paramInference1.py index 05cf42dc3..0921c960c 100644 --- a/packages/pyright-internal/src/tests/samples/paramInference1.py +++ b/packages/pyright-internal/src/tests/samples/paramInference1.py @@ -3,11 +3,9 @@ class Parent: - def __init__(self, a: int, b: str): - ... + def __init__(self, a: int, b: str): ... - def func1(self, a: int, b: str) -> float: - ... + def func1(self, a: int, b: str) -> float: ... class Child(Parent): diff --git a/packages/pyright-internal/src/tests/samples/paramNames1.py b/packages/pyright-internal/src/tests/samples/paramNames1.py index 0b82b5a58..155884110 100644 --- a/packages/pyright-internal/src/tests/samples/paramNames1.py +++ b/packages/pyright-internal/src/tests/samples/paramNames1.py @@ -37,19 +37,16 @@ class Class1: @overload # This should generate an error or warning if the setting # is enabled because "self" is expected. - def foo6(x: "Class1") -> int: - ... + def foo6(x: "Class1") -> int: ... @overload # This should generate an error or warning if the setting # is enabled because "self" is expected. - def foo6(x: int) -> str: - ... + def foo6(x: int) -> str: ... # This should generate an error or warning if the setting # is enabled because "self" is expected. - def foo6(x) -> int | str: - ... + def foo6(x) -> int | str: ... class Metaclass(type): diff --git a/packages/pyright-internal/src/tests/samples/paramSpec1.py b/packages/pyright-internal/src/tests/samples/paramSpec1.py index 9a3fc0561..f3d58afba 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec1.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec1.py @@ -36,8 +36,7 @@ def func2(x: Callable[P, Any]): class SomeWrapper(Protocol[P]): - def __call__(self, *args: P.args, **kwargs: P.kwargs): - ... + def __call__(self, *args: P.args, **kwargs: P.kwargs): ... # This should generate an error because P cannot be used with other diff --git a/packages/pyright-internal/src/tests/samples/paramSpec13.py b/packages/pyright-internal/src/tests/samples/paramSpec13.py index c62df9a33..eff6ba1f8 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec13.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec13.py @@ -13,12 +13,10 @@ _T = TypeVar("_T") AddIntParam = Callable[Concatenate[int, _P], _T] -def func1(func: Callable[_P, _R]) -> AddIntParam[_P, _R]: - ... +def func1(func: Callable[_P, _R]) -> AddIntParam[_P, _R]: ... -def func2(a: str, b: list[int]) -> str: - ... +def func2(a: str, b: list[int]) -> str: ... v1 = func1(func2) @@ -29,19 +27,15 @@ reveal_type(v1, expected_text="(int, a: str, b: list[int]) -> str") X = AddIntParam[int, int] -class RemoteResponse(Generic[_T]): - ... +class RemoteResponse(Generic[_T]): ... class RemoteFunction(Generic[_P, _R]): - def __init__(self, func: Callable[_P, _R]) -> None: - ... + def __init__(self, func: Callable[_P, _R]) -> None: ... - def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: - ... + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... - def remote(self, *args: _P.args, **kwargs: _P.kwargs) -> RemoteResponse[_R]: - ... + def remote(self, *args: _P.args, **kwargs: _P.kwargs) -> RemoteResponse[_R]: ... r1 = RemoteFunction(func2) @@ -67,8 +61,7 @@ r1.remote(1, []) A = RemoteFunction[int, int] -def remote(func: Callable[_P, _R]) -> RemoteFunction[_P, _R]: - ... +def remote(func: Callable[_P, _R]) -> RemoteFunction[_P, _R]: ... v4 = remote(func2) @@ -79,8 +72,7 @@ Coro = Coroutine[Any, Any, _T] CoroFunc = Callable[_P, Coro[_T]] -class ClassA: - ... +class ClassA: ... CheckFunc = CoroFunc[Concatenate[ClassA, _P], bool] diff --git a/packages/pyright-internal/src/tests/samples/paramSpec16.py b/packages/pyright-internal/src/tests/samples/paramSpec16.py index f3b294eb2..3a11a6ce9 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec16.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec16.py @@ -18,7 +18,7 @@ class ClassA(Generic[P, T, Q, U]): ... def decorator1( - func: Callable[Concatenate[Callable[P, T], Q], U] + func: Callable[Concatenate[Callable[P, T], Q], U], ) -> ClassA[P, T, Q, U]: ... diff --git a/packages/pyright-internal/src/tests/samples/paramSpec18.py b/packages/pyright-internal/src/tests/samples/paramSpec18.py index a59bf7477..c545efd77 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec18.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec18.py @@ -6,15 +6,13 @@ from typing import Callable, Concatenate, ParamSpec, Protocol P = ParamSpec("P") -def callback(a: int, b: str, c: str) -> int: - ... +def callback(a: int, b: str, c: str) -> int: ... CallableWithConcatenate = Callable[Concatenate[int, P], int] -def func_with_callable(cb: CallableWithConcatenate[P]) -> Callable[P, bool]: - ... +def func_with_callable(cb: CallableWithConcatenate[P]) -> Callable[P, bool]: ... x1 = func_with_callable(callback) @@ -22,12 +20,10 @@ reveal_type(x1, expected_text="(b: str, c: str) -> bool") class ClassWithConcatenate(Protocol[P]): - def __call__(self, x: int, /, *args: P.args, **kwargs: P.kwargs) -> int: - ... + def __call__(self, x: int, /, *args: P.args, **kwargs: P.kwargs) -> int: ... -def func_with_protocol(cb: ClassWithConcatenate[P]) -> Callable[P, bool]: - ... +def func_with_protocol(cb: ClassWithConcatenate[P]) -> Callable[P, bool]: ... x2 = func_with_protocol(callback) @@ -35,8 +31,7 @@ reveal_type(x2, expected_text="(b: str, c: str) -> bool") class CallbackPos(Protocol[P]): - def __call__(self, /, *args: P.args, **kwargs: P.kwargs) -> None: - ... + def __call__(self, /, *args: P.args, **kwargs: P.kwargs) -> None: ... def invoke_pos(cb: CallbackPos[P], /, *args: P.args, **kwargs: P.kwargs) -> None: diff --git a/packages/pyright-internal/src/tests/samples/paramSpec20.py b/packages/pyright-internal/src/tests/samples/paramSpec20.py index 707710640..a68340f20 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec20.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec20.py @@ -14,43 +14,34 @@ class X(Generic[T, P1]): x: T -def x1(x: X[int, P2]) -> str: - ... +def x1(x: X[int, P2]) -> str: ... -def x2(x: X[int, Concatenate[int, P2]]) -> str: - ... +def x2(x: X[int, Concatenate[int, P2]]) -> str: ... -def X3(x: X[int, [int, bool]]) -> str: - ... +def X3(x: X[int, [int, bool]]) -> str: ... -def x4(x: X[int, ...]) -> str: - ... +def x4(x: X[int, ...]) -> str: ... # This should generate an error because "int" can't be bound to a ParamSpec. -def x5(x: X[int, int]) -> str: - ... +def x5(x: X[int, int]) -> str: ... # This should generate an error. -def x6(x: X[..., ...]) -> str: - ... +def x6(x: X[..., ...]) -> str: ... # This should generate an error. -def x7(x: X[[int], [int, int]]) -> str: - ... +def x7(x: X[[int], [int, int]]) -> str: ... class Y(Generic[P2]): - def __init__(self, cb: Callable[P2, Any]) -> None: - ... + def __init__(self, cb: Callable[P2, Any]) -> None: ... - def m1(self) -> X[int, Concatenate[float, P2]]: - ... + def m1(self) -> X[int, Concatenate[float, P2]]: ... y1 = Y(x4) @@ -64,24 +55,19 @@ class Z(Generic[P1]): f: Callable[P1, int] -def z1(x: Z[[int, str, bool]]) -> str: - ... +def z1(x: Z[[int, str, bool]]) -> str: ... -def z2(x: Z[int, str, bool]) -> str: - ... +def z2(x: Z[int, str, bool]) -> str: ... # This should generate an error. -def z3(x: Z[[int, [str], bool]]) -> str: - ... +def z3(x: Z[[int, [str], bool]]) -> str: ... # This should generate an error. -def z4(x: Z[[[int, str, bool]]]) -> str: - ... +def z4(x: Z[[[int, str, bool]]]) -> str: ... # This should generate an error. -def z5(x: Z[[...]]) -> str: - ... +def z5(x: Z[[...]]) -> str: ... diff --git a/packages/pyright-internal/src/tests/samples/paramSpec25.py b/packages/pyright-internal/src/tests/samples/paramSpec25.py index 6503a3de5..4d4bc4b57 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec25.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec25.py @@ -6,24 +6,20 @@ from typing import Any, Callable, Concatenate, Generic, ParamSpec P = ParamSpec("P") -class Context: - ... +class Context: ... CommandHandler = Callable[Concatenate[Context, P], Any] class Command(Generic[P]): - def __init__(self, handler: CommandHandler[P]) -> None: - ... + def __init__(self, handler: CommandHandler[P]) -> None: ... -def handler_no_args(ctx: Context) -> None: - ... +def handler_no_args(ctx: Context) -> None: ... -def handler_one_arg(ctx: Context, a: int) -> None: - ... +def handler_one_arg(ctx: Context, a: int) -> None: ... cmd_no_args = Command(handler_no_args) diff --git a/packages/pyright-internal/src/tests/samples/paramSpec26.py b/packages/pyright-internal/src/tests/samples/paramSpec26.py index d45526006..4879253be 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec26.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec26.py @@ -7,16 +7,13 @@ P = ParamSpec("P") class A(Generic[P]): - def __init__(self, func: Callable[P, Any]) -> None: - ... + def __init__(self, func: Callable[P, Any]) -> None: ... -def func1(a: A[Concatenate[int, P]]) -> A[P]: - ... +def func1(a: A[Concatenate[int, P]]) -> A[P]: ... -def func2(a: int, b: str) -> str: - ... +def func2(a: int, b: str) -> str: ... val1 = A(func2) diff --git a/packages/pyright-internal/src/tests/samples/paramSpec28.py b/packages/pyright-internal/src/tests/samples/paramSpec28.py index df028737a..f13fed80a 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec28.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec28.py @@ -12,27 +12,24 @@ _Self = TypeVar("_Self", bound="_GenerativeType") def decorator( - target: Callable[Concatenate[_Fn, _Args], _Ret] -) -> Callable[[_Fn], Callable[_Args, _Ret]]: - ... + target: Callable[Concatenate[_Fn, _Args], _Ret], +) -> Callable[[_Fn], Callable[_Args, _Ret]]: ... class _GenerativeType(Protocol): - def _generate(self: "_Self") -> "_Self": - ... + def _generate(self: "_Self") -> "_Self": ... def generative( - fn: Callable[Concatenate[_Self, _Args], None] + fn: Callable[Concatenate[_Self, _Args], None], ) -> Callable[Concatenate[_Self, _Args], _Self]: @decorator def _generative( fn: Callable[Concatenate[_Self, _Args], None], self: _Self, *args: _Args.args, - **kw: _Args.kwargs - ) -> _Self: - ... + **kw: _Args.kwargs, + ) -> _Self: ... decorated = _generative(fn) diff --git a/packages/pyright-internal/src/tests/samples/paramSpec30.py b/packages/pyright-internal/src/tests/samples/paramSpec30.py index caf3c65e7..7b24bbc53 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec30.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec30.py @@ -37,7 +37,7 @@ def error_decorator( """Filter specific errors and raise custom exception for remaining once.""" def decorator( - func: Callable[Concatenate[_T, _P], _R] + func: Callable[Concatenate[_T, _P], _R], ) -> Callable[Concatenate[_T, _P], _R | None]: def wrapper(self: _T, *args: _P.args, **kwargs: _P.kwargs) -> _R | None: try: diff --git a/packages/pyright-internal/src/tests/samples/paramSpec33.py b/packages/pyright-internal/src/tests/samples/paramSpec33.py index 692d884bb..83158975a 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec33.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec33.py @@ -18,7 +18,7 @@ def func1(func: Callable[P, int]) -> Callable[P, int]: def func2( - func: Callable[Concatenate[int, P], int] + func: Callable[Concatenate[int, P], int], ) -> Callable[Concatenate[int, P], int]: def inner_func(x: int) -> int: # This should generate a type error. diff --git a/packages/pyright-internal/src/tests/samples/paramSpec35.py b/packages/pyright-internal/src/tests/samples/paramSpec35.py index 51866cf7f..99cd7c8d4 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec35.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec35.py @@ -6,16 +6,13 @@ from typing import Callable, ParamSpec P = ParamSpec("P") -def func1(x: Callable[P, int], y: Callable[P, int]) -> Callable[P, bool]: - ... +def func1(x: Callable[P, int], y: Callable[P, int]) -> Callable[P, bool]: ... -def a1(p0: int) -> int: - ... +def a1(p0: int) -> int: ... -def a2(p0: int, p2: str) -> int: - ... +def a2(p0: int, p2: str) -> int: ... v1 = func1(a1, a1) diff --git a/packages/pyright-internal/src/tests/samples/paramSpec36.py b/packages/pyright-internal/src/tests/samples/paramSpec36.py index 5887e3229..ab4e625ce 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec36.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec36.py @@ -12,8 +12,7 @@ R = TypeVar("R") class TakesFunctionWithArguments(Protocol): def __call__( self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs - ) -> Future[R]: - ... + ) -> Future[R]: ... @contextlib.contextmanager diff --git a/packages/pyright-internal/src/tests/samples/paramSpec37.py b/packages/pyright-internal/src/tests/samples/paramSpec37.py index 269d04dd3..ebb16e7fa 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec37.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec37.py @@ -9,8 +9,7 @@ T = TypeVar("T") class ClassA(Protocol[R]): - def __call__(self, n: int, /, *args: Any, **kwargs: Any) -> list[R]: - ... + def __call__(self, n: int, /, *args: Any, **kwargs: Any) -> list[R]: ... def noop(v: T) -> T: diff --git a/packages/pyright-internal/src/tests/samples/paramSpec38.py b/packages/pyright-internal/src/tests/samples/paramSpec38.py index 68f97f502..135f2fc16 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec38.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec38.py @@ -16,8 +16,7 @@ class ClassA(Generic[P, R]): return self.callback(*args, **kwargs) -def func1(obj: object, **kwargs: object) -> object: - ... +def func1(obj: object, **kwargs: object) -> object: ... reveal_type( diff --git a/packages/pyright-internal/src/tests/samples/paramSpec4.py b/packages/pyright-internal/src/tests/samples/paramSpec4.py index 7a318def4..0e9d56790 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec4.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec4.py @@ -16,8 +16,7 @@ P = ParamSpec("P") R = TypeVar("R") -class Request: - ... +class Request: ... def with_request(f: Callable[Concatenate[Request, P], R]) -> Callable[P, R]: @@ -46,43 +45,35 @@ takes_int_str(1, "A", 2) # This should generate an error because a ParamSpec can appear # only within the last type arg for Concatenate -def decorator1(f: Callable[Concatenate[P, P], int]) -> Callable[P, int]: - ... +def decorator1(f: Callable[Concatenate[P, P], int]) -> Callable[P, int]: ... # This should generate an error because the last type arg # for Concatenate should be a ParamSpec. -def decorator2(f: Callable[Concatenate[int, int], int]) -> Callable[P, int]: - ... +def decorator2(f: Callable[Concatenate[int, int], int]) -> Callable[P, int]: ... # This should generate an error because Concatenate is missing # its type arguments. -def decorator3(f: Callable[Concatenate, int]) -> Callable[P, int]: - ... +def decorator3(f: Callable[Concatenate, int]) -> Callable[P, int]: ... def decorator4(func: Callable[P, None]) -> Callable[Concatenate[int, P], None]: - def wrapper(x: int, /, *args: P.args, **kwargs: P.kwargs) -> None: - ... + def wrapper(x: int, /, *args: P.args, **kwargs: P.kwargs) -> None: ... return wrapper -def func1(func: Callable[Concatenate[int, P], None]) -> Callable[P, None]: - ... +def func1(func: Callable[Concatenate[int, P], None]) -> Callable[P, None]: ... -def func2(a: int, b: str, c: str) -> None: - ... +def func2(a: int, b: str, c: str) -> None: ... -def func3(a: int, /, b: str, c: str) -> None: - ... +def func3(a: int, /, b: str, c: str) -> None: ... -def func4(a: int, b: str, /, c: str) -> None: - ... +def func4(a: int, b: str, /, c: str) -> None: ... v1 = func1(func2) @@ -95,12 +86,10 @@ v3 = func1(func4) reveal_type(v3, expected_text="(b: str, /, c: str) -> None") -def func5(__fn: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: - ... +def func5(__fn: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: ... -def func6(name: str, *args: str): - ... +def func6(name: str, *args: str): ... v5 = func5(func6, "a", "b", "c") @@ -109,8 +98,7 @@ v5 = func5(func6, "a", "b", "c") v6 = func5(func6, "a", "b", "c", 1) -def func7(name: str, **kwargs: str): - ... +def func7(name: str, **kwargs: str): ... v7 = func5(func7, "a", b="b", c="c") @@ -124,8 +112,7 @@ X = TypeVar("X") class DecoProto(Protocol[P, T]): - def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: - ... + def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T: ... def func8(cb: Callable[Concatenate[X, P], T]) -> DecoProto[Concatenate[X, P], T]: @@ -150,8 +137,7 @@ class A(Generic[R, P]): self.prop = prop -def func10(q: int, /) -> str: - ... +def func10(q: int, /) -> str: ... y1 = A(func10, 1) diff --git a/packages/pyright-internal/src/tests/samples/paramSpec40.py b/packages/pyright-internal/src/tests/samples/paramSpec40.py index 6ee738cad..678b379bd 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec40.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec40.py @@ -34,8 +34,7 @@ class TD1(TypedDict, total=False): def func3( a: int, b: int, /, *, c: str = ..., d: str = ..., **kwargs: Unpack[TD1] -) -> float: - ... +) -> float: ... call(func3, 1, 2, e="", c="") diff --git a/packages/pyright-internal/src/tests/samples/paramSpec42.py b/packages/pyright-internal/src/tests/samples/paramSpec42.py index d17aa0fcc..c987b7fb5 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec42.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec42.py @@ -14,8 +14,7 @@ P = ParamSpec("P") R = TypeVar("R") -def func1(a: S, b: T) -> dict[S, T]: - ... +def func1(a: S, b: T) -> dict[S, T]: ... class DecoratorClass1(Generic[P, R]): @@ -25,8 +24,7 @@ class DecoratorClass1(Generic[P, R]): def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: return self._func(*args, **kwargs) - def other(self, val: int, *args: P.args, **kwargs: P.kwargs) -> R: - ... + def other(self, val: int, *args: P.args, **kwargs: P.kwargs) -> R: ... decorated_func1 = DecoratorClass1(func1) @@ -44,8 +42,7 @@ func1_other_ret = decorated_func1.other(0, 1, "") reveal_type(func1_other_ret, expected_text="dict[int, str]") -def func2(func: Callable[P, R]) -> Callable[P, R]: - ... +def func2(func: Callable[P, R]) -> Callable[P, R]: ... d1 = func2(func1) diff --git a/packages/pyright-internal/src/tests/samples/paramSpec43.py b/packages/pyright-internal/src/tests/samples/paramSpec43.py index 001c59add..879237770 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec43.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec43.py @@ -8,8 +8,7 @@ R = TypeVar("R") class Decorator(Protocol): - def __call__(self, __x: Callable[P, R]) -> Callable[P, R]: - ... + def __call__(self, __x: Callable[P, R]) -> Callable[P, R]: ... def func1(deco: Decorator): diff --git a/packages/pyright-internal/src/tests/samples/paramSpec44.py b/packages/pyright-internal/src/tests/samples/paramSpec44.py index c920761bb..237364ab8 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec44.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec44.py @@ -8,16 +8,13 @@ R = TypeVar("R") @overload -def func1(f: Callable[P, R]) -> Callable[P, R]: - ... +def func1(f: Callable[P, R]) -> Callable[P, R]: ... @overload -def func1() -> Callable[[Callable[P, R]], Callable[P, R]]: - ... +def func1() -> Callable[[Callable[P, R]], Callable[P, R]]: ... def func1( - f: Callable[P, R] | None = None -) -> Callable[P, R] | Callable[[Callable[P, R]], Callable[P, R]]: - ... + f: Callable[P, R] | None = None, +) -> Callable[P, R] | Callable[[Callable[P, R]], Callable[P, R]]: ... diff --git a/packages/pyright-internal/src/tests/samples/paramSpec45.py b/packages/pyright-internal/src/tests/samples/paramSpec45.py index ca1923535..33fab200b 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec45.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec45.py @@ -6,16 +6,13 @@ from typing import Callable, ParamSpec P = ParamSpec("P") -def func1(func: Callable[P, object], *args: P.args, **kwargs: P.kwargs) -> object: - ... +def func1(func: Callable[P, object], *args: P.args, **kwargs: P.kwargs) -> object: ... -def func2(x: str) -> int: - ... +def func2(x: str) -> int: ... -def func3(y: str) -> int: - ... +def func3(y: str) -> int: ... print(func1(func2, x="..."), func1(func3, y="...")) diff --git a/packages/pyright-internal/src/tests/samples/paramSpec46.py b/packages/pyright-internal/src/tests/samples/paramSpec46.py index 88b713e5b..ff68dd7f0 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec46.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec46.py @@ -5,32 +5,27 @@ from typing import Callable, Concatenate TA1 = Callable[Concatenate[int, ...], None] -def func1(cb: Callable[Concatenate[int, str, ...], None]): - ... +def func1(cb: Callable[Concatenate[int, str, ...], None]): ... -def func2(cb: TA1): - ... +def func2(cb: TA1): ... -def cb1(x: int, y: str, z: str) -> None: - ... +def cb1(x: int, y: str, z: str) -> None: ... func1(cb1) func2(cb1) -def cb2(x: int, y: str, *args: int, **kwargs: str) -> None: - ... +def cb2(x: int, y: str, *args: int, **kwargs: str) -> None: ... func1(cb2) func2(cb2) -def cb3(x: str, y: str) -> None: - ... +def cb3(x: str, y: str) -> None: ... # This should generate an error. diff --git a/packages/pyright-internal/src/tests/samples/paramSpec47.py b/packages/pyright-internal/src/tests/samples/paramSpec47.py index fa74a1f0d..b19448b7c 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec47.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec47.py @@ -6,8 +6,7 @@ from typing import Any, Callable, ParamSpec P = ParamSpec("P") -def func1(f: Callable[P, Any], *args: P.args, **kwargs: P.kwargs) -> str: - ... +def func1(f: Callable[P, Any], *args: P.args, **kwargs: P.kwargs) -> str: ... def func2(a: int) -> int: diff --git a/packages/pyright-internal/src/tests/samples/paramSpec5.py b/packages/pyright-internal/src/tests/samples/paramSpec5.py index 830fd1c0a..60ce2ea6f 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec5.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec5.py @@ -13,16 +13,14 @@ def decorator(fn: Callable[P, R]) -> Callable[P, R]: return fn -def func1(*, value: str) -> None: - ... +def func1(*, value: str) -> None: ... f1 = decorator(func1) reveal_type(f1, expected_text="(*, value: str) -> None") -def func2(value: str, /) -> None: - ... +def func2(value: str, /) -> None: ... f2 = decorator(func2) diff --git a/packages/pyright-internal/src/tests/samples/paramSpec50.py b/packages/pyright-internal/src/tests/samples/paramSpec50.py index 02d06fe14..5ae51b276 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec50.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec50.py @@ -6,8 +6,7 @@ P = ParamSpec("P") T = TypeVar("T") -def deco1(func: Callable[P, Iterator[T]]) -> Callable[P, Iterator[T]]: - ... +def deco1(func: Callable[P, Iterator[T]]) -> Callable[P, Iterator[T]]: ... @deco1 @@ -15,16 +14,13 @@ def func1( func: Callable[P, str], *func_args: P.args, **func_kwargs: P.kwargs, -) -> Iterator[str]: - ... +) -> Iterator[str]: ... -def func2(a: int, b: float) -> str: - ... +def func2(a: int, b: float) -> str: ... -def func3(a: int) -> str: - ... +def func3(a: int) -> str: ... func1(func2, 3, 1.1) diff --git a/packages/pyright-internal/src/tests/samples/paramSpec6.py b/packages/pyright-internal/src/tests/samples/paramSpec6.py index 988b78d45..ccb262ccf 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec6.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec6.py @@ -6,12 +6,10 @@ P = ParamSpec("P") R = TypeVar("R") -def func1(fn: Callable[P, R]) -> Callable[P, R]: - ... +def func1(fn: Callable[P, R]) -> Callable[P, R]: ... -def func2(a: str, b: str = "") -> str: - ... +def func2(a: str, b: str = "") -> str: ... func1(func2)("") diff --git a/packages/pyright-internal/src/tests/samples/paramSpec7.py b/packages/pyright-internal/src/tests/samples/paramSpec7.py index d1ea1bfa3..2218a1700 100644 --- a/packages/pyright-internal/src/tests/samples/paramSpec7.py +++ b/packages/pyright-internal/src/tests/samples/paramSpec7.py @@ -7,13 +7,11 @@ P = ParamSpec("P") R = TypeVar("R") -def func1(f: Callable[P, R]) -> Callable[P, R]: - ... +def func1(f: Callable[P, R]) -> Callable[P, R]: ... class ClassA(Generic[R]): - def method1(self, v: R) -> None: - ... + def method1(self, v: R) -> None: ... v1: ClassA[int] = ClassA() diff --git a/packages/pyright-internal/src/tests/samples/paramType1.py b/packages/pyright-internal/src/tests/samples/paramType1.py index 725344a0e..7e7c5d8fe 100644 --- a/packages/pyright-internal/src/tests/samples/paramType1.py +++ b/packages/pyright-internal/src/tests/samples/paramType1.py @@ -13,61 +13,47 @@ _TChild1 = TypeVar("_TChild1", bound="Child1") class Child1: - def m1(self: "Child1"): - ... + def m1(self: "Child1"): ... # This should generate an error. - def m2(self: Parent): - ... + def m2(self: Parent): ... # This should generate an error. - def m3(self: type["Child1"]): - ... + def m3(self: type["Child1"]): ... - def m4(self: _TChild1) -> _TChild1: - ... + def m4(self: _TChild1) -> _TChild1: ... # This should generate an error. - def m5(self: type[_TChild1]) -> _TChild1: - ... + def m5(self: type[_TChild1]) -> _TChild1: ... - def m6(self: _T) -> _T: - ... + def m6(self: _T) -> _T: ... # This should generate an error. - def __new__(cls: "Child1"): - ... + def __new__(cls: "Child1"): ... @classmethod - def cm1(cls: type["Child1"]): - ... + def cm1(cls: type["Child1"]): ... # This should generate an error. @classmethod # This should generate an error. - def cm2(cls: "Child1"): - ... + def cm2(cls: "Child1"): ... @classmethod # This should generate an error. - def cm3(cls: type[Parent]): - ... + def cm3(cls: type[Parent]): ... @classmethod - def cm4(cls: type[_TChild1]) -> _TChild1: - ... + def cm4(cls: type[_TChild1]) -> _TChild1: ... # This should generate an error. @classmethod # This should generate an error. - def cm5(cls: _TChild1) -> _TChild1: - ... + def cm5(cls: _TChild1) -> _TChild1: ... @classmethod - def cm6(cls: type[_T]) -> _T: - ... + def cm6(cls: type[_T]) -> _T: ... class MyMeta(type): - def m1(self: type[_T]) -> Iterator[_T]: - ... + def m1(self: type[_T]) -> Iterator[_T]: ... diff --git a/packages/pyright-internal/src/tests/samples/parameters1.py b/packages/pyright-internal/src/tests/samples/parameters1.py index 9048d8f2a..fabe4ee98 100644 --- a/packages/pyright-internal/src/tests/samples/parameters1.py +++ b/packages/pyright-internal/src/tests/samples/parameters1.py @@ -4,13 +4,11 @@ class A: # This should generate an error if reportMissingParameterType is enabled # because 'y' is missing a type annotation. - def method1(self, x: int, _, y) -> int: - ... + def method1(self, x: int, _, y) -> int: ... def method2(self, x, y): # type: (int, int) -> int ... -def g(__p: int, x: int, y: str): - ... +def g(__p: int, x: int, y: str): ... diff --git a/packages/pyright-internal/src/tests/samples/partial1.py b/packages/pyright-internal/src/tests/samples/partial1.py index c62f951df..558c19070 100644 --- a/packages/pyright-internal/src/tests/samples/partial1.py +++ b/packages/pyright-internal/src/tests/samples/partial1.py @@ -165,12 +165,10 @@ p8_1(3, "", foo=4, bar=5) class Partial(Protocol[_T2]): - def __new__(cls, __func: Callable[..., _T2]) -> Self: - ... + def __new__(cls, __func: Callable[..., _T2]) -> Self: ... -def func9() -> int: - ... +def func9() -> int: ... # This should generate an error. diff --git a/packages/pyright-internal/src/tests/samples/partial2.py b/packages/pyright-internal/src/tests/samples/partial2.py index efab0f675..c48453c9e 100644 --- a/packages/pyright-internal/src/tests/samples/partial2.py +++ b/packages/pyright-internal/src/tests/samples/partial2.py @@ -9,8 +9,7 @@ def func1(a: int, b: int, x: str) -> str: class Proto1(Protocol): - def __call__(self, x: str) -> str: - ... + def __call__(self, x: str) -> str: ... func2: Proto1 = partial(func1, 3, 4, x="a") @@ -19,8 +18,7 @@ func2(x="b") class Proto2(Protocol): - def __call__(self, b: int) -> str: - ... + def __call__(self, b: int) -> str: ... func3: Proto2 = partial(func1, 3, b=3, x="a") diff --git a/packages/pyright-internal/src/tests/samples/partial4.py b/packages/pyright-internal/src/tests/samples/partial4.py index 22c093500..f5bbafba4 100644 --- a/packages/pyright-internal/src/tests/samples/partial4.py +++ b/packages/pyright-internal/src/tests/samples/partial4.py @@ -6,13 +6,11 @@ from typing import overload @overload -def func1(val1: float, val2: float) -> float: - ... +def func1(val1: float, val2: float) -> float: ... @overload -def func1(val1: str, val2: str) -> str: - ... +def func1(val1: str, val2: str) -> str: ... def func1(val1: float | str, val2: float | str) -> float | str: diff --git a/packages/pyright-internal/src/tests/samples/partial5.py b/packages/pyright-internal/src/tests/samples/partial5.py index 9a6cd9226..960193eed 100644 --- a/packages/pyright-internal/src/tests/samples/partial5.py +++ b/packages/pyright-internal/src/tests/samples/partial5.py @@ -7,8 +7,7 @@ from typing import Self, TypeVar class A: - def __init__(self, x: int, y: int) -> None: - ... + def __init__(self, x: int, y: int) -> None: ... # This should generate an error because "y" has the wrong type. diff --git a/packages/pyright-internal/src/tests/samples/property1.py b/packages/pyright-internal/src/tests/samples/property1.py index ce2a68319..13f35c3d6 100644 --- a/packages/pyright-internal/src/tests/samples/property1.py +++ b/packages/pyright-internal/src/tests/samples/property1.py @@ -82,8 +82,7 @@ p3: property = ClassA.deletable_prop class ClassC: @property - def prop1(self) -> type[Self]: - ... + def prop1(self) -> type[Self]: ... def method1(self) -> None: reveal_type(self.prop1, expected_text="type[Self@ClassC]") diff --git a/packages/pyright-internal/src/tests/samples/property11.py b/packages/pyright-internal/src/tests/samples/property11.py index d8f3cffe8..f29b2c467 100644 --- a/packages/pyright-internal/src/tests/samples/property11.py +++ b/packages/pyright-internal/src/tests/samples/property11.py @@ -36,8 +36,7 @@ class Class2: return cls -class Class3(Class2): - ... +class Class3(Class2): ... reveal_type(Class2.prop1, expected_text="type[Class2]") diff --git a/packages/pyright-internal/src/tests/samples/property13.py b/packages/pyright-internal/src/tests/samples/property13.py index 06fcc0bf6..8595d3478 100644 --- a/packages/pyright-internal/src/tests/samples/property13.py +++ b/packages/pyright-internal/src/tests/samples/property13.py @@ -8,8 +8,7 @@ class MyMeta(type): class Base(metaclass=MyMeta): - def __new__(cls, arg) -> "Base": - ... + def __new__(cls, arg) -> "Base": ... reveal_type(Base.something, expected_text="Base") diff --git a/packages/pyright-internal/src/tests/samples/property16.py b/packages/pyright-internal/src/tests/samples/property16.py index 9d9b17b06..045735c41 100644 --- a/packages/pyright-internal/src/tests/samples/property16.py +++ b/packages/pyright-internal/src/tests/samples/property16.py @@ -11,22 +11,18 @@ T = TypeVar("T") class Parent(Generic[T]): @property - def prop1(self) -> T: - ... + def prop1(self) -> T: ... @property - def prop2(self) -> Self: - ... + def prop2(self) -> Self: ... class Child(Parent[str]): @Parent.prop1.setter - def prop1(self, value: str) -> None: - ... + def prop1(self, value: str) -> None: ... @Parent.prop2.setter - def prop2(self, value: str) -> None: - ... + def prop2(self, value: str) -> None: ... parent = Parent[int]() diff --git a/packages/pyright-internal/src/tests/samples/property18.py b/packages/pyright-internal/src/tests/samples/property18.py index ba5f60e95..bb091de8c 100644 --- a/packages/pyright-internal/src/tests/samples/property18.py +++ b/packages/pyright-internal/src/tests/samples/property18.py @@ -27,7 +27,7 @@ class HasAttr(Protocol): def decorate( - func: Callable[Concatenate[S, P], R] + func: Callable[Concatenate[S, P], R], ) -> Callable[Concatenate[S, P], R]: ... diff --git a/packages/pyright-internal/src/tests/samples/property4.py b/packages/pyright-internal/src/tests/samples/property4.py index 723de1440..338eb9ed1 100644 --- a/packages/pyright-internal/src/tests/samples/property4.py +++ b/packages/pyright-internal/src/tests/samples/property4.py @@ -9,8 +9,7 @@ _P = TypeVar("_P", bound=str) class ClassA(str): @property - def parent(self: _P) -> _P: - ... + def parent(self: _P) -> _P: ... p = ClassA().parent diff --git a/packages/pyright-internal/src/tests/samples/protocol10.py b/packages/pyright-internal/src/tests/samples/protocol10.py index fde218750..c0b706574 100644 --- a/packages/pyright-internal/src/tests/samples/protocol10.py +++ b/packages/pyright-internal/src/tests/samples/protocol10.py @@ -5,16 +5,13 @@ from typing import Protocol class ProtocolBase(Protocol): - def a(self) -> None: - ... + def a(self) -> None: ... - def b(self) -> None: - ... + def b(self) -> None: ... class ProtocolExtended(ProtocolBase, Protocol): - def c(self) -> None: - ... + def c(self) -> None: ... class Base: diff --git a/packages/pyright-internal/src/tests/samples/protocol11.py b/packages/pyright-internal/src/tests/samples/protocol11.py index d6e63e3c5..d81d72818 100644 --- a/packages/pyright-internal/src/tests/samples/protocol11.py +++ b/packages/pyright-internal/src/tests/samples/protocol11.py @@ -14,8 +14,7 @@ _TBase1 = TypeVar("_TBase1", bound=Base) _TBase2 = TypeVar("_TBase2", bound=Base) -def my_next(__i: Iterator[_T1]) -> _T1: - ... +def my_next(__i: Iterator[_T1]) -> _T1: ... class SourceProvider(Generic[_TBase1]): diff --git a/packages/pyright-internal/src/tests/samples/protocol13.py b/packages/pyright-internal/src/tests/samples/protocol13.py index 3d2aabfcd..482919153 100644 --- a/packages/pyright-internal/src/tests/samples/protocol13.py +++ b/packages/pyright-internal/src/tests/samples/protocol13.py @@ -6,13 +6,11 @@ from typing import Protocol class CollectionProtocol(Protocol): - def watch(self, *, max_time: int | None = ..., key: str | None = ...) -> None: - ... + def watch(self, *, max_time: int | None = ..., key: str | None = ...) -> None: ... class Collection: - def watch(self, key: str | None = None, max_time: int | None = None) -> None: - ... + def watch(self, key: str | None = None, max_time: int | None = None) -> None: ... # This should not generate an error even though the "keys" and diff --git a/packages/pyright-internal/src/tests/samples/protocol14.py b/packages/pyright-internal/src/tests/samples/protocol14.py index 8a2af5d0b..6ce135e18 100644 --- a/packages/pyright-internal/src/tests/samples/protocol14.py +++ b/packages/pyright-internal/src/tests/samples/protocol14.py @@ -7,8 +7,7 @@ T = TypeVar("T") class HasParent(Protocol): - def get_parent(self: T) -> T: - ... + def get_parent(self: T) -> T: ... GenericNode = TypeVar("GenericNode", bound=HasParent) diff --git a/packages/pyright-internal/src/tests/samples/protocol15.py b/packages/pyright-internal/src/tests/samples/protocol15.py index 0534227de..5a2e5d73b 100644 --- a/packages/pyright-internal/src/tests/samples/protocol15.py +++ b/packages/pyright-internal/src/tests/samples/protocol15.py @@ -8,11 +8,9 @@ T = TypeVar("T") class Proto(Protocol): @property - def f(self: T) -> T: - ... + def f(self: T) -> T: ... - def m(self, item: T, callback: Callable[[T], str]) -> str: - ... + def m(self, item: T, callback: Callable[[T], str]) -> str: ... class Concrete: @@ -20,8 +18,7 @@ class Concrete: def f(self: T) -> T: return self - def m(self, item: T, callback: Callable[[T], str]) -> str: - ... + def m(self, item: T, callback: Callable[[T], str]) -> str: ... x: Proto = Concrete() diff --git a/packages/pyright-internal/src/tests/samples/protocol16.py b/packages/pyright-internal/src/tests/samples/protocol16.py index 460c61dfe..69b8dd201 100644 --- a/packages/pyright-internal/src/tests/samples/protocol16.py +++ b/packages/pyright-internal/src/tests/samples/protocol16.py @@ -4,17 +4,14 @@ from typing import Any, Protocol class Session(Protocol): - def execute(self, statement: Any, *args: Any, **kwargs: Any) -> None: - ... + def execute(self, statement: Any, *args: Any, **kwargs: Any) -> None: ... class CoolSession(Protocol): - def execute(self, stmt: Any, *args: Any, **kwargs: Any) -> None: - ... + def execute(self, stmt: Any, *args: Any, **kwargs: Any) -> None: ... -def func1(arg: Session) -> None: - ... +def func1(arg: Session) -> None: ... def func2(x: CoolSession): diff --git a/packages/pyright-internal/src/tests/samples/protocol18.py b/packages/pyright-internal/src/tests/samples/protocol18.py index 36952fd07..03ceeb506 100644 --- a/packages/pyright-internal/src/tests/samples/protocol18.py +++ b/packages/pyright-internal/src/tests/samples/protocol18.py @@ -4,23 +4,20 @@ from typing import Protocol -class A(Protocol): - ... +class A(Protocol): ... # This should generate an error. A() -class B(A): - ... +class B(A): ... B() -class C(A, Protocol): - ... +class C(A, Protocol): ... # This should generate an error. diff --git a/packages/pyright-internal/src/tests/samples/protocol19.py b/packages/pyright-internal/src/tests/samples/protocol19.py index a08e5deb0..6dccd28d4 100644 --- a/packages/pyright-internal/src/tests/samples/protocol19.py +++ b/packages/pyright-internal/src/tests/samples/protocol19.py @@ -14,8 +14,7 @@ class Y(Protocol): y: int -def funcY(x: Y) -> Y: - ... +def funcY(x: Y) -> Y: ... # This should generate an error @@ -31,8 +30,7 @@ class X(Protocol): x: Final[int] = field() -def funcX(x: X) -> X: - ... +def funcX(x: X) -> X: ... # This should generate an error diff --git a/packages/pyright-internal/src/tests/samples/protocol2.py b/packages/pyright-internal/src/tests/samples/protocol2.py index 657323af4..c66e72022 100644 --- a/packages/pyright-internal/src/tests/samples/protocol2.py +++ b/packages/pyright-internal/src/tests/samples/protocol2.py @@ -11,8 +11,7 @@ T_contra = TypeVar("T_contra", contravariant=True) class Writer(Protocol[T_contra]): - def write(self, data: T_contra) -> None: - ... + def write(self, data: T_contra) -> None: ... class WriteFile: diff --git a/packages/pyright-internal/src/tests/samples/protocol20.py b/packages/pyright-internal/src/tests/samples/protocol20.py index 59b6ecec5..06702f96b 100644 --- a/packages/pyright-internal/src/tests/samples/protocol20.py +++ b/packages/pyright-internal/src/tests/samples/protocol20.py @@ -5,8 +5,7 @@ from typing import Protocol, TypeVar class ClsProtocol(Protocol): - def __init__(self): - ... + def __init__(self): ... T1 = TypeVar("T1", bound="ClsProtocol") diff --git a/packages/pyright-internal/src/tests/samples/protocol21.py b/packages/pyright-internal/src/tests/samples/protocol21.py index c899a9010..078dda297 100644 --- a/packages/pyright-internal/src/tests/samples/protocol21.py +++ b/packages/pyright-internal/src/tests/samples/protocol21.py @@ -7,8 +7,7 @@ from typing import Protocol class A(Protocol): @property - def name(self) -> str: - ... + def name(self) -> str: ... class B: diff --git a/packages/pyright-internal/src/tests/samples/protocol22.py b/packages/pyright-internal/src/tests/samples/protocol22.py index 623354876..aa80b445d 100644 --- a/packages/pyright-internal/src/tests/samples/protocol22.py +++ b/packages/pyright-internal/src/tests/samples/protocol22.py @@ -18,26 +18,22 @@ _T2_contra = TypeVar("_T2_contra", contravariant=True) # This is right, as `_T1_co` and `_T2_co` are only covariant with # return type. class P1(Protocol[_T1_co, _T2_co]): - def m1(self) -> _T1_co | _T2_co: - ... + def m1(self) -> _T1_co | _T2_co: ... # This is right, as `_T1_contra` and `_T2_contra` are only covariant # with the argument type. class P2(Protocol[_T1_contra, _T2_contra]): - def m1(self, a: _T1_contra | _T2_contra) -> None: - ... + def m1(self, a: _T1_contra | _T2_contra) -> None: ... # This is right, as `_T1` and `_T2` are both covariant with the # argument type and the return type. class P3(Protocol[_T1, _T2]): - def m1(self, a: _T1, b: _T2) -> _T1 | _T2: - ... + def m1(self, a: _T1, b: _T2) -> _T1 | _T2: ... # This is right, as `_T1` and `_T2` are both covariant with the # argument type and the return type. class P4(Protocol[_T1, _T2]): - def m2(self, a: _T1 | _T2) -> tuple[_T1, _T2]: - ... + def m2(self, a: _T1 | _T2) -> tuple[_T1, _T2]: ... diff --git a/packages/pyright-internal/src/tests/samples/protocol23.py b/packages/pyright-internal/src/tests/samples/protocol23.py index 56a3576e2..f7f7e1bc4 100644 --- a/packages/pyright-internal/src/tests/samples/protocol23.py +++ b/packages/pyright-internal/src/tests/samples/protocol23.py @@ -7,8 +7,7 @@ from typing import Protocol class Proto(Protocol): @abstractmethod - def meth(self) -> int: - ... + def meth(self) -> int: ... class Concrete: @@ -34,8 +33,7 @@ val1().meth() val1 = Proto -def func2() -> type[Proto]: - ... +def func2() -> type[Proto]: ... val1 = func2() diff --git a/packages/pyright-internal/src/tests/samples/protocol24.py b/packages/pyright-internal/src/tests/samples/protocol24.py index 18a9b859b..a0b79c490 100644 --- a/packages/pyright-internal/src/tests/samples/protocol24.py +++ b/packages/pyright-internal/src/tests/samples/protocol24.py @@ -5,18 +5,15 @@ from typing import Any, ClassVar, Protocol class ProtoA(Protocol): - def meth(_self, x: int) -> int: - ... + def meth(_self, x: int) -> int: ... class ProtoB(Protocol): - def meth(_self, self: Any, x: int) -> int: - ... + def meth(_self, self: Any, x: int) -> int: ... class C: - def meth(self, x: int) -> int: - ... + def meth(self, x: int) -> int: ... # This should generate an error because C.meth isn't compatible @@ -30,8 +27,7 @@ class ProtoD(Protocol): var1: int @property - def var2(self) -> str: - ... + def var2(self) -> str: ... class E: @@ -51,19 +47,16 @@ e: ProtoD = F class Jumps(Protocol): - def jump(self) -> int: - ... + def jump(self) -> int: ... class Jumper1: @classmethod - def jump(cls) -> int: - ... + def jump(cls) -> int: ... class Jumper2: - def jump(self) -> int: - ... + def jump(self) -> int: ... def do_jump(j: Jumps): diff --git a/packages/pyright-internal/src/tests/samples/protocol25.py b/packages/pyright-internal/src/tests/samples/protocol25.py index b0a4d2f7b..1ecb4ca58 100644 --- a/packages/pyright-internal/src/tests/samples/protocol25.py +++ b/packages/pyright-internal/src/tests/samples/protocol25.py @@ -5,20 +5,17 @@ from typing import Any, Iterable, Protocol -class B: - ... +class B: ... class C: - def __class_getitem__(cls, __item: Any) -> Any: - ... + def __class_getitem__(cls, __item: Any) -> Any: ... class SupportsClassGetItem(Protocol): __slots__: str | Iterable[str] = () - def __class_getitem__(cls, __item: Any) -> Any: - ... + def __class_getitem__(cls, __item: Any) -> Any: ... b1: SupportsClassGetItem = B() # OK (missing __class_getitem__ is ignored) diff --git a/packages/pyright-internal/src/tests/samples/protocol26.py b/packages/pyright-internal/src/tests/samples/protocol26.py index 7a8899d30..f7d67b942 100644 --- a/packages/pyright-internal/src/tests/samples/protocol26.py +++ b/packages/pyright-internal/src/tests/samples/protocol26.py @@ -7,31 +7,27 @@ _T_co = TypeVar("_T_co", covariant=True) class SupportsIndex(Protocol): - def __index__(self) -> int: - ... + def __index__(self) -> int: ... class TupleLike(Sequence[_T_co]): @overload - def __getitem__(self, index: SupportsIndex) -> _T_co: - ... + def __getitem__(self, index: SupportsIndex) -> _T_co: ... @overload - def __getitem__(self, index: slice) -> "TupleLike[_T_co]": - ... + def __getitem__(self, index: slice) -> "TupleLike[_T_co]": ... - def __getitem__(self, index: slice | SupportsIndex) -> "_T_co | TupleLike[_T_co]": - ... + def __getitem__( + self, index: slice | SupportsIndex + ) -> "_T_co | TupleLike[_T_co]": ... class NestedSequence(Protocol[_T_co]): @overload - def __getitem__(self, index: int, /) -> "_T_co | NestedSequence[_T_co]": - ... + def __getitem__(self, index: int, /) -> "_T_co | NestedSequence[_T_co]": ... @overload - def __getitem__(self, index: slice, /) -> "NestedSequence[_T_co]": - ... + def __getitem__(self, index: slice, /) -> "NestedSequence[_T_co]": ... def func(t: TupleLike[int]): diff --git a/packages/pyright-internal/src/tests/samples/protocol28.py b/packages/pyright-internal/src/tests/samples/protocol28.py index 948fa52b0..e80f64a98 100644 --- a/packages/pyright-internal/src/tests/samples/protocol28.py +++ b/packages/pyright-internal/src/tests/samples/protocol28.py @@ -10,24 +10,20 @@ _T3 = TypeVar("_T3", covariant=True) class Callable1(Protocol[_T1]): - def __call__(self, __x: _T1) -> Any: - ... + def __call__(self, __x: _T1) -> Any: ... _T4 = TypeVar("_T4", bound=Callable1[Any]) class Decorator1(Protocol[_T2]): - def __call__(self, __x: Callable1[_T2]) -> Any: - ... + def __call__(self, __x: Callable1[_T2]) -> Any: ... -def decorator1(__x: Decorator1[_T3]) -> Decorator1[_T3]: - ... +def decorator1(__x: Decorator1[_T3]) -> Decorator1[_T3]: ... -def func1(__x: _T4) -> _T4: - ... +def func1(__x: _T4) -> _T4: ... decorator1(func1) diff --git a/packages/pyright-internal/src/tests/samples/protocol31.py b/packages/pyright-internal/src/tests/samples/protocol31.py index a11bd7a0a..3142cf9a8 100644 --- a/packages/pyright-internal/src/tests/samples/protocol31.py +++ b/packages/pyright-internal/src/tests/samples/protocol31.py @@ -9,8 +9,7 @@ Tct = TypeVar("Tct", contravariant=True) class Interface(Protocol[Tct]): - def run(self, *, value1: Tct, value2: int) -> object: - ... + def run(self, *, value1: Tct, value2: int) -> object: ... class Implementation(Generic[Tct]): diff --git a/packages/pyright-internal/src/tests/samples/protocol32.py b/packages/pyright-internal/src/tests/samples/protocol32.py index 5f4b59997..222840e4b 100644 --- a/packages/pyright-internal/src/tests/samples/protocol32.py +++ b/packages/pyright-internal/src/tests/samples/protocol32.py @@ -8,18 +8,15 @@ Value = TypeVar("Value") class Base1(Protocol[Value]): - def method1(self, default: Value) -> Value: - ... + def method1(self, default: Value) -> Value: ... class Base2(Base1[Value], Protocol): - def method2(self, default: Value) -> Value: - ... + def method2(self, default: Value) -> Value: ... class Interface(Base2[Value], Protocol[Arg, Value]): - def another(self, arg: Arg) -> None: - ... + def another(self, arg: Arg) -> None: ... class Implementation1(Generic[Arg, Value]): @@ -70,16 +67,13 @@ def func3(arg: Arg, value: Value) -> Interface[Arg, Value]: class Base4(Protocol): @overload - def method3(self, message: int) -> int: - ... + def method3(self, message: int) -> int: ... @overload - def method3(self, message: str) -> str: - ... + def method3(self, message: str) -> str: ... def method3(self, message: str | int): return message -class Implementation4(Base4): - ... +class Implementation4(Base4): ... diff --git a/packages/pyright-internal/src/tests/samples/protocol33.py b/packages/pyright-internal/src/tests/samples/protocol33.py index c51489cdc..f43464969 100644 --- a/packages/pyright-internal/src/tests/samples/protocol33.py +++ b/packages/pyright-internal/src/tests/samples/protocol33.py @@ -8,11 +8,9 @@ U = TypeVar("U", covariant=True) class AProto(Generic[T, U], Protocol): - def f(self) -> T | U: - ... + def f(self) -> T | U: ... - def g(self) -> "AProto[T, U]": - ... + def g(self) -> "AProto[T, U]": ... class A(Generic[T, U]): @@ -24,11 +22,9 @@ class A(Generic[T, U]): class BProto(Generic[T, U], Protocol): - def f(self) -> T | U: - ... + def f(self) -> T | U: ... - def g(self) -> "BProto[T, U]": - ... + def g(self) -> "BProto[T, U]": ... class B(Generic[T, U]): diff --git a/packages/pyright-internal/src/tests/samples/protocol34.py b/packages/pyright-internal/src/tests/samples/protocol34.py index 3467d161f..4ba0958c4 100644 --- a/packages/pyright-internal/src/tests/samples/protocol34.py +++ b/packages/pyright-internal/src/tests/samples/protocol34.py @@ -8,8 +8,7 @@ T = TypeVar("T") class X(Protocol): - def f(self) -> int: - ... + def f(self) -> int: ... class Y(Generic[T]): diff --git a/packages/pyright-internal/src/tests/samples/protocol36.py b/packages/pyright-internal/src/tests/samples/protocol36.py index 7d0b7e22f..921b11e8d 100644 --- a/packages/pyright-internal/src/tests/samples/protocol36.py +++ b/packages/pyright-internal/src/tests/samples/protocol36.py @@ -7,12 +7,10 @@ _T_co = TypeVar("_T_co", covariant=True) class NestedSequence(Protocol[_T_co]): @overload - def __getitem__(self, __i: int) -> _T_co | "NestedSequence[_T_co]": - ... + def __getitem__(self, __i: int) -> _T_co | "NestedSequence[_T_co]": ... @overload - def __getitem__(self, __s: slice) -> "NestedSequence[_T_co]": - ... + def __getitem__(self, __s: slice) -> "NestedSequence[_T_co]": ... def func(v1: list[list[list[int]]]): diff --git a/packages/pyright-internal/src/tests/samples/protocol38.py b/packages/pyright-internal/src/tests/samples/protocol38.py index a31c51ed9..cc316cf54 100644 --- a/packages/pyright-internal/src/tests/samples/protocol38.py +++ b/packages/pyright-internal/src/tests/samples/protocol38.py @@ -5,12 +5,10 @@ from typing import Any, Literal, Protocol, TypeVar class Negatable(Protocol): - def __neg__(self) -> "Negatable": - ... + def __neg__(self) -> "Negatable": ... -def func1(x: Negatable) -> None: - ... +def func1(x: Negatable) -> None: ... func1(0) @@ -24,8 +22,7 @@ T = TypeVar("T", covariant=True) class SupportsGetItem(Protocol[T]): - def __getitem__(self, __k: int) -> T: - ... + def __getitem__(self, __k: int) -> T: ... def func3(a: tuple[Any, ...]): diff --git a/packages/pyright-internal/src/tests/samples/protocol39.py b/packages/pyright-internal/src/tests/samples/protocol39.py index cf6c96aa3..ba7ed6804 100644 --- a/packages/pyright-internal/src/tests/samples/protocol39.py +++ b/packages/pyright-internal/src/tests/samples/protocol39.py @@ -6,8 +6,7 @@ from typing import Any, Protocol class SupportsGet(Protocol): @property - def __get__(self) -> Any: - ... + def __get__(self) -> Any: ... def func1(cls: Any) -> None: diff --git a/packages/pyright-internal/src/tests/samples/protocol40.py b/packages/pyright-internal/src/tests/samples/protocol40.py index 1a1455181..7d6922a49 100644 --- a/packages/pyright-internal/src/tests/samples/protocol40.py +++ b/packages/pyright-internal/src/tests/samples/protocol40.py @@ -8,17 +8,14 @@ S = TypeVar("S", covariant=True) class P1Parent(Protocol[S]): - def f0(self, /) -> Self: - ... + def f0(self, /) -> Self: ... -class P1Child(P1Parent[S], Protocol[S]): - ... +class P1Child(P1Parent[S], Protocol[S]): ... class C1(Generic[T]): - def f0(self, /) -> Self: - ... + def f0(self, /) -> Self: ... a1: P1Parent[str] = C1[str]() @@ -30,8 +27,7 @@ class P2Parent(Protocol[T]): return right -class P2Child(P2Parent[T], Protocol[T]): - ... +class P2Child(P2Parent[T], Protocol[T]): ... class C2(Generic[S]): diff --git a/packages/pyright-internal/src/tests/samples/protocol41.py b/packages/pyright-internal/src/tests/samples/protocol41.py index 134a9a261..2af2e1297 100644 --- a/packages/pyright-internal/src/tests/samples/protocol41.py +++ b/packages/pyright-internal/src/tests/samples/protocol41.py @@ -8,31 +8,26 @@ _T_co = TypeVar("_T_co", covariant=True) _T_contra = TypeVar("_T_contra", contravariant=True) -class MyStr: - ... +class MyStr: ... class MyBytes: - def __buffer__(self, __flags: int) -> memoryview: - ... + def __buffer__(self, __flags: int) -> memoryview: ... MyAnyStr = TypeVar("MyAnyStr", MyStr, MyBytes) class Buffer(Protocol): - def __buffer__(self, __flags: int) -> memoryview: - ... + def __buffer__(self, __flags: int) -> memoryview: ... class SupportsRead(Protocol[_T_co]): - def read(self, __length: int = ...) -> _T_co: - ... + def read(self, __length: int = ...) -> _T_co: ... class SupportsWrite(Protocol[_T_contra]): - def write(self, __s: _T_contra) -> object: - ... + def write(self, __s: _T_contra) -> object: ... class BufferedWriter: @@ -40,8 +35,7 @@ class BufferedWriter: raise NotImplementedError -def func1(s: SupportsRead[MyAnyStr], t: SupportsWrite[MyAnyStr]) -> None: - ... +def func1(s: SupportsRead[MyAnyStr], t: SupportsWrite[MyAnyStr]) -> None: ... def test1(src: SupportsRead[MyBytes], tgt: BufferedWriter) -> None: @@ -61,21 +55,17 @@ class BytesIO: class WriteBuffer(Protocol[AnyStr_contra]): - def write(self, __b: AnyStr_contra) -> Any: - ... + def write(self, __b: AnyStr_contra) -> Any: ... class NDFrame: @overload - def to_csv(self, p: WriteBuffer[bytes]) -> None: - ... + def to_csv(self, p: WriteBuffer[bytes]) -> None: ... @overload - def to_csv(self, p: None = ...) -> str: - ... + def to_csv(self, p: None = ...) -> str: ... - def to_csv(self, p: Any = None) -> Any: - ... + def to_csv(self, p: Any = None) -> Any: ... def test3(b: BytesIO) -> None: diff --git a/packages/pyright-internal/src/tests/samples/protocol43.py b/packages/pyright-internal/src/tests/samples/protocol43.py index 9bcdec07a..fcb90d143 100644 --- a/packages/pyright-internal/src/tests/samples/protocol43.py +++ b/packages/pyright-internal/src/tests/samples/protocol43.py @@ -7,8 +7,7 @@ A = TypeVar("A") class HasAdd1(Protocol[A]): - def __add__(self: A, other: A) -> A: - ... + def __add__(self: A, other: A) -> A: ... T1 = TypeVar("T1", bound=HasAdd1) @@ -24,8 +23,7 @@ def merge_element_lists1(a: Sequence[T1], b: Sequence[T1]) -> Sequence[T1]: # This is similar to HasAdd1 except that the class isn't generic. class HasAdd2(Protocol): - def __add__(self: A, other: A) -> A: - ... + def __add__(self: A, other: A) -> A: ... T2 = TypeVar("T2", bound=HasAdd2) diff --git a/packages/pyright-internal/src/tests/samples/protocol44.py b/packages/pyright-internal/src/tests/samples/protocol44.py index 5fae0c728..002060234 100644 --- a/packages/pyright-internal/src/tests/samples/protocol44.py +++ b/packages/pyright-internal/src/tests/samples/protocol44.py @@ -8,14 +8,11 @@ V = TypeVar("V") class SpecialDict(Protocol[K, V]): - def items(self) -> Iterable[tuple[K, V | int]]: - ... + def items(self) -> Iterable[tuple[K, V | int]]: ... - def __getitem__(self, __key: K) -> V | int: - ... + def __getitem__(self, __key: K) -> V | int: ... - def __setitem__(self, __key: K, __value: V | int) -> None: - ... + def __setitem__(self, __key: K, __value: V | int) -> None: ... def func1(k: K, v: V) -> SpecialDict[K, V]: diff --git a/packages/pyright-internal/src/tests/samples/protocol45.py b/packages/pyright-internal/src/tests/samples/protocol45.py index 894b327b6..566ffd070 100644 --- a/packages/pyright-internal/src/tests/samples/protocol45.py +++ b/packages/pyright-internal/src/tests/samples/protocol45.py @@ -10,8 +10,7 @@ Output = TypeVar("Output") class Proto1(Protocol): - def __call__(self, item: S, /) -> S: - ... + def __call__(self, item: S, /) -> S: ... class Impl1: @@ -30,5 +29,3 @@ class Wrapper(Generic[Input, Output]): y = Wrapper(Impl1()) reveal_type(y, expected_text="Wrapper[T@__call__, T@__call__]") x: Proto1 = y - - diff --git a/packages/pyright-internal/src/tests/samples/protocol46.py b/packages/pyright-internal/src/tests/samples/protocol46.py index dc539d3ee..274c6db01 100644 --- a/packages/pyright-internal/src/tests/samples/protocol46.py +++ b/packages/pyright-internal/src/tests/samples/protocol46.py @@ -9,42 +9,33 @@ T = TypeVar("T") class ProtoA(Protocol[T_contra, T]): - def method1(self, value: T_contra) -> "ProtoA[T_contra, T]": - ... + def method1(self, value: T_contra) -> "ProtoA[T_contra, T]": ... @classmethod - def method2(cls, value: T) -> T: - ... + def method2(cls, value: T) -> T: ... class ProtoB(Protocol[T_contra, T]): - def method3(self) -> ProtoA[T_contra, T]: - ... + def method3(self) -> ProtoA[T_contra, T]: ... class ImplA: - def method1(self, value: int) -> Self: - ... + def method1(self, value: int) -> Self: ... @classmethod - def method2(cls, value: int) -> int: - ... + def method2(cls, value: int) -> int: ... class ImplB: - def method3(self) -> ImplA: - ... + def method3(self) -> ImplA: ... - def method1(self, value: int) -> Self: - ... + def method1(self, value: int) -> Self: ... @classmethod - def method2(cls: type[ProtoB[Never, T]], value: list[T]) -> list[T]: - ... + def method2(cls: type[ProtoB[Never, T]], value: list[T]) -> list[T]: ... -def func1(x: ProtoA[Never, T]) -> T: - ... +def func1(x: ProtoA[Never, T]) -> T: ... v1 = func1(ImplB()) diff --git a/packages/pyright-internal/src/tests/samples/protocol47.py b/packages/pyright-internal/src/tests/samples/protocol47.py index c175b4417..2a69f8402 100644 --- a/packages/pyright-internal/src/tests/samples/protocol47.py +++ b/packages/pyright-internal/src/tests/samples/protocol47.py @@ -9,8 +9,7 @@ T2 = TypeVar("T2") class ProtoA(Protocol[T1]): - def method1(self, __key: str, __default: T2) -> "T1 | T2": - ... + def method1(self, __key: str, __default: T2) -> "T1 | T2": ... T3 = TypeVar("T3", covariant=True) @@ -25,8 +24,7 @@ class A(Generic[T3]): a1: A[str] = A() -def func1(storage: ProtoA[int]): - ... +def func1(storage: ProtoA[int]): ... v1: ProtoA[int] = a1 diff --git a/packages/pyright-internal/src/tests/samples/protocol48.py b/packages/pyright-internal/src/tests/samples/protocol48.py index 872a3f23f..9a36e4692 100644 --- a/packages/pyright-internal/src/tests/samples/protocol48.py +++ b/packages/pyright-internal/src/tests/samples/protocol48.py @@ -6,17 +6,14 @@ T = TypeVar("T", covariant=True) class SupportsMethod1(Protocol[T]): - def method1(self) -> T: - ... + def method1(self) -> T: ... -def apply_method1(__x: SupportsMethod1[T]) -> T: - ... +def apply_method1(__x: SupportsMethod1[T]) -> T: ... class A: - def method1(self) -> tuple[Self, Self]: - ... + def method1(self) -> tuple[Self, Self]: ... def method2(self): x = apply_method1(self) diff --git a/packages/pyright-internal/src/tests/samples/protocol8.py b/packages/pyright-internal/src/tests/samples/protocol8.py index cac7e2bcc..7c790e10a 100644 --- a/packages/pyright-internal/src/tests/samples/protocol8.py +++ b/packages/pyright-internal/src/tests/samples/protocol8.py @@ -4,13 +4,11 @@ from typing import Protocol -class _BaseClass: - ... +class _BaseClass: ... class _Protocol1(Protocol): - def __call__(self, p1: str, p2) -> _BaseClass: - ... + def __call__(self, p1: str, p2) -> _BaseClass: ... def func1(callback: _Protocol1): @@ -18,13 +16,11 @@ def func1(callback: _Protocol1): class _Class1(_BaseClass): - def __init__(self, my_str: str): - ... + def __init__(self, my_str: str): ... class _Class2(_BaseClass): - def __init__(self, p1: str, p2: str): - ... + def __init__(self, p1: str, p2: str): ... # This should generate an error because the diff --git a/packages/pyright-internal/src/tests/samples/protocol9.py b/packages/pyright-internal/src/tests/samples/protocol9.py index 4aee00c45..f86e3d743 100644 --- a/packages/pyright-internal/src/tests/samples/protocol9.py +++ b/packages/pyright-internal/src/tests/samples/protocol9.py @@ -8,12 +8,10 @@ class TreeLike(Protocol): value: int @property - def left(self) -> "TreeLike | None": - ... + def left(self) -> "TreeLike | None": ... @property - def right(self) -> "TreeLike | None": - ... + def right(self) -> "TreeLike | None": ... class SimpleTree: @@ -37,8 +35,7 @@ root: TreeLike = SimpleTree(0) class ProtoA(Protocol): - def method1(self) -> "ProtoA": - ... + def method1(self) -> "ProtoA": ... class ImplA: diff --git a/packages/pyright-internal/src/tests/samples/protocolExplicit3.py b/packages/pyright-internal/src/tests/samples/protocolExplicit3.py index 73a753e81..183198ec2 100644 --- a/packages/pyright-internal/src/tests/samples/protocolExplicit3.py +++ b/packages/pyright-internal/src/tests/samples/protocolExplicit3.py @@ -10,8 +10,7 @@ from typing import final from .protocolExplicit2 import Protocol1, Protocol3, Protocol5, Protocol6, Protocol7 -class Concrete1(Protocol1): - ... +class Concrete1(Protocol1): ... # This should generate an error because some attributes are not implemented. diff --git a/packages/pyright-internal/src/tests/samples/protocolModule2.py b/packages/pyright-internal/src/tests/samples/protocolModule2.py index bbf1e7d25..d2bd17deb 100644 --- a/packages/pyright-internal/src/tests/samples/protocolModule2.py +++ b/packages/pyright-internal/src/tests/samples/protocolModule2.py @@ -11,12 +11,10 @@ class P1(Protocol): var_1: int var_2: int | str - def func_1(self, a: int, b: str) -> str: - ... + def func_1(self, a: int, b: str) -> str: ... @staticmethod - def func_2() -> str: - ... + def func_2() -> str: ... v1: P1 = protocolModule1 @@ -33,8 +31,7 @@ v2: P2 = protocolModule1 class P3(Protocol): - def func_1(self, a: int, b: str) -> int: - ... + def func_1(self, a: int, b: str) -> int: ... # This should generate an error because func_1 has the @@ -43,8 +40,7 @@ v3: P3 = protocolModule1 class P4(Protocol): - def func_2(self) -> str: - ... + def func_2(self) -> str: ... y: int @@ -56,8 +52,7 @@ v4: P4 = protocolModule1 _T = TypeVar("_T", bound=P2) -class NonProtocol: - ... +class NonProtocol: ... # Test type narrowing of module symbols for isinstance checks. @@ -87,12 +82,10 @@ _T1 = TypeVar("_T1") class P5(Protocol[_T1]): - def func_1(self, a: int, b: _T1) -> _T1: - ... + def func_1(self, a: int, b: _T1) -> _T1: ... -def func4(x: P5[_T1]) -> _T1: - ... +def func4(x: P5[_T1]) -> _T1: ... v5 = func4(protocolModule1) @@ -101,8 +94,7 @@ reveal_type(v5, expected_text="str") class P6(Protocol): @property - def var_1(self) -> int: - ... + def var_1(self) -> int: ... v6: P6 = protocolModule1 diff --git a/packages/pyright-internal/src/tests/samples/protocolModule3.py b/packages/pyright-internal/src/tests/samples/protocolModule3.py index 940a97ff7..134b05312 100644 --- a/packages/pyright-internal/src/tests/samples/protocolModule3.py +++ b/packages/pyright-internal/src/tests/samples/protocolModule3.py @@ -6,8 +6,7 @@ Y = TypeVar("Y", contravariant=True) class Fn(Protocol[Y]): - def __call__(self, y: Y) -> None: - ... + def __call__(self, y: Y) -> None: ... def x(x: Fn[int]) -> None: diff --git a/packages/pyright-internal/src/tests/samples/protocolModule4.py b/packages/pyright-internal/src/tests/samples/protocolModule4.py index 560027106..ac2e3ed27 100644 --- a/packages/pyright-internal/src/tests/samples/protocolModule4.py +++ b/packages/pyright-internal/src/tests/samples/protocolModule4.py @@ -11,8 +11,7 @@ Z = TypeVar("Z") class FnHandler(Protocol[X]): - def __call__(self, x: Fn[X]) -> None: - ... + def __call__(self, x: Fn[X]) -> None: ... class ModuleSpec(Protocol[Z]): diff --git a/packages/pyright-internal/src/tests/samples/pseudoGeneric1.py b/packages/pyright-internal/src/tests/samples/pseudoGeneric1.py index 8a0c0b8ff..90c280f92 100644 --- a/packages/pyright-internal/src/tests/samples/pseudoGeneric1.py +++ b/packages/pyright-internal/src/tests/samples/pseudoGeneric1.py @@ -5,8 +5,7 @@ _DEFAULT_VALUE = object() class ClassA: - def __init__(self, name, description=_DEFAULT_VALUE): - ... + def __init__(self, name, description=_DEFAULT_VALUE): ... a1: list[ClassA] = [ClassA("a", description="b")] diff --git a/packages/pyright-internal/src/tests/samples/recursiveTypeAlias12.py b/packages/pyright-internal/src/tests/samples/recursiveTypeAlias12.py index 963e590bc..683a7559d 100644 --- a/packages/pyright-internal/src/tests/samples/recursiveTypeAlias12.py +++ b/packages/pyright-internal/src/tests/samples/recursiveTypeAlias12.py @@ -8,19 +8,16 @@ from typing import Any, Protocol, Self, TypeAlias class TraceFunctionProto(Protocol): - def __call__(self, frame: FrameType, event: str, arg: Any) -> Self | None: - ... + def __call__(self, frame: FrameType, event: str, arg: Any) -> Self | None: ... TraceFunction: TypeAlias = Callable[[FrameType, str, Any], "TraceFunction | None"] -def settrace(tf: TraceFunction | None) -> None: - ... +def settrace(tf: TraceFunction | None) -> None: ... -def func1(frame: FrameType, event: str, arg: Any) -> TraceFunction: - ... +def func1(frame: FrameType, event: str, arg: Any) -> TraceFunction: ... def func2(tf: TraceFunctionProto | None): diff --git a/packages/pyright-internal/src/tests/samples/recursiveTypeAlias6.py b/packages/pyright-internal/src/tests/samples/recursiveTypeAlias6.py index 1370fcc1b..ced168084 100644 --- a/packages/pyright-internal/src/tests/samples/recursiveTypeAlias6.py +++ b/packages/pyright-internal/src/tests/samples/recursiveTypeAlias6.py @@ -9,16 +9,14 @@ RecList = Union[Mapping[str, "RecList[S]"], Sequence["RecList[S]"], S] T3 = TypeVar("T3", RecList[int], RecList[str]) -def f3(x: RecList[int] | RecList[str]) -> None: - ... +def f3(x: RecList[int] | RecList[str]) -> None: ... def g3(x: T3): return f3(x) -def f4(x: RecList[str] | RecList[int]) -> None: - ... +def f4(x: RecList[str] | RecList[int]) -> None: ... def g4(x: T3): diff --git a/packages/pyright-internal/src/tests/samples/self10.py b/packages/pyright-internal/src/tests/samples/self10.py index 6cdda68e8..feae0657c 100644 --- a/packages/pyright-internal/src/tests/samples/self10.py +++ b/packages/pyright-internal/src/tests/samples/self10.py @@ -4,8 +4,7 @@ from typing import Self class A: - def self_arg(self, other: Self): - ... + def self_arg(self, other: Self): ... def call_self_arg(self): # This should generate an error. diff --git a/packages/pyright-internal/src/tests/samples/self3.py b/packages/pyright-internal/src/tests/samples/self3.py index c6a705247..f2cd95585 100644 --- a/packages/pyright-internal/src/tests/samples/self3.py +++ b/packages/pyright-internal/src/tests/samples/self3.py @@ -3,7 +3,6 @@ class SomeClass: - def __str__(self) -> str: - ... + def __str__(self) -> str: ... __repr__ = __str__ diff --git a/packages/pyright-internal/src/tests/samples/self4.py b/packages/pyright-internal/src/tests/samples/self4.py index eb16944c5..fd8914b39 100644 --- a/packages/pyright-internal/src/tests/samples/self4.py +++ b/packages/pyright-internal/src/tests/samples/self4.py @@ -7,11 +7,9 @@ T = TypeVar("T") S = TypeVar("S", bound="MyClass[Any]") -def my_generic_wrapper(f: Callable[[S], str]) -> Callable[[S], int]: - ... +def my_generic_wrapper(f: Callable[[S], str]) -> Callable[[S], int]: ... class MyClass(Generic[T]): @my_generic_wrapper - def do_something(self) -> str: - ... + def do_something(self) -> str: ... diff --git a/packages/pyright-internal/src/tests/samples/self6.py b/packages/pyright-internal/src/tests/samples/self6.py index b39a5fab2..12b695a02 100644 --- a/packages/pyright-internal/src/tests/samples/self6.py +++ b/packages/pyright-internal/src/tests/samples/self6.py @@ -7,8 +7,7 @@ T_contra = TypeVar("T_contra", contravariant=True) class MyClass(Generic[T_contra]): - def __new__(cls: type[Self]) -> Self: - ... + def __new__(cls: type[Self]) -> Self: ... MyClass[int]() diff --git a/packages/pyright-internal/src/tests/samples/slots3.py b/packages/pyright-internal/src/tests/samples/slots3.py index 60252aa4e..86d5909f2 100644 --- a/packages/pyright-internal/src/tests/samples/slots3.py +++ b/packages/pyright-internal/src/tests/samples/slots3.py @@ -5,14 +5,11 @@ from typing import Any class MyDescriptor: - def __init__(self, *, slot: str): - ... + def __init__(self, *, slot: str): ... - def __set__(self, instance: object, value: object) -> None: - ... + def __set__(self, instance: object, value: object) -> None: ... - def __get__(self, instance: object, owner: Any) -> Any: - ... + def __get__(self, instance: object, owner: Any) -> Any: ... class ClassA: diff --git a/packages/pyright-internal/src/tests/samples/solver10.py b/packages/pyright-internal/src/tests/samples/solver10.py index d7b6dc798..a2fecdcb6 100644 --- a/packages/pyright-internal/src/tests/samples/solver10.py +++ b/packages/pyright-internal/src/tests/samples/solver10.py @@ -17,8 +17,7 @@ def extend_if(xs: list[_T], ys: list[tuple[_T, bool]]) -> list[_T]: extend_if(["foo"], [("bar", True), ("baz", True)]) -def func1(value: _T) -> Callable[[_T], None]: - ... +def func1(value: _T) -> Callable[[_T], None]: ... def func2() -> Callable[[bool], None]: diff --git a/packages/pyright-internal/src/tests/samples/solver11.py b/packages/pyright-internal/src/tests/samples/solver11.py index a6e539831..b18281f76 100644 --- a/packages/pyright-internal/src/tests/samples/solver11.py +++ b/packages/pyright-internal/src/tests/samples/solver11.py @@ -5,8 +5,7 @@ from typing import Callable, Literal, TypeVar -def filter_fn(value: object): - ... +def filter_fn(value: object): ... v1 = filter(filter_fn, [1, 2, 3]) @@ -23,15 +22,13 @@ _T = TypeVar("_T") Animal = Literal["cat"] -def func(v: Callable[[], _T]) -> _T: - ... +def func(v: Callable[[], _T]) -> _T: ... x1: dict[Animal, int] = func(lambda: {"cat": 0}) -def func1(factory: Callable[[], _T]) -> _T: - ... +def func1(factory: Callable[[], _T]) -> _T: ... x2: set[int] = func1(lambda: set()) diff --git a/packages/pyright-internal/src/tests/samples/solver12.py b/packages/pyright-internal/src/tests/samples/solver12.py index dfd4f04a3..ffd248a09 100644 --- a/packages/pyright-internal/src/tests/samples/solver12.py +++ b/packages/pyright-internal/src/tests/samples/solver12.py @@ -8,8 +8,7 @@ _T2 = TypeVar("_T2", bound="ClassA") class ClassA: - def chain(self: _T1) -> _T1: - ... + def chain(self: _T1) -> _T1: ... def func1(p1: _T2) -> _T2: diff --git a/packages/pyright-internal/src/tests/samples/solver13.py b/packages/pyright-internal/src/tests/samples/solver13.py index e41124d76..40b50ecb7 100644 --- a/packages/pyright-internal/src/tests/samples/solver13.py +++ b/packages/pyright-internal/src/tests/samples/solver13.py @@ -7,14 +7,11 @@ T = TypeVar("T") class ClassA(Iterator[T]): - def __init__(self, it: Iterable[T]) -> None: - ... + def __init__(self, it: Iterable[T]) -> None: ... - def __next__(self) -> T: - ... + def __next__(self) -> T: ... - def __iter__(self) -> Iterator[T]: - ... + def __iter__(self) -> Iterator[T]: ... def func1(val: Iterable[T]) -> Iterator[T]: diff --git a/packages/pyright-internal/src/tests/samples/solver14.py b/packages/pyright-internal/src/tests/samples/solver14.py index c952b9a20..38508e4c4 100644 --- a/packages/pyright-internal/src/tests/samples/solver14.py +++ b/packages/pyright-internal/src/tests/samples/solver14.py @@ -9,27 +9,22 @@ _X_contra = TypeVar("_X_contra", contravariant=True) class SupportsDivMod(Protocol, Generic[_X_contra, _X_co]): - def __divmod__(self, __other: _X_contra) -> _X_co: - ... + def __divmod__(self, __other: _X_contra) -> _X_co: ... class SupportsRDivMod(Protocol[_X_contra, _X_co]): - def __rdivmod__(self, __other: _X_contra) -> _X_co: - ... + def __rdivmod__(self, __other: _X_contra) -> _X_co: ... @overload -def divmod(__x: SupportsDivMod[_X_contra, _X_co], __y: _X_contra) -> _X_co: - ... +def divmod(__x: SupportsDivMod[_X_contra, _X_co], __y: _X_contra) -> _X_co: ... @overload -def divmod(__x: _X_contra, __y: SupportsRDivMod[_X_contra, _X_co]) -> _X_co: - ... +def divmod(__x: _X_contra, __y: SupportsRDivMod[_X_contra, _X_co]) -> _X_co: ... -def divmod(__x: Any, __y: Any) -> Any: - ... +def divmod(__x: Any, __y: Any) -> Any: ... reveal_type( @@ -42,19 +37,16 @@ reveal_type(divmod(3, 4.5), expected_text="tuple[float, float]") class SupportsLessThan(Protocol): - def __lt__(self, __other: Any) -> bool: - ... + def __lt__(self, __other: Any) -> bool: ... SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan) -def max2(__arg1: SupportsLessThanT, __arg2: SupportsLessThanT) -> SupportsLessThanT: - ... +def max2(__arg1: SupportsLessThanT, __arg2: SupportsLessThanT) -> SupportsLessThanT: ... -def min2(__arg1: SupportsLessThanT, __arg2: SupportsLessThanT) -> SupportsLessThanT: - ... +def min2(__arg1: SupportsLessThanT, __arg2: SupportsLessThanT) -> SupportsLessThanT: ... def func1(): diff --git a/packages/pyright-internal/src/tests/samples/solver15.py b/packages/pyright-internal/src/tests/samples/solver15.py index dc76b2f06..1682cbe44 100644 --- a/packages/pyright-internal/src/tests/samples/solver15.py +++ b/packages/pyright-internal/src/tests/samples/solver15.py @@ -4,15 +4,13 @@ from typing import Callable, Generic, TypeVar -class Base: - ... +class Base: ... T = TypeVar("T", bound=Base) -def register(state_name: str, state: type[T]): - ... +def register(state_name: str, state: type[T]): ... def register_state(state_name: str) -> Callable[[type[T]], type[T]]: @@ -23,15 +21,13 @@ def register_state(state_name: str) -> Callable[[type[T]], type[T]]: return decorator -class F: - ... +class F: ... E = TypeVar("E", bound=F) -def coercer_method(value: E | str, enum: type[E]) -> E: - ... +def coercer_method(value: E | str, enum: type[E]) -> E: ... class C(Generic[E]): diff --git a/packages/pyright-internal/src/tests/samples/solver17.py b/packages/pyright-internal/src/tests/samples/solver17.py index a056fc9d5..fa395cb47 100644 --- a/packages/pyright-internal/src/tests/samples/solver17.py +++ b/packages/pyright-internal/src/tests/samples/solver17.py @@ -8,12 +8,10 @@ from typing import Pattern, Sequence, TypeVar _T = TypeVar("_T") -def func1(v: list[_T | None]) -> _T: - ... +def func1(v: list[_T | None]) -> _T: ... -def func2(v: list[_T | str | None]) -> _T: - ... +def func2(v: list[_T | str | None]) -> _T: ... v1: list[int | None] = [1, None] diff --git a/packages/pyright-internal/src/tests/samples/solver18.py b/packages/pyright-internal/src/tests/samples/solver18.py index 7e713f0a7..5c2e9b1ab 100644 --- a/packages/pyright-internal/src/tests/samples/solver18.py +++ b/packages/pyright-internal/src/tests/samples/solver18.py @@ -9,8 +9,7 @@ _T = TypeVar("_T") _P = ParamSpec("_P") -def func1(x: str | None | _T) -> str | None | _T: - ... +def func1(x: str | None | _T) -> str | None | _T: ... reveal_type(func1(None), expected_text="str | None") @@ -18,8 +17,7 @@ reveal_type(func1("hi"), expected_text="str | None") reveal_type(func1(3), expected_text="str | int | None") -def func2(x: str | None | _T) -> list[str | None | _T]: - ... +def func2(x: str | None | _T) -> list[str | None | _T]: ... reveal_type(func2(None), expected_text="list[str | None]") @@ -31,17 +29,14 @@ Callback = Callable[..., Awaitable[None]] _C = TypeVar("_C", bound=Callback) -class ClassA(Generic[_C]): - ... +class ClassA(Generic[_C]): ... -def decorator1() -> Callable[[_C | ClassA[_C]], ClassA[_C]]: - ... +def decorator1() -> Callable[[_C | ClassA[_C]], ClassA[_C]]: ... @decorator1() -async def func3() -> None: - ... +async def func3() -> None: ... def func4(l: list): @@ -52,12 +47,10 @@ val = func4([]) reveal_type(val, expected_text="Unknown | None") -def func5() -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: - ... +def func5() -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: ... -def func6(x: int) -> str: - ... +def func6(x: int) -> str: ... reveal_type(func5()(func6), expected_text="(x: int) -> str") @@ -68,8 +61,7 @@ class ClassB(Generic[_P]): pass -def decorator2() -> Callable[[Callable[_P, None]], ClassB[_P]]: - ... +def decorator2() -> Callable[[Callable[_P, None]], ClassB[_P]]: ... @decorator2() diff --git a/packages/pyright-internal/src/tests/samples/solver2.py b/packages/pyright-internal/src/tests/samples/solver2.py index eada59a73..c57fb1a57 100644 --- a/packages/pyright-internal/src/tests/samples/solver2.py +++ b/packages/pyright-internal/src/tests/samples/solver2.py @@ -13,8 +13,7 @@ class ProtoA(Iterator[_T], Protocol): pass -def decorator1(func: Callable[..., Iterator[_T]]) -> Callable[..., ProtoA[_T]]: - ... +def decorator1(func: Callable[..., Iterator[_T]]) -> Callable[..., ProtoA[_T]]: ... @decorator1 diff --git a/packages/pyright-internal/src/tests/samples/solver21.py b/packages/pyright-internal/src/tests/samples/solver21.py index a9c732a90..cd627e8a2 100644 --- a/packages/pyright-internal/src/tests/samples/solver21.py +++ b/packages/pyright-internal/src/tests/samples/solver21.py @@ -3,12 +3,10 @@ from typing import Generic, TypeVar -class A: - ... +class A: ... -class B: - ... +class B: ... _T3 = TypeVar("_T3", bound=A | B) @@ -19,12 +17,10 @@ class Registry(Generic[_T3]): self.registry = {} @property - def registry(self) -> dict[str, _T3]: - ... + def registry(self) -> dict[str, _T3]: ... @registry.setter - def registry(self, registry: dict[str, _T3]) -> None: - ... + def registry(self, registry: dict[str, _T3]) -> None: ... def get(self, _id: str) -> _T3 | None: return self.registry.get(_id) diff --git a/packages/pyright-internal/src/tests/samples/solver22.py b/packages/pyright-internal/src/tests/samples/solver22.py index bb48c1f35..272f322b8 100644 --- a/packages/pyright-internal/src/tests/samples/solver22.py +++ b/packages/pyright-internal/src/tests/samples/solver22.py @@ -6,12 +6,10 @@ from typing import Any, TypeVar T = TypeVar("T") -def f(x: type[T]) -> T: - ... +def f(x: type[T]) -> T: ... -def g() -> type | Any: - ... +def g() -> type | Any: ... y = g() diff --git a/packages/pyright-internal/src/tests/samples/solver23.py b/packages/pyright-internal/src/tests/samples/solver23.py index f01849100..defdfed1d 100644 --- a/packages/pyright-internal/src/tests/samples/solver23.py +++ b/packages/pyright-internal/src/tests/samples/solver23.py @@ -3,12 +3,10 @@ from typing import Hashable -def func1(x: list[Hashable]): - ... +def func1(x: list[Hashable]): ... -def func2(x: list[object]): - ... +def func2(x: list[object]): ... v1: list[int] = [1] diff --git a/packages/pyright-internal/src/tests/samples/solver27.py b/packages/pyright-internal/src/tests/samples/solver27.py index 323a307e8..f1171bb01 100644 --- a/packages/pyright-internal/src/tests/samples/solver27.py +++ b/packages/pyright-internal/src/tests/samples/solver27.py @@ -35,14 +35,12 @@ class ClassA(Generic[T]): reveal_type(ClassA[int], expected_text="type[ClassA[int]]") -def deco4() -> Callable[[type[T]], type[T]]: - ... +def deco4() -> Callable[[type[T]], type[T]]: ... @deco4() class ClassB: - def get_features(self) -> list[str]: - ... + def get_features(self) -> list[str]: ... def func1(specs: Iterable[str] | ClassB) -> None: diff --git a/packages/pyright-internal/src/tests/samples/solver29.py b/packages/pyright-internal/src/tests/samples/solver29.py index 934d368ed..e1498c86b 100644 --- a/packages/pyright-internal/src/tests/samples/solver29.py +++ b/packages/pyright-internal/src/tests/samples/solver29.py @@ -7,20 +7,16 @@ S = TypeVar("S") T = TypeVar("T") -def accepts_bool(b: bool) -> None: - ... +def accepts_bool(b: bool) -> None: ... -def accepts_int(i: int) -> None: - ... +def accepts_int(i: int) -> None: ... -def func1(x: S | T, l2: Callable[[S], Any], l3: Callable[[T], Any]) -> tuple[S, T]: - ... +def func1(x: S | T, l2: Callable[[S], Any], l3: Callable[[T], Any]) -> tuple[S, T]: ... -def func2(x: T | S, l2: Callable[[S], Any], l3: Callable[[T], Any]) -> tuple[S, T]: - ... +def func2(x: T | S, l2: Callable[[S], Any], l3: Callable[[T], Any]) -> tuple[S, T]: ... x1 = func1(0, accepts_int, accepts_bool) diff --git a/packages/pyright-internal/src/tests/samples/solver3.py b/packages/pyright-internal/src/tests/samples/solver3.py index a6d63f8be..a9176a3e0 100644 --- a/packages/pyright-internal/src/tests/samples/solver3.py +++ b/packages/pyright-internal/src/tests/samples/solver3.py @@ -7,8 +7,7 @@ from typing import Iterable, Iterator, Literal, TypeVar _T = TypeVar("_T") -def filter(__function: None, __iterable: Iterable[_T | None]) -> Iterator[_T]: - ... +def filter(__function: None, __iterable: Iterable[_T | None]) -> Iterator[_T]: ... # In this case, bool is a subclass of int, so the TypeVar diff --git a/packages/pyright-internal/src/tests/samples/solver30.py b/packages/pyright-internal/src/tests/samples/solver30.py index a417adba8..46a49fa2a 100644 --- a/packages/pyright-internal/src/tests/samples/solver30.py +++ b/packages/pyright-internal/src/tests/samples/solver30.py @@ -15,24 +15,19 @@ class Item: items = [Item()] -def func1(a: Iterable[X]) -> X: - ... +def func1(a: Iterable[X]) -> X: ... -def func2(a: Iterable[Y]) -> Iterable[Y]: - ... +def func2(a: Iterable[Y]) -> Iterable[Y]: ... class func3(Iterator[Z]): - def __init__(self, a: Callable[[Z], Any], b: Iterable[Z]) -> None: - ... + def __init__(self, a: Callable[[Z], Any], b: Iterable[Z]) -> None: ... - def __next__(self) -> Z: - ... + def __next__(self) -> Z: ... -def func4(a: Callable[[Z], Any], b: Iterable[Z]) -> Iterator[Z]: - ... +def func4(a: Callable[[Z], Any], b: Iterable[Z]) -> Iterator[Z]: ... func1(func2(func3(lambda x: reveal_type(x.foo, expected_text="bool"), items))) diff --git a/packages/pyright-internal/src/tests/samples/solver31.py b/packages/pyright-internal/src/tests/samples/solver31.py index 0d0102035..5209ed763 100644 --- a/packages/pyright-internal/src/tests/samples/solver31.py +++ b/packages/pyright-internal/src/tests/samples/solver31.py @@ -8,12 +8,10 @@ T = TypeVar("T") class A(Generic[T]): - def __init__(self, i: Iterable[T]): - ... + def __init__(self, i: Iterable[T]): ... -def func1(i: Iterable[T]) -> T: - ... +def func1(i: Iterable[T]) -> T: ... reveal_type(func1([0] + [""]), expected_text="str | int") diff --git a/packages/pyright-internal/src/tests/samples/solver32.py b/packages/pyright-internal/src/tests/samples/solver32.py index 31d8e861f..82105b0f6 100644 --- a/packages/pyright-internal/src/tests/samples/solver32.py +++ b/packages/pyright-internal/src/tests/samples/solver32.py @@ -9,29 +9,23 @@ DT = TypeVar("DT", bound="DateTimeProto") class TimeDeltaProto(Protocol): - def __pos__(self) -> Self: - ... + def __pos__(self) -> Self: ... class DateTimeProto(Protocol[TD]): - def __add__(self, other: TD, /) -> Self: - ... + def __add__(self, other: TD, /) -> Self: ... - def __sub__(self, other: Self, /) -> TD: - ... + def __sub__(self, other: Self, /) -> TD: ... class TimeDelta: - def __pos__(self) -> Self: - ... + def __pos__(self) -> Self: ... class DateTime: - def __add__(self, other: bool | int) -> Self: - ... + def __add__(self, other: bool | int) -> Self: ... - def __sub__(self, other: "DateTime") -> TimeDelta: - ... + def __sub__(self, other: "DateTime") -> TimeDelta: ... def func1(__val: DT) -> DT: diff --git a/packages/pyright-internal/src/tests/samples/solver5.py b/packages/pyright-internal/src/tests/samples/solver5.py index 0b98ad8e4..1d361e8a4 100644 --- a/packages/pyright-internal/src/tests/samples/solver5.py +++ b/packages/pyright-internal/src/tests/samples/solver5.py @@ -3,8 +3,7 @@ # encounters are covariant or invariant. -def func1(value: object) -> bool: - ... +def func1(value: object) -> bool: ... v1 = filter(func1, ["b", "a", "r"]) diff --git a/packages/pyright-internal/src/tests/samples/solver6.py b/packages/pyright-internal/src/tests/samples/solver6.py index 2672a8fb0..70db5025a 100644 --- a/packages/pyright-internal/src/tests/samples/solver6.py +++ b/packages/pyright-internal/src/tests/samples/solver6.py @@ -15,8 +15,9 @@ def is_one(x: int) -> bool: v1 = ["a", "b", "c"] -def func1(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Iterator[_T]: - ... +def func1( + __function: Callable[[_T], Any], __iterable: Iterable[_T] +) -> Iterator[_T]: ... # This should be flagged as an error because nums is diff --git a/packages/pyright-internal/src/tests/samples/solver9.py b/packages/pyright-internal/src/tests/samples/solver9.py index 4a42e3adb..486e0c0a0 100644 --- a/packages/pyright-internal/src/tests/samples/solver9.py +++ b/packages/pyright-internal/src/tests/samples/solver9.py @@ -27,8 +27,7 @@ c = func2(None) class ClassA(Generic[_T1]): - def __init__(self, value: _T1) -> None: - ... + def __init__(self, value: _T1) -> None: ... @classmethod def get(cls: type[_T3]) -> type[_T3]: diff --git a/packages/pyright-internal/src/tests/samples/solverHigherOrder10.py b/packages/pyright-internal/src/tests/samples/solverHigherOrder10.py index 549100721..5cf168e94 100644 --- a/packages/pyright-internal/src/tests/samples/solverHigherOrder10.py +++ b/packages/pyright-internal/src/tests/samples/solverHigherOrder10.py @@ -7,12 +7,10 @@ A = TypeVar("A") B = TypeVar("B") -def func1(fn: Callable[[A, B], A], b: B) -> A: - ... +def func1(fn: Callable[[A, B], A], b: B) -> A: ... -def func2(a: A, x: A) -> A: - ... +def func2(a: A, x: A) -> A: ... def func3(a: A) -> A: diff --git a/packages/pyright-internal/src/tests/samples/solverHigherOrder11.py b/packages/pyright-internal/src/tests/samples/solverHigherOrder11.py index 30b04cee8..cb6f71bae 100644 --- a/packages/pyright-internal/src/tests/samples/solverHigherOrder11.py +++ b/packages/pyright-internal/src/tests/samples/solverHigherOrder11.py @@ -12,17 +12,14 @@ T = TypeVar("T") class Proto1(Protocol[T]): - def method(self, v: T) -> T: - ... + def method(self, v: T) -> T: ... class Impl1: - def method(self, v: T) -> T: - ... + def method(self, v: T) -> T: ... -def func1(a: Proto1[T], b: T) -> T: - ... +def func1(a: Proto1[T], b: T) -> T: ... v1 = func1(a=Impl1(), b="abc") diff --git a/packages/pyright-internal/src/tests/samples/solverHigherOrder2.py b/packages/pyright-internal/src/tests/samples/solverHigherOrder2.py index da1f2227c..4b1f5433b 100644 --- a/packages/pyright-internal/src/tests/samples/solverHigherOrder2.py +++ b/packages/pyright-internal/src/tests/samples/solverHigherOrder2.py @@ -16,8 +16,7 @@ def not_identity(x: Any) -> int: class Test(Generic[T]): - def fun(self, x: Iterable[T], f: Callable[[T], T]): - ... + def fun(self, x: Iterable[T], f: Callable[[T], T]): ... def caller(self, x: Iterable[T]): self.fun(x, identity) diff --git a/packages/pyright-internal/src/tests/samples/solverHigherOrder4.py b/packages/pyright-internal/src/tests/samples/solverHigherOrder4.py index bd0b79e85..d01a7c1a4 100644 --- a/packages/pyright-internal/src/tests/samples/solverHigherOrder4.py +++ b/packages/pyright-internal/src/tests/samples/solverHigherOrder4.py @@ -9,20 +9,16 @@ _T_co = TypeVar("_T_co", covariant=True) _U = TypeVar("_U") -class MyIterable(Protocol[_T_co]): - ... +class MyIterable(Protocol[_T_co]): ... -class MySupportsAbs(Protocol[_T_co]): - ... +class MySupportsAbs(Protocol[_T_co]): ... -def my_abs(x: MySupportsAbs[_T], /) -> _T: - ... +def my_abs(x: MySupportsAbs[_T], /) -> _T: ... -def my_map(a: Callable[[_T], _U], b: MyIterable[_T]) -> MyIterable[_U]: - ... +def my_map(a: Callable[[_T], _U], b: MyIterable[_T]) -> MyIterable[_U]: ... def func1(xs: MyIterable[MySupportsAbs[int]]): @@ -37,8 +33,7 @@ def ident(x: _U) -> _U: return x -def func2(__cb: Callable[[_T1], _T], __arg0: _T1) -> _T: - ... +def func2(__cb: Callable[[_T1], _T], __arg0: _T1) -> _T: ... x1_0 = func2(ident, "hi") @@ -52,8 +47,7 @@ _P = ParamSpec("_P") _R = TypeVar("_R") -def func3(__obj: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: - ... +def func3(__obj: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... x2_0 = func3(ident, "hi") diff --git a/packages/pyright-internal/src/tests/samples/solverHigherOrder5.py b/packages/pyright-internal/src/tests/samples/solverHigherOrder5.py index 6371c9d1e..2db68b32c 100644 --- a/packages/pyright-internal/src/tests/samples/solverHigherOrder5.py +++ b/packages/pyright-internal/src/tests/samples/solverHigherOrder5.py @@ -40,7 +40,7 @@ def triple_1( def triple_2( - f: tuple[Callable[[A], X], Callable[[B], Y], Callable[[C], Z]] + f: tuple[Callable[[A], X], Callable[[B], Y], Callable[[C], Z]], ) -> Callable[[A, B, C], tuple[X, Y, Z]]: def wrapped(a: A, b: B, c: C) -> tuple[X, Y, Z]: return f[0](a), f[1](b), f[2](c) @@ -166,7 +166,7 @@ reveal_type( def test_7( - g: Callable[[C], D] + g: Callable[[C], D], ) -> Callable[[Callable[[A], Callable[[B], C]]], Callable[[A], Callable[[B], D]]]: val6 = test_6(test_6)(test_6)(g) reveal_type( diff --git a/packages/pyright-internal/src/tests/samples/solverHigherOrder6.py b/packages/pyright-internal/src/tests/samples/solverHigherOrder6.py index e53a27767..9aa039747 100644 --- a/packages/pyright-internal/src/tests/samples/solverHigherOrder6.py +++ b/packages/pyright-internal/src/tests/samples/solverHigherOrder6.py @@ -23,24 +23,21 @@ v1 = min(1, max(2, 0.5)) reveal_type(v1, expected_text="float") -class Future(Generic[_T]): - ... +class Future(Generic[_T]): ... -def func1(future: Future[_T]) -> Future[_T]: - ... +def func1(future: Future[_T]) -> Future[_T]: ... -def func2(__fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: - ... +def func2( + __fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs +) -> Future[_T]: ... -def func3() -> int: - ... +def func3() -> int: ... -def func4(a: int, b: int) -> str: - ... +def func4(a: int, b: int) -> str: ... reveal_type(func1(func2(func3)), expected_text="Future[int]") @@ -49,8 +46,7 @@ reveal_type(func1(func2(func4, a=1, b=2)), expected_text="Future[str]") class Proto(Protocol): - def __call__(self, func: _T) -> _T: - ... + def __call__(self, func: _T) -> _T: ... def func5(cb: Proto, names: Any): diff --git a/packages/pyright-internal/src/tests/samples/solverHigherOrder8.py b/packages/pyright-internal/src/tests/samples/solverHigherOrder8.py index 746d62924..1d3d6275e 100644 --- a/packages/pyright-internal/src/tests/samples/solverHigherOrder8.py +++ b/packages/pyright-internal/src/tests/samples/solverHigherOrder8.py @@ -9,18 +9,15 @@ T = TypeVar("T") class Proto1(Protocol[P, R]): @classmethod - def collect(cls, *args: P.args, **kwargs: P.kwargs) -> R: - ... + def collect(cls, *args: P.args, **kwargs: P.kwargs) -> R: ... class Class1: @classmethod - def collect(cls, n: type[T]) -> Callable[[Callable[[T], int]], None]: - ... + def collect(cls, n: type[T]) -> Callable[[Callable[[T], int]], None]: ... -def func1(a: Proto1[P, R], *args: P.args, **kwargs: P.kwargs) -> R: - ... +def func1(a: Proto1[P, R], *args: P.args, **kwargs: P.kwargs) -> R: ... reveal_type(func1(Class1, float), expected_text="((float) -> int) -> None") diff --git a/packages/pyright-internal/src/tests/samples/solverHigherOrder9.py b/packages/pyright-internal/src/tests/samples/solverHigherOrder9.py index f10da17e3..fb929e137 100644 --- a/packages/pyright-internal/src/tests/samples/solverHigherOrder9.py +++ b/packages/pyright-internal/src/tests/samples/solverHigherOrder9.py @@ -10,20 +10,17 @@ S = TypeVar("S") T = TypeVar("T") -def deco1(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: - ... +def deco1(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: ... -def func1(val1: T, val2: S, val3: S) -> T: - ... +def func1(val1: T, val2: S, val3: S) -> T: ... reveal_type(deco1(func1, val1=1, val2=3, val3="s"), expected_text="int") reveal_type(deco1(func1, 1, 3, "s"), expected_text="int") -def func2(val1: T, val2: S) -> T | list[S]: - ... +def func2(val1: T, val2: S) -> T | list[S]: ... reveal_type(deco1(func2, val1=1, val2="s"), expected_text="int | list[str]") diff --git a/packages/pyright-internal/src/tests/samples/solverLiteral2.py b/packages/pyright-internal/src/tests/samples/solverLiteral2.py index 7134322ec..7372805b1 100644 --- a/packages/pyright-internal/src/tests/samples/solverLiteral2.py +++ b/packages/pyright-internal/src/tests/samples/solverLiteral2.py @@ -18,4 +18,3 @@ def func2() -> None: # This should generate an error. x.append("not foo") print(foo_list) - diff --git a/packages/pyright-internal/src/tests/samples/solverScoring1.py b/packages/pyright-internal/src/tests/samples/solverScoring1.py index 2a9b94b76..3ecb1137b 100644 --- a/packages/pyright-internal/src/tests/samples/solverScoring1.py +++ b/packages/pyright-internal/src/tests/samples/solverScoring1.py @@ -24,21 +24,17 @@ def func3(input1: list[str]): def func4( - func: Callable[[], T] | Callable[[T], None] | list[T] | dict[str, T] | T -) -> T: - ... + func: Callable[[], T] | Callable[[T], None] | list[T] | dict[str, T] | T, +) -> T: ... -def func5(func: Callable[[], T]) -> T: - ... +def func5(func: Callable[[], T]) -> T: ... -def func6(val: str) -> None: - ... +def func6(val: str) -> None: ... -def func7() -> str: - ... +def func7() -> str: ... reveal_type(func4([""]), expected_text="str") diff --git a/packages/pyright-internal/src/tests/samples/solverScoring2.py b/packages/pyright-internal/src/tests/samples/solverScoring2.py index 7f4ad0dd3..e7e134ad6 100644 --- a/packages/pyright-internal/src/tests/samples/solverScoring2.py +++ b/packages/pyright-internal/src/tests/samples/solverScoring2.py @@ -8,20 +8,17 @@ from typing import Any, Generic, TypeVar, Union T1 = TypeVar("T1") -class Wrapper(Generic[T1]): - ... +class Wrapper(Generic[T1]): ... -def ensure_wrapped(item: Union[T1, Wrapper[T1]]) -> Wrapper[T1]: - ... +def ensure_wrapped(item: Union[T1, Wrapper[T1]]) -> Wrapper[T1]: ... def some_func(x: Wrapper[T1]) -> Wrapper[T1]: return ensure_wrapped(x) -def func1a(value: list[Union[T1, list[T1]]]) -> T1: - ... +def func1a(value: list[Union[T1, list[T1]]]) -> T1: ... def func2a(value: list[Union[float, list[float]]]): @@ -39,8 +36,7 @@ def func4a(value: list[Union[float, str, list[Union[float, str]]]]): reveal_type(x, expected_text="float | str") -def func1b(value: list[Union[int, list[T1]]]) -> T1: - ... +def func1b(value: list[Union[int, list[T1]]]) -> T1: ... def func2b(value: list[Union[int, list[float]]]): @@ -53,8 +49,7 @@ def func3b(value: list[Union[str, list[float]]]): func1b(value) -def ensure_list(value: Union[T1, list[T1]]) -> list[T1]: - ... +def ensure_list(value: Union[T1, list[T1]]) -> list[T1]: ... def func4( diff --git a/packages/pyright-internal/src/tests/samples/solverScoring3.py b/packages/pyright-internal/src/tests/samples/solverScoring3.py index 5cd2d1d5e..9f0711f11 100644 --- a/packages/pyright-internal/src/tests/samples/solverScoring3.py +++ b/packages/pyright-internal/src/tests/samples/solverScoring3.py @@ -6,8 +6,7 @@ from typing import TypeVar T = TypeVar("T") -def to_list(t: list[T] | T) -> list[T]: - ... +def to_list(t: list[T] | T) -> list[T]: ... x = to_list([1, 2, 3]) diff --git a/packages/pyright-internal/src/tests/samples/solverScoring4.py b/packages/pyright-internal/src/tests/samples/solverScoring4.py index 8af28608a..e30eaeee6 100644 --- a/packages/pyright-internal/src/tests/samples/solverScoring4.py +++ b/packages/pyright-internal/src/tests/samples/solverScoring4.py @@ -10,8 +10,7 @@ TResult = TypeVar("TResult") class ResolveFunc(Protocol[T_contra]): - def __call__(self, resolve_value: T_contra) -> None: - ... + def __call__(self, resolve_value: T_contra) -> None: ... FullfillFunc = Callable[[T], TResult | "Promise[TResult]"] @@ -20,14 +19,11 @@ ExecutorFunc = Callable[[ResolveFunc[T]], None] class Promise(Generic[T]): @staticmethod - def resolve(resolve_value: S) -> "Promise[S]": - ... + def resolve(resolve_value: S) -> "Promise[S]": ... - def __init__(self, executor_func: ExecutorFunc[T]) -> None: - ... + def __init__(self, executor_func: ExecutorFunc[T]) -> None: ... - def then(self, onfullfilled: FullfillFunc[T, TResult]) -> "Promise[TResult]": - ... + def then(self, onfullfilled: FullfillFunc[T, TResult]) -> "Promise[TResult]": ... Promise.resolve(1).then(lambda result: reveal_type(result, expected_text="int")) diff --git a/packages/pyright-internal/src/tests/samples/specialization1.py b/packages/pyright-internal/src/tests/samples/specialization1.py index 643ee5c06..482ee9db7 100644 --- a/packages/pyright-internal/src/tests/samples/specialization1.py +++ b/packages/pyright-internal/src/tests/samples/specialization1.py @@ -23,14 +23,11 @@ class Moo(Generic[_T1]): class Foo: - def __init__(self) -> None: - ... + def __init__(self) -> None: ... - def m1(self, a: Moo[A]) -> None: - ... + def m1(self, a: Moo[A]) -> None: ... - def m2(self, b: Moo[B]) -> None: - ... + def m2(self, b: Moo[B]) -> None: ... a = Moo[A]() diff --git a/packages/pyright-internal/src/tests/samples/staticExpression2.py b/packages/pyright-internal/src/tests/samples/staticExpression2.py index a65ffad90..011c1074c 100644 --- a/packages/pyright-internal/src/tests/samples/staticExpression2.py +++ b/packages/pyright-internal/src/tests/samples/staticExpression2.py @@ -13,13 +13,11 @@ if sys.version_info < (3, 5, 2): @overload -def from_json_timestamp(ts: int) -> datetime: - ... +def from_json_timestamp(ts: int) -> datetime: ... @overload -def from_json_timestamp(ts: None) -> None: - ... +def from_json_timestamp(ts: None) -> None: ... def from_json_timestamp(ts: Optional[int]) -> Optional[datetime]: diff --git a/packages/pyright-internal/src/tests/samples/super13.py b/packages/pyright-internal/src/tests/samples/super13.py index 4556b503e..3b624b527 100644 --- a/packages/pyright-internal/src/tests/samples/super13.py +++ b/packages/pyright-internal/src/tests/samples/super13.py @@ -1,5 +1,6 @@ # This sample tests the use of `super` outside of a method. + def func1(t: type) -> super: return super(t, t) diff --git a/packages/pyright-internal/src/tests/samples/super2.py b/packages/pyright-internal/src/tests/samples/super2.py index 478ea53d4..bc59ca4d0 100644 --- a/packages/pyright-internal/src/tests/samples/super2.py +++ b/packages/pyright-internal/src/tests/samples/super2.py @@ -30,18 +30,15 @@ reveal_type(b2, expected_text="B") class C: - def __init__(self) -> None: - ... + def __init__(self) -> None: ... class CChild(C): - def __init__(self, name: str) -> None: - ... + def __init__(self, name: str) -> None: ... class D: - def __init__(self, name: str, num: int): - ... + def __init__(self, name: str, num: int): ... class DChild1(CChild, D): diff --git a/packages/pyright-internal/src/tests/samples/super4.py b/packages/pyright-internal/src/tests/samples/super4.py index d88b2fd21..f3a7eb581 100644 --- a/packages/pyright-internal/src/tests/samples/super4.py +++ b/packages/pyright-internal/src/tests/samples/super4.py @@ -25,8 +25,7 @@ reveal_type(Child1.construct(), expected_text="Child1") class Parent2: @classmethod - def construct(cls: type[_T2]) -> _T2: - ... + def construct(cls: type[_T2]) -> _T2: ... class Child2(Parent2): diff --git a/packages/pyright-internal/src/tests/samples/super7.py b/packages/pyright-internal/src/tests/samples/super7.py index 8d1987de4..34cae1bf2 100644 --- a/packages/pyright-internal/src/tests/samples/super7.py +++ b/packages/pyright-internal/src/tests/samples/super7.py @@ -8,8 +8,7 @@ T = TypeVar("T") class BaseClass: - def my_method(self, value: int) -> int: - ... + def my_method(self, value: int) -> int: ... class SubClass(BaseClass): @@ -57,12 +56,10 @@ class SubClass(BaseClass): return super(__class__, self).my_method(self, value) -class A(Generic[T]): - ... +class A(Generic[T]): ... -class B(Generic[T]): - ... +class B(Generic[T]): ... class C(A[int], B[T]): diff --git a/packages/pyright-internal/src/tests/samples/super9.py b/packages/pyright-internal/src/tests/samples/super9.py index e112b8b1c..9b21ff73d 100644 --- a/packages/pyright-internal/src/tests/samples/super9.py +++ b/packages/pyright-internal/src/tests/samples/super9.py @@ -8,12 +8,10 @@ _T = TypeVar("_T") class Foo(Generic[_T]): - def __init__(self, x: _T = 1) -> None: - ... + def __init__(self, x: _T = 1) -> None: ... -class Bar(Foo[int]): - ... +class Bar(Foo[int]): ... class Baz(Bar): diff --git a/packages/pyright-internal/src/tests/samples/totalOrdering1.py b/packages/pyright-internal/src/tests/samples/totalOrdering1.py index 8c6882e34..7b9f64893 100644 --- a/packages/pyright-internal/src/tests/samples/totalOrdering1.py +++ b/packages/pyright-internal/src/tests/samples/totalOrdering1.py @@ -7,8 +7,7 @@ from functools import total_ordering class ClassA: val1: int - def __gt__(self, other: object) -> bool: - ... + def __gt__(self, other: object) -> bool: ... a = ClassA() diff --git a/packages/pyright-internal/src/tests/samples/tryExcept11.py b/packages/pyright-internal/src/tests/samples/tryExcept11.py index 41863e36d..35f9bdc9a 100644 --- a/packages/pyright-internal/src/tests/samples/tryExcept11.py +++ b/packages/pyright-internal/src/tests/samples/tryExcept11.py @@ -2,6 +2,7 @@ # a try/except and is referenced within the finally clause. This ensures # that the "finally gate" logic is reentrant. + def func1(): func2() diff --git a/packages/pyright-internal/src/tests/samples/tuple1.py b/packages/pyright-internal/src/tests/samples/tuple1.py index b20a1edba..fdfdfa843 100644 --- a/packages/pyright-internal/src/tests/samples/tuple1.py +++ b/packages/pyright-internal/src/tests/samples/tuple1.py @@ -1,7 +1,8 @@ # This sample file tests various aspects of type analysis for tuples. import os -from typing import Any, Callable +from typing import Any, Callable, Never + from typing_extensions import ( # pyright: ignore[reportMissingModuleSource] TypeVarTuple, Unpack, @@ -270,3 +271,13 @@ def func19(a: tuple[int, ...], b: tuple[int, *tuple[int, ...]]): # This should generate an error. b5: tuple[int, int, *tuple[int, ...]] = b + + +def func20(v: tuple[Never]): + # This should generate an error. + x1: tuple[Never] = (1,) + + # This should generate an error. + x2: tuple[Never] = () + + x3: tuple[Never] = v diff --git a/packages/pyright-internal/src/tests/samples/tuple3.py b/packages/pyright-internal/src/tests/samples/tuple3.py index bfcc329da..ffaf610ce 100644 --- a/packages/pyright-internal/src/tests/samples/tuple3.py +++ b/packages/pyright-internal/src/tests/samples/tuple3.py @@ -4,8 +4,7 @@ from typing import Callable -def func1(values: tuple[str, ...]): - ... +def func1(values: tuple[str, ...]): ... # This should generate an error. @@ -15,16 +14,13 @@ func1(("", False)) func1((False, "")) -def func2(x: tuple[int]) -> None: - ... +def func2(x: tuple[int]) -> None: ... -def func3(x: tuple[()]) -> None: - ... +def func3(x: tuple[()]) -> None: ... -def func4(x: tuple[int, ...]) -> None: - ... +def func4(x: tuple[int, ...]) -> None: ... c1: Callable[[tuple[int]], None] diff --git a/packages/pyright-internal/src/tests/samples/tuple7.py b/packages/pyright-internal/src/tests/samples/tuple7.py index 13aa52fec..09197779c 100644 --- a/packages/pyright-internal/src/tests/samples/tuple7.py +++ b/packages/pyright-internal/src/tests/samples/tuple7.py @@ -7,8 +7,7 @@ _T = TypeVar("_T") class ClassA(tuple[int, str, int, _T]): - def __new__(cls) -> Self: - ... + def __new__(cls) -> Self: ... objA = ClassA[complex]() @@ -34,8 +33,7 @@ for aaa in objA: class ClassB(tuple[_T, ...]): - def __new__(cls) -> Self: - ... + def __new__(cls) -> Self: ... objB = ClassB[complex]() diff --git a/packages/pyright-internal/src/tests/samples/tuple8.py b/packages/pyright-internal/src/tests/samples/tuple8.py index 449b9bb15..48acf2d09 100644 --- a/packages/pyright-internal/src/tests/samples/tuple8.py +++ b/packages/pyright-internal/src/tests/samples/tuple8.py @@ -8,8 +8,7 @@ _T = TypeVar("_T") class ClassA(tuple[int, str, int, _T]): - def __new__(cls) -> Self: - ... + def __new__(cls) -> Self: ... objA = ClassA[complex]() @@ -38,8 +37,7 @@ for aaa in objA: class ClassB(tuple[_T, ...]): - def __new__(cls) -> Self: - ... + def __new__(cls) -> Self: ... objB = ClassB[complex]() @@ -89,8 +87,7 @@ t3_2: TupleTypeAlias2 = (3, 4) T = TypeVar("T") -def baz(v: Iterable[T]) -> tuple[T]: - ... +def baz(v: Iterable[T]) -> tuple[T]: ... def qux() -> None: diff --git a/packages/pyright-internal/src/tests/samples/typeAlias10.py b/packages/pyright-internal/src/tests/samples/typeAlias10.py index 06d3a00e4..cd8aced2e 100644 --- a/packages/pyright-internal/src/tests/samples/typeAlias10.py +++ b/packages/pyright-internal/src/tests/samples/typeAlias10.py @@ -8,8 +8,7 @@ from typing import Any, Generic, TypeAlias, TypeVar _T = TypeVar("_T") -class A(Generic[_T]): - ... +class A(Generic[_T]): ... # This should generate an error if reportMissingTypeArgument is enabled. @@ -33,8 +32,7 @@ v4: C[int] class D(Generic[_T]): - def __getitem__(self, key: Any) -> int: - ... + def __getitem__(self, key: Any) -> int: ... D_Alias = D[_T] diff --git a/packages/pyright-internal/src/tests/samples/typeAlias14.py b/packages/pyright-internal/src/tests/samples/typeAlias14.py index 4020747ca..f0d963128 100644 --- a/packages/pyright-internal/src/tests/samples/typeAlias14.py +++ b/packages/pyright-internal/src/tests/samples/typeAlias14.py @@ -10,15 +10,13 @@ TA1 = Callable[[T], T] TA2 = Callable[[T], T] | Callable[P, T] -def f1() -> TA1: - ... +def f1() -> TA1: ... reveal_type(f1(), expected_text="(Unknown) -> Unknown") -def f2() -> TA2: - ... +def f2() -> TA2: ... g2 = f2() diff --git a/packages/pyright-internal/src/tests/samples/typeAlias18.py b/packages/pyright-internal/src/tests/samples/typeAlias18.py index af786c89d..b44b35498 100644 --- a/packages/pyright-internal/src/tests/samples/typeAlias18.py +++ b/packages/pyright-internal/src/tests/samples/typeAlias18.py @@ -19,18 +19,15 @@ A_Alias_2: TypeAlias = A_Alias_1[T2 | int] # This should generate an error because the variance is incompatible. -class A_1(A_Alias_1[T2]): - ... +class A_1(A_Alias_1[T2]): ... # This should generate an error because the variance is incompatible. -class A_2(A_Alias_2[T2]): - ... +class A_2(A_Alias_2[T2]): ... # This should generate an error because the variance is incompatible. -class A_3(A[T2]): - ... +class A_3(A[T2]): ... class B(Generic[T1, T2]): @@ -41,5 +38,4 @@ B_Alias_1 = B[T2, T3] # This should generate an error because the variance is incompatible. -class C(B_Alias_1[T3, T2]): - ... +class C(B_Alias_1[T3, T2]): ... diff --git a/packages/pyright-internal/src/tests/samples/typeAlias8.py b/packages/pyright-internal/src/tests/samples/typeAlias8.py index 27c0d150a..697f9342c 100644 --- a/packages/pyright-internal/src/tests/samples/typeAlias8.py +++ b/packages/pyright-internal/src/tests/samples/typeAlias8.py @@ -10,8 +10,7 @@ F = Callable[[T], T] def func1() -> F[T]: - def g(x: T) -> T: - ... + def g(x: T) -> T: ... return g diff --git a/packages/pyright-internal/src/tests/samples/typeAliasStatement1.py b/packages/pyright-internal/src/tests/samples/typeAliasStatement1.py index 0c3298f8d..cc8bb7388 100644 --- a/packages/pyright-internal/src/tests/samples/typeAliasStatement1.py +++ b/packages/pyright-internal/src/tests/samples/typeAliasStatement1.py @@ -37,8 +37,7 @@ else: type TA7 = int -def func1() -> type[int]: - ... +def func1() -> type[int]: ... # This should generate an error because a call expression is not diff --git a/packages/pyright-internal/src/tests/samples/typeAliasStatement4.py b/packages/pyright-internal/src/tests/samples/typeAliasStatement4.py index 1a8f9b1a3..be9698675 100644 --- a/packages/pyright-internal/src/tests/samples/typeAliasStatement4.py +++ b/packages/pyright-internal/src/tests/samples/typeAliasStatement4.py @@ -35,5 +35,3 @@ type TA6 = "TA7" type TA7 = TA6 type JSONNode = list[JSONNode] | dict[str, JSONNode] | str | float - - diff --git a/packages/pyright-internal/src/tests/samples/typeCheckOnly1.py b/packages/pyright-internal/src/tests/samples/typeCheckOnly1.py index 15eb4be15..44a4fa45e 100644 --- a/packages/pyright-internal/src/tests/samples/typeCheckOnly1.py +++ b/packages/pyright-internal/src/tests/samples/typeCheckOnly1.py @@ -30,8 +30,7 @@ if TYPE_CHECKING: pass @type_check_only - def func1() -> None: - ... + def func1() -> None: ... # This should generate an error. diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowing5.py b/packages/pyright-internal/src/tests/samples/typeNarrowing5.py index c41a40d45..d457bd315 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowing5.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowing5.py @@ -22,8 +22,7 @@ def func2(struct: Any): T = TypeVar("T") -class A(Generic[T]): - ... +class A(Generic[T]): ... def func3(val: A[Any]): diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingIn2.py b/packages/pyright-internal/src/tests/samples/typeNarrowingIn2.py index 77e01de3f..2810c553b 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingIn2.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingIn2.py @@ -23,4 +23,3 @@ def func2(x: MyEnum): reveal_type(x, expected_text="Literal[MyEnum.A, MyEnum.B]") else: reveal_type(x, expected_text="Literal[MyEnum.C]") - diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingIsClass1.py b/packages/pyright-internal/src/tests/samples/typeNarrowingIsClass1.py index 96fca0de4..71633b92f 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingIsClass1.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingIsClass1.py @@ -5,17 +5,14 @@ from typing import Any, TypeVar, final @final -class A: - ... +class A: ... @final -class B: - ... +class B: ... -class C: - ... +class C: ... def func1(x: type[A] | type[B] | None | int): @@ -34,7 +31,7 @@ def func2(x: type[A] | type[B] | None | int, y: type[A]): def func3(x: type[A] | type[B] | Any): if x is A: - reveal_type(x, expected_text="type[A] | Any") + reveal_type(x, expected_text="type[A]") else: reveal_type(x, expected_text="type[B] | Any") @@ -51,7 +48,7 @@ T = TypeVar("T") def func5(x: type[A] | type[B] | type[T]) -> type[A] | type[B] | type[T]: if x is A: - reveal_type(x, expected_text="type[A] | type[T@func5]") + reveal_type(x, expected_text="type[A] | type[A]*") else: reveal_type(x, expected_text="type[B] | type[T@func5]") @@ -63,3 +60,10 @@ def func6(x: type): reveal_type(x, expected_text="type[str]") else: reveal_type(x, expected_text="type") + + +def func7(x: type[A | B]): + if x is A: + reveal_type(x, expected_text="type[A]") + else: + reveal_type(x, expected_text="type[B]") diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingIsNone1.py b/packages/pyright-internal/src/tests/samples/typeNarrowingIsNone1.py index 87a95cc11..32789a8c5 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingIsNone1.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingIsNone1.py @@ -71,8 +71,7 @@ def func6(x: Any | object | None): class NoneProto(Protocol): - def __bool__(self) -> Literal[False]: - ... + def __bool__(self) -> Literal[False]: ... def func7(x: NoneProto | None): diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py index df48c7b2c..458b56106 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py @@ -130,8 +130,7 @@ def func7(a: Union[list[int], int]): # on isinstance checks. -class Base1: - ... +class Base1: ... class Sub1_1(Base1): @@ -183,14 +182,12 @@ def func10(val: Sub2[str] | Base2[str, float]): @runtime_checkable class Proto1(Protocol): - def f0(self, /) -> None: - ... + def f0(self, /) -> None: ... @runtime_checkable class Proto2(Proto1, Protocol): - def f1(self, /) -> None: - ... + def f1(self, /) -> None: ... def func11(x: Proto1): diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance15.py b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance15.py index faaeac817..1562a3f43 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance15.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance15.py @@ -4,8 +4,7 @@ from typing import TypeVar, Generic -class Operator: - ... +class Operator: ... OpType = TypeVar("OpType", bound=Operator) diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance5.py b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance5.py index 442796193..cdc476ef1 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance5.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance5.py @@ -4,28 +4,24 @@ from typing import Callable, Sequence, TypeVar -class A: - ... +class A: ... class B: - def __call__(self, x: str) -> int: - ... + def __call__(self, x: str) -> int: ... -class C: - ... +class C: ... -class D(C): - ... +class D(C): ... TCall1 = TypeVar("TCall1", bound=Callable[..., int]) def func1( - obj: Callable[[int, str], int] | list[int] | A | B | C | D | TCall1 + obj: Callable[[int, str], int] | list[int] | A | B | C | D | TCall1, ) -> TCall1 | None: if isinstance(obj, (Callable, Sequence, C)): reveal_type( diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance6.py b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance6.py index 898a5d663..099f3356b 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance6.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance6.py @@ -7,12 +7,10 @@ from typing import Any, Generic, Iterable, Sequence, TypeVar _T1 = TypeVar("_T1") -class ParentA(Generic[_T1]): - ... +class ParentA(Generic[_T1]): ... -class ChildA1(ParentA[_T1]): - ... +class ChildA1(ParentA[_T1]): ... def func1(a: ParentA[int], b: ParentA[str] | ParentA[complex]) -> None: @@ -79,12 +77,10 @@ class ParentD(Generic[_T1]): x: _T1 -class ChildD1(ParentD[_T1]): - ... +class ChildD1(ParentD[_T1]): ... -class ChildD2(ParentD[int]): - ... +class ChildD2(ParentD[int]): ... def func7(a: ParentD[_T1]) -> _T1 | None: diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance8.py b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance8.py index 52fa8efa9..0649762c8 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance8.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance8.py @@ -10,8 +10,7 @@ from typing import Any class Base(ABC): @abstractmethod - def f(self) -> None: - ... + def f(self) -> None: ... def func1(cls: Any): diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingLiteral2.py b/packages/pyright-internal/src/tests/samples/typeNarrowingLiteral2.py index 7d08f2805..c4f861947 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingLiteral2.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingLiteral2.py @@ -27,12 +27,10 @@ def func2(a: SomeEnum) -> Literal[3]: return a.value -def must_be_true(a: Literal[True]): - ... +def must_be_true(a: Literal[True]): ... -def must_be_false(a: Literal[False]): - ... +def must_be_false(a: Literal[False]): ... def func3(a: bool): diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingLocalConst1.py b/packages/pyright-internal/src/tests/samples/typeNarrowingLocalConst1.py index adf1c4749..be56f6bce 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingLocalConst1.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingLocalConst1.py @@ -85,12 +85,10 @@ def func6(x: A | B) -> None: x = B() -def get_string() -> str: - ... +def get_string() -> str: ... -def get_optional_string() -> str | None: - ... +def get_optional_string() -> str | None: ... def func7(val: str | None = None): diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingNoneMember1.py b/packages/pyright-internal/src/tests/samples/typeNarrowingNoneMember1.py index 7bdec48b6..4ad493656 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingNoneMember1.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingNoneMember1.py @@ -47,8 +47,7 @@ def func2(a: Union[UnionFirst, StrSecond]): class A: @property - def prop1(self) -> int | None: - ... + def prop1(self) -> int | None: ... member1: None member2: int | None @@ -58,8 +57,7 @@ class A: class B: @property - def prop1(self) -> int: - ... + def prop1(self) -> int: ... member1: int member2: int | None diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingTypeEquals1.py b/packages/pyright-internal/src/tests/samples/typeNarrowingTypeEquals1.py index 0e16b89d3..137618b9d 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingTypeEquals1.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingTypeEquals1.py @@ -93,12 +93,10 @@ def func7(val: Any): reveal_type(val, expected_text="int | Any") -class CParent: - ... +class CParent: ... -class CChild(CParent): - ... +class CChild(CParent): ... _TC = TypeVar("_TC", bound=CParent) diff --git a/packages/pyright-internal/src/tests/samples/typeNarrowingTypeIs1.py b/packages/pyright-internal/src/tests/samples/typeNarrowingTypeIs1.py index e4bd834cb..94b8af0cc 100644 --- a/packages/pyright-internal/src/tests/samples/typeNarrowingTypeIs1.py +++ b/packages/pyright-internal/src/tests/samples/typeNarrowingTypeIs1.py @@ -93,12 +93,10 @@ def func7(val: Any): reveal_type(val, expected_text="int | Any") -class CParent: - ... +class CParent: ... -class CChild(CParent): - ... +class CChild(CParent): ... _TC = TypeVar("_TC", bound=CParent) diff --git a/packages/pyright-internal/src/tests/samples/typeParams2.py b/packages/pyright-internal/src/tests/samples/typeParams2.py index 1e404c126..0fa58aa74 100644 --- a/packages/pyright-internal/src/tests/samples/typeParams2.py +++ b/packages/pyright-internal/src/tests/samples/typeParams2.py @@ -3,10 +3,8 @@ # is < 3.12. # This should generate an error if <3.12 -class ClassA[T, S]: - ... +class ClassA[T, S]: ... + # This should generate an error if <3.12 -def func1[T, S](): - ... - +def func1[T, S](): ... diff --git a/packages/pyright-internal/src/tests/samples/typeParams4.py b/packages/pyright-internal/src/tests/samples/typeParams4.py index 00c270398..f495299d5 100644 --- a/packages/pyright-internal/src/tests/samples/typeParams4.py +++ b/packages/pyright-internal/src/tests/samples/typeParams4.py @@ -1,21 +1,17 @@ -# This sample tests errors related to the use of a Generic +# This sample tests errors related to the use of a Generic # or Protocol base class with PEP 695 type parameter syntax. from typing import Generic, Protocol + # This should generate an error because Generic should not # be used with type parameter syntax. -class ClassA[T](Generic[T]): - ... +class ClassA[T](Generic[T]): ... -class ClassB[T](Protocol): - ... +class ClassB[T](Protocol): ... # This should generate an error because Protocol should not be used # with type parameters when used with type parameter syntax. -class ClassC[T](Protocol[T]): - ... - - \ No newline at end of file +class ClassC[T](Protocol[T]): ... diff --git a/packages/pyright-internal/src/tests/samples/typeParams6.py b/packages/pyright-internal/src/tests/samples/typeParams6.py index 7d187ea91..244afb3ed 100644 --- a/packages/pyright-internal/src/tests/samples/typeParams6.py +++ b/packages/pyright-internal/src/tests/samples/typeParams6.py @@ -8,19 +8,16 @@ T1 = TypeVar("T1") T2 = TypeVar("T2") T4 = TypeVar("T4") + # This should generate an error because traditional type variables # like T1 cannot be combined with new-style type parameters. -class ClassA[T3](dict[T1, T3]): - ... +class ClassA[T3](dict[T1, T3]): ... class ClassB(Generic[T1]): class ClassC[T2](dict[T1, T2]): - def method1[T3](self, a: T1, b: T2, c: T3) -> T1 | T2 | T3: - ... + def method1[T3](self, a: T1, b: T2, c: T3) -> T1 | T2 | T3: ... # This should generate an error because traditional type variables # like T4 cannot be combined with new-style type parameters. - def method2[T3](self, a: T3, b: T4) -> T3 | T4: - ... - + def method2[T3](self, a: T3, b: T4) -> T3 | T4: ... diff --git a/packages/pyright-internal/src/tests/samples/typeParams7.py b/packages/pyright-internal/src/tests/samples/typeParams7.py index c449e426c..2509b4d99 100644 --- a/packages/pyright-internal/src/tests/samples/typeParams7.py +++ b/packages/pyright-internal/src/tests/samples/typeParams7.py @@ -1,13 +1,13 @@ # This sample tests the handling of bound and constrained type parameters # as specified in PEP 695 type parameter statements. -class ClassA[**P, R: str]: - ... + +class ClassA[**P, R: str]: ... A1 = ClassA[..., str] -# This should generate an error because str isn't a valid +# This should generate an error because str isn't a valid # specialization for a ParamSpec. A2 = ClassA[str, str] @@ -17,13 +17,16 @@ A3 = ClassA[[str], str] # to the bound. A4 = ClassA[..., int] + class StrSubclass(str): ... + A5 = ClassA[..., StrSubclass] class ClassB[X: (int, str), Y](dict[Y, X]): ... + B1 = ClassB[int, int] # This should generate an error because float doesn't conform @@ -31,8 +34,8 @@ B1 = ClassB[int, int] B2 = ClassB[float, float] -class ClassC[*Ts]: - ... +class ClassC[*Ts]: ... + C1 = ClassC[str, str] diff --git a/packages/pyright-internal/src/tests/samples/typePrinter1.py b/packages/pyright-internal/src/tests/samples/typePrinter1.py index 33a729ed7..5f2ecfa64 100644 --- a/packages/pyright-internal/src/tests/samples/typePrinter1.py +++ b/packages/pyright-internal/src/tests/samples/typePrinter1.py @@ -5,13 +5,11 @@ from . import typePrinter2 class A: - class Inner: - ... + class Inner: ... class B: - class Inner: - ... + class Inner: ... def func1(v: A.Inner | None): @@ -22,8 +20,7 @@ def func2(v: A.Inner | B.Inner | None): reveal_type(v, expected_text="typePrinter1.A.Inner | typePrinter1.B.Inner | None") -class IntOrStr: - ... +class IntOrStr: ... def func3(v: typePrinter2.IntOrStr | IntOrStr | None): diff --git a/packages/pyright-internal/src/tests/samples/typePromotions1.py b/packages/pyright-internal/src/tests/samples/typePromotions1.py index 6b6b774b6..ef13b5686 100644 --- a/packages/pyright-internal/src/tests/samples/typePromotions1.py +++ b/packages/pyright-internal/src/tests/samples/typePromotions1.py @@ -15,8 +15,7 @@ def func2(mem_view_val: memoryview, byte_array_val: bytearray): v2: bytes = byte_array_val -class IntSubclass(int): - ... +class IntSubclass(int): ... def func3(x: IntSubclass) -> float: diff --git a/packages/pyright-internal/src/tests/samples/typeVar10.py b/packages/pyright-internal/src/tests/samples/typeVar10.py index c58319b48..e82546733 100644 --- a/packages/pyright-internal/src/tests/samples/typeVar10.py +++ b/packages/pyright-internal/src/tests/samples/typeVar10.py @@ -5,13 +5,11 @@ from typing import TypeVar class A: - def method(self, x: "A") -> "A": - ... + def method(self, x: "A") -> "A": ... class B: - def method(self, x: "B") -> "B": - ... + def method(self, x: "B") -> "B": ... T = TypeVar("T", A, B) diff --git a/packages/pyright-internal/src/tests/samples/typeVar4.py b/packages/pyright-internal/src/tests/samples/typeVar4.py index afc8da69d..69813077a 100644 --- a/packages/pyright-internal/src/tests/samples/typeVar4.py +++ b/packages/pyright-internal/src/tests/samples/typeVar4.py @@ -38,8 +38,7 @@ class Foo(Generic[_T, _T_co, _T_contra]): # This should generate an error because contravariant # TypeVars are not allowed for return parameters. - def func8(self) -> _T_contra: - ... + def func8(self) -> _T_contra: ... # This should generate an error because contravariant # TypeVars are not allowed for return parameters. diff --git a/packages/pyright-internal/src/tests/samples/typeVar7.py b/packages/pyright-internal/src/tests/samples/typeVar7.py index 65cbefa3f..3ab94d8fe 100644 --- a/packages/pyright-internal/src/tests/samples/typeVar7.py +++ b/packages/pyright-internal/src/tests/samples/typeVar7.py @@ -137,19 +137,15 @@ def custom_add(a: _T3, b: _T4) -> float: class Thing1: - def __add__(self, value: float) -> "Thing1": - ... + def __add__(self, value: float) -> "Thing1": ... - def __radd__(self, value: float) -> "Thing1": - ... + def __radd__(self, value: float) -> "Thing1": ... class Thing2: - def __add__(self, value: float) -> "Thing2": - ... + def __add__(self, value: float) -> "Thing2": ... - def __radd__(self, value: float) -> "Thing2": - ... + def __radd__(self, value: float) -> "Thing2": ... TThing = TypeVar("TThing", Thing1, Thing2) diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefault2.py b/packages/pyright-internal/src/tests/samples/typeVarDefault2.py index 754e4d05a..ccb64c2f5 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefault2.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefault2.py @@ -2,7 +2,7 @@ # in PEP 696 (default types for TypeVarLike). from typing import Any, ParamSpec, TypeVar, Unpack -from typing_extensions import TypeVarTuple # pyright: ignore[reportMissingModuleSource] +from typing_extensions import TypeVarTuple # pyright: ignore[reportMissingModuleSource] T1 = TypeVar("T1") Ts1 = TypeVarTuple("Ts1") @@ -12,80 +12,105 @@ P1 = ParamSpec("P1") # This should generate an error because default must be a type expression. class ClassT1[T = 3]: ... + class ClassT2[T: float = int]: ... + # This should generate an error because default must be a subtype of bound. class ClassT3[T: int = float]: ... + class ClassT4[T: list[Any] = list[int]]: ... + class ClassT5[T: (bytes, str) = str]: ... + # This should generate an error because str | bytes isn't one of the constrained types. class ClassT6[T: (bytes, str) = str | bytes]: ... + # This should generate an error because T1 is not a valid default. class ClassT7[T = T1]: ... + # This should generate an error because Ts1 is not a valid default. class ClassT8[T = Ts1]: ... + # This should generate an error because P1 is not a valid default. class ClassT9[T = P1]: ... class ClassTs1[*Ts = *tuple[int]]: ... + class ClassTs2[*Ts = Unpack[tuple[int]]]: ... + # This should generate an error because default must be unpacked tuple. class ClassTs3[*Ts = tuple[int]]: ... + # This should generate an error because default must be unpacked tuple. class ClassTs4[*Ts = int]: ... + # This should generate an error because default must be unpacked tuple. class ClassTs5[*Ts = T1]: ... + # This should generate an error because default must be unpacked tuple. class ClassTs6[*Ts = Ts1]: ... + # This should generate an error because default must be unpacked tuple. class ClassTs7[*Ts = P1]: ... + class ClassTs8[*Ts = Unpack[tuple[int, ...]]]: ... + # This should generate an error because T1 isn't legal here. class ClassTs9[*Ts = Unpack[tuple[T1, T1]]]: ... + # This should generate an error because ... isn't legal here. class ClassTs10[*Ts = ...]: ... class ClassP1[**P = [int]]: ... + class ClassP2[**P = ...]: ... + class ClassP3[**P = []]: ... + class ClassP4[**P = [int, str, None, int | None]]: ... + # This should generate an error because T1 isn't legal here. class ClassP5[**P = [T1]]: ... + # This should generate an error because ParamSpec must be a list of types. class ClassP6[**P = int]: ... + # This should generate an error because ParamSpec must be a list of types. class ClassP7[**P = 3]: ... + # This should generate an error because ParamSpec must be a list of types. class ClassP8[**P = [1, int]]: ... + # This should generate an error because it combines a traditional ParamSpec # with a new-style (PEP 695) ParamSpec. class ClassP9[**P = P1]: ... + # This should generate an error because ParamSpec must be a list of types. class ClassP10[**P = Ts1]: ... - diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefault4.py b/packages/pyright-internal/src/tests/samples/typeVarDefault4.py index 18146b7d3..5da123d50 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefault4.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefault4.py @@ -4,14 +4,14 @@ from typing import TypeVar -# This should generate an error because T1 is after T2. -class ClassA[T2=str, T1]: ... # This should generate an error because T1 is after T2. -def funcA[T2=str, T1](a: T2, b: T1) -> T1 | T2: - ... +class ClassA[T2 = str, T1]: ... + # This should generate an error because T1 is after T2. -type TA_A[T2=str, T1] = dict[T2, T1] +def funcA[T2 = str, T1](a: T2, b: T1) -> T1 | T2: ... +# This should generate an error because T1 is after T2. +type TA_A[T2 = str, T1] = dict[T2, T1] diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefault5.py b/packages/pyright-internal/src/tests/samples/typeVarDefault5.py index 88821c81a..67ee439da 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefault5.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefault5.py @@ -4,12 +4,15 @@ from dataclasses import dataclass from typing import Any, overload + class ClassA: ... + @dataclass class ClassB[T: ClassA = ClassA]: owner: T + def post_comment[T: ClassA](owner: T) -> ClassB[T]: return ClassB(owner) diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py b/packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py index 438b61256..f276e6bc5 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py @@ -4,10 +4,11 @@ from typing import Self, Unpack -class ClassA[T1=str, T2=T1](dict[T1, T2]): +class ClassA[T1 = str, T2 = T1](dict[T1, T2]): def method1(self) -> Self: return self + reveal_type( ClassA[int].method1, expected_text="(self: ClassA[int, int]) -> ClassA[int, int]" ) @@ -23,9 +24,11 @@ reveal_type(a2, expected_text="ClassA[str, str]") # This should generate an error because T2 depends on T1. -class ClassC[T2=T1, T1=str]: ... +class ClassC[T2 = T1, T1 = str]: ... + + +class ClassD[T1 = str, T2 = T1](dict[T2, T1]): ... -class ClassD[T1=str, T2=T1](dict[T2, T1]): ... d1 = ClassD[int]() reveal_type(d1, expected_text="ClassD[int, int]") @@ -33,10 +36,13 @@ reveal_type(d1, expected_text="ClassD[int, int]") d2 = ClassD() reveal_type(d2, expected_text="ClassD[str, str]") -# This should generate an error because T5 refers to itself. -class ClassE[T5=T5]: ... -class ClassH[T1=str, T2=T1, T3=list[T2]]: ... +# This should generate an error because T5 refers to itself. +class ClassE[T5 = T5]: ... + + +class ClassH[T1 = str, T2 = T1, T3 = list[T2]]: ... + h1 = ClassH() reveal_type(h1, expected_text="ClassH[str, str, list[str]]") @@ -47,19 +53,23 @@ reveal_type(h2, expected_text="ClassH[int, int, list[int]]") h3 = ClassH[int, float]() reveal_type(h3, expected_text="ClassH[int, float, list[float]]") + # This should generate an error because T2 depends on T1. -class ClassI[T2=T1]: ... +class ClassI[T2 = T1]: ... + # This should generate an error because T4 depends on T2. -class ClassJ[T1=str, T4=dict[T1, T2]]: ... +class ClassJ[T1 = str, T4 = dict[T1, T2]]: ... -class ClassK[T1=str]: + +class ClassK[T1 = str]: # This should generate an error because T2 depends on T1, which # is defined in an outer scope. - class ClassL[T2=T1]: ... + class ClassL[T2 = T1]: ... -class ClassPA[**P1, **P2=P1, **P3=P2]: ... +class ClassPA[**P1, **P2 = P1, **P3 = P2]: ... + pa1 = ClassPA() reveal_type(pa1, expected_text="ClassPA[..., ..., ...]") @@ -75,9 +85,11 @@ reveal_type(pa4, expected_text="ClassPA[..., (int, int), (float)]") # This should generate an error because P1 depends on P2. -class ClassPB[**P2=P1, **P1=...]: ... +class ClassPB[**P2 = P1, **P1 = ...]: ... + + +class ClassPC[T1 = str, **P4 = [int, T1]]: ... -class ClassPC[T1=str, **P4=[int, T1]]: ... pc1 = ClassPC() reveal_type(pc1, expected_text="ClassPC[str, (int, str)]") @@ -90,10 +102,11 @@ reveal_type(pc3, expected_text="ClassPC[float, ...]") # This should generate an error because P4 depends on T1. -class ClassPD[**P4=[int, T1], T1=str]: ... +class ClassPD[**P4 = [int, T1], T1 = str]: ... -class ClassTA[T1=str, T2=T1, *Ts1=Unpack[tuple[T1, T2]]]: ... +class ClassTA[T1 = str, T2 = T1, *Ts1 = Unpack[tuple[T1, T2]]]: ... + ta1 = ClassTA() reveal_type(ta1, expected_text="ClassTA[str, str, str, str]") @@ -107,11 +120,14 @@ reveal_type(ta3, expected_text="ClassTA[int, float, int, float]") ta4 = ClassTA[int, float, *tuple[None, ...]]() reveal_type(ta4, expected_text="ClassTA[int, float, *tuple[None, ...]]") + # This should generate an error because Ts1 depends on T2. # It will generate a second error because T2 follows a TypeVarTuple. -class ClassTB[T1=str, *Ts1=Unpack[tuple[T1, T2]], T2=T1]: ... +class ClassTB[T1 = str, *Ts1 = Unpack[tuple[T1, T2]], T2 = T1]: ... + + +class ClassTC[T1 = str, *Ts2 = Unpack[tuple[T1, ...]]]: ... -class ClassTC[T1=str, *Ts2=Unpack[tuple[T1, ...]]]: ... tc1 = ClassTC() reveal_type(tc1, expected_text="ClassTC[str, *tuple[str, ...]]") @@ -124,4 +140,3 @@ reveal_type(tc3, expected_text="ClassTC[int]") tc4 = ClassTC[int, *tuple[None]]() reveal_type(tc4, expected_text="ClassTC[int, None]") - diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefaultClass4.py b/packages/pyright-internal/src/tests/samples/typeVarDefaultClass4.py index c51bb9355..d49a061c2 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefaultClass4.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefaultClass4.py @@ -8,8 +8,7 @@ P = ParamSpec("P", default=...) R = TypeVar("R", default=Any) -class ParentA(Generic[P, R]): - ... +class ParentA(Generic[P, R]): ... class ChildA(ParentA[P, R]): diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefaultFunction3.py b/packages/pyright-internal/src/tests/samples/typeVarDefaultFunction3.py index 876134b19..d3f3876aa 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefaultFunction3.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefaultFunction3.py @@ -5,8 +5,9 @@ from typing import TypeVar -def func1[T1, T2 = list[T1]](x: T1, y: int | T2 = 0) -> T2 | list[T1]: - ... + +def func1[T1, T2 = list[T1]](x: T1, y: int | T2 = 0) -> T2 | list[T1]: ... + v1_1 = func1("hi", 3.4) reveal_type(v1_1, expected_text="float | list[str]") @@ -16,6 +17,4 @@ reveal_type(v1_2, expected_text="list[str]") # This should generate an error because T1 depends on T2. -def func2[T2=list[T1], T1=str]() -> None: - ... - +def func2[T2 = list[T1], T1 = str]() -> None: ... diff --git a/packages/pyright-internal/src/tests/samples/typeVarDefaultTypeAlias3.py b/packages/pyright-internal/src/tests/samples/typeVarDefaultTypeAlias3.py index c207ef38a..bbc23c04f 100644 --- a/packages/pyright-internal/src/tests/samples/typeVarDefaultTypeAlias3.py +++ b/packages/pyright-internal/src/tests/samples/typeVarDefaultTypeAlias3.py @@ -6,49 +6,74 @@ from typing import Callable, Unpack -type TA_A[T1=str, T2=T1] = dict[T1, T2] +type TA_A[T1 = str, T2 = T1] = dict[T1, T2] + def func1(a1: TA_A[int], a2: TA_A): reveal_type(a1, expected_text="dict[int, int]") reveal_type(a2, expected_text="dict[str, str]") + # This should generate an error because T2 depends on T1. -type TA_B[T2=T1, T1=str] = None +type TA_B[T2 = T1, T1 = str] = None # This should generate an error because T5 refers to itself. -type TA_C[T5=T5] = None +type TA_C[T5 = T5] = None + +type TA_D[T1 = str, T2 = T1, T3 = list[T2]] = tuple[T1, T2, T3] -type TA_D[T1=str, T2=T1, T3=list[T2]] = tuple[T1, T2, T3] def func2(d1: TA_D, d2: TA_D[int], d3: TA_D[int, float]): reveal_type(d1, expected_text="tuple[str, str, list[str]]") reveal_type(d2, expected_text="tuple[int, int, list[int]]") reveal_type(d3, expected_text="tuple[int, float, list[float]]") + # This should generate an error because T2 depends on T1. -type TA_E[T2=T1] = list[T2] +type TA_E[T2 = T1] = list[T2] # This should generate two errors because T4 depends on T2 and T1. -type TA_F[T2=T1, T4=dict[T1, T2]] = dict[T2, T4] +type TA_F[T2 = T1, T4 = dict[T1, T2]] = dict[T2, T4] + class ClassK[T1]: # This should generate an error because T2 depends on T1, which # is defined in an outer scope. - type TA_G[T2=T1] = list[T2] + type TA_G[T2 = T1] = list[T2] -type TA_PA[**P1, **P2=P1, **P3=P2] = tuple[Callable[P1, None], Callable[P2, None], Callable[P3, None]] +type TA_PA[**P1, **P2 = P1, **P3 = P2] = tuple[ + Callable[P1, None], Callable[P2, None], Callable[P3, None] +] -def func3(pa1: TA_PA, pa2: TA_PA[[str]], pa3: TA_PA[..., [float]], pa4: TA_PA[..., [int, int], [float]]): + +def func3( + pa1: TA_PA, + pa2: TA_PA[[str]], + pa3: TA_PA[..., [float]], + pa4: TA_PA[..., [int, int], [float]], +): reveal_type(pa1, expected_text="tuple[(...) -> None, (...) -> None, (...) -> None]") reveal_type(pa2, expected_text="tuple[(str) -> None, (str) -> None, (str) -> None]") - reveal_type(pa3, expected_text="tuple[(...) -> None, (float) -> None, (float) -> None]") - reveal_type(pa4, expected_text="tuple[(...) -> None, (int, int) -> None, (float) -> None]") + reveal_type( + pa3, expected_text="tuple[(...) -> None, (float) -> None, (float) -> None]" + ) + reveal_type( + pa4, expected_text="tuple[(...) -> None, (int, int) -> None, (float) -> None]" + ) + # This should generate an error because P1 depends on P2. -type TA_PB[**P2=P1, **P1=...] = tuple[Callable[P2, None], Callable[P1, None]] +type TA_PB[**P2 = P1, **P1 = ...] = tuple[Callable[P2, None], Callable[P1, None]] + +type TA_PC[ + T1 = str, + **P4 = [ + int, + T1, + ], +] = T1 | Callable[P4, T1] -type TA_PC[T1=str, **P4=[int, T1, ]] = T1 | Callable[P4, T1] def func4(pc1: TA_PC, pc2: TA_PC[float], pc3: TA_PC[float, ...]): reveal_type(pc1, expected_text="str | ((int, str) -> str)") @@ -57,29 +82,44 @@ def func4(pc1: TA_PC, pc2: TA_PC[float], pc3: TA_PC[float, ...]): # This should generate an error because P4 depends on T1. -type TA_PD[**P4=[int, T1], T1=str] = Callable[P4, T1] +type TA_PD[**P4 = [int, T1], T1 = str] = Callable[P4, T1] class ClassTA[T1, T2, *Ts1]: ... -type TA_TA[T1=str, T2=T1, *Ts1=Unpack[tuple[T1, T2]]] = ClassTA[T1, T2, *Ts1] -def func5(ta1: TA_TA, ta2: TA_TA[int], ta3: TA_TA[int, float], ta4: TA_TA[int, float, *tuple[None, ...]]): +type TA_TA[T1 = str, T2 = T1, *Ts1 = Unpack[tuple[T1, T2]]] = ClassTA[T1, T2, *Ts1] + + +def func5( + ta1: TA_TA, + ta2: TA_TA[int], + ta3: TA_TA[int, float], + ta4: TA_TA[int, float, *tuple[None, ...]], +): reveal_type(ta1, expected_text="ClassTA[str, str, str, str]") reveal_type(ta2, expected_text="ClassTA[int, int, int, int]") reveal_type(ta3, expected_text="ClassTA[int, float, int, float]") reveal_type(ta4, expected_text="ClassTA[int, float, *tuple[None, ...]]") + # This should generate an error because Ts1 depends on T2. -type TA_TB[T1=str, *Ts1=Unpack[tuple[T1, T2]], T2=T1] = tuple[T1, *Ts1, T2] +type TA_TB[T1 = str, *Ts1 = Unpack[tuple[T1, T2]], T2 = T1] = tuple[T1, *Ts1, T2] + class ClassTC[T1, *Ts2]: ... -type TA_TC[T1=str, *Ts2=Unpack[tuple[T1, ...]]] = ClassTC[T1, *Ts2] -def func6(tc1: TA_TC, tc2: TA_TC[int], tc3: TA_TC[int, *tuple[()]], tc4: TA_TC[int, *tuple[None]]): +type TA_TC[T1 = str, *Ts2 = Unpack[tuple[T1, ...]]] = ClassTC[T1, *Ts2] + + +def func6( + tc1: TA_TC, + tc2: TA_TC[int], + tc3: TA_TC[int, *tuple[()]], + tc4: TA_TC[int, *tuple[None]], +): reveal_type(tc1, expected_text="ClassTC[str, *tuple[str, ...]]") reveal_type(tc2, expected_text="ClassTC[int, *tuple[int, ...]]") reveal_type(tc3, expected_text="ClassTC[int]") reveal_type(tc4, expected_text="ClassTC[int, None]") - diff --git a/packages/pyright-internal/src/tests/samples/typedDict1.py b/packages/pyright-internal/src/tests/samples/typedDict1.py index 9a0be6c52..922401247 100644 --- a/packages/pyright-internal/src/tests/samples/typedDict1.py +++ b/packages/pyright-internal/src/tests/samples/typedDict1.py @@ -89,4 +89,3 @@ class TD8(TypedDict, metaclass=type): # other __init_subclass__ parameters. class TD9(TypedDict, other=True): name: str - diff --git a/packages/pyright-internal/src/tests/samples/typedDict11.py b/packages/pyright-internal/src/tests/samples/typedDict11.py index 2087ee436..c339bf387 100644 --- a/packages/pyright-internal/src/tests/samples/typedDict11.py +++ b/packages/pyright-internal/src/tests/samples/typedDict11.py @@ -14,8 +14,7 @@ list2: list[MessageTypeDef] = [ TMessage = TypeVar("TMessage", bound=MessageTypeDef) -def func1(x: list[TMessage]) -> TMessage: - ... +def func1(x: list[TMessage]) -> TMessage: ... func1([{"Id": "", "Handle": ""}]) diff --git a/packages/pyright-internal/src/tests/samples/typedDict15.py b/packages/pyright-internal/src/tests/samples/typedDict15.py index d484fdc79..86f5cf4e7 100644 --- a/packages/pyright-internal/src/tests/samples/typedDict15.py +++ b/packages/pyright-internal/src/tests/samples/typedDict15.py @@ -9,16 +9,14 @@ class HasName(Protocol): class SupportsClear(Protocol): - def clear(self) -> None: - ... + def clear(self) -> None: ... _T = TypeVar("_T") class SupportsUpdate(Protocol): - def update(self: _T, __m: _T) -> None: - ... + def update(self: _T, __m: _T) -> None: ... class B(TypedDict): diff --git a/packages/pyright-internal/src/tests/samples/typedDict18.py b/packages/pyright-internal/src/tests/samples/typedDict18.py index 6cb48852e..38025d06a 100644 --- a/packages/pyright-internal/src/tests/samples/typedDict18.py +++ b/packages/pyright-internal/src/tests/samples/typedDict18.py @@ -50,8 +50,7 @@ class TD5(TypedDict, Generic[_T1]): y: _T1 -def func2(a: TD5[Literal[1]]): - ... +def func2(a: TD5[Literal[1]]): ... func2({"x": 1, "y": 1}) @@ -60,8 +59,7 @@ func2({"x": 1, "y": 1}) func2({"x": 2, "y": 1}) -def func3(a: TD5[_T1]) -> _T1: - ... +def func3(a: TD5[_T1]) -> _T1: ... reveal_type(func3({"x": 1, "y": 1}), expected_text="int") @@ -72,8 +70,7 @@ class TD6(TD5[Literal[1]]): z: str -def func4(a: TD6) -> Literal[1]: - ... +def func4(a: TD6) -> Literal[1]: ... func4({"x": 1, "y": 1, "z": "a"}) @@ -96,8 +93,7 @@ f3: TD7[Literal[1]] = {"x": 1, "y": 1, "z": "a"} reveal_type(func5({"x": 1, "y": 1, "z": "a"})) -class TD8(TD7[Literal[1]]): - ... +class TD8(TD7[Literal[1]]): ... def func6(a: TD8) -> Literal[1]: @@ -115,8 +111,7 @@ class TD9(TypedDict, Generic[_T1]): class ClassA(Generic[_T1]): - def __init__(self, **attrs: Unpack[TD9[_T1]]) -> None: - ... + def __init__(self, **attrs: Unpack[TD9[_T1]]) -> None: ... f5 = ClassA[int](x=1) @@ -136,5 +131,4 @@ class TD11(TypedDict): y: int -class TD12(TD10[str], TD11): - ... +class TD12(TD10[str], TD11): ... diff --git a/packages/pyright-internal/src/tests/samples/typedDict2.py b/packages/pyright-internal/src/tests/samples/typedDict2.py index d225816e9..1a150438b 100644 --- a/packages/pyright-internal/src/tests/samples/typedDict2.py +++ b/packages/pyright-internal/src/tests/samples/typedDict2.py @@ -53,7 +53,7 @@ book4: BookBasedMovie = { book5: BookBasedMovie = { "name": "Moonraker", - "year": 1979 + "year": 1979, # This should generate an error because 'based_on' is # a required field, and it's not provided. } diff --git a/packages/pyright-internal/src/tests/samples/typedDict22.py b/packages/pyright-internal/src/tests/samples/typedDict22.py index 36e7142e1..5e4ac2d6e 100644 --- a/packages/pyright-internal/src/tests/samples/typedDict22.py +++ b/packages/pyright-internal/src/tests/samples/typedDict22.py @@ -3,8 +3,7 @@ from typing import TypedDict -class TD1(TypedDict): - ... +class TD1(TypedDict): ... reveal_type(TD1.__required_keys__, expected_text="frozenset[str]") diff --git a/packages/pyright-internal/src/tests/samples/typedDict9.py b/packages/pyright-internal/src/tests/samples/typedDict9.py index f9c887959..0176f4698 100644 --- a/packages/pyright-internal/src/tests/samples/typedDict9.py +++ b/packages/pyright-internal/src/tests/samples/typedDict9.py @@ -40,8 +40,7 @@ class Outer3(TypedDict): z: Literal[""] | Inner4 -def func1(td: Outer3): - ... +def func1(td: Outer3): ... o3: Outer2 = {"y": "", "z": {"x": 0}} diff --git a/packages/pyright-internal/src/tests/samples/unions1.py b/packages/pyright-internal/src/tests/samples/unions1.py index 9c54b4425..20951088a 100644 --- a/packages/pyright-internal/src/tests/samples/unions1.py +++ b/packages/pyright-internal/src/tests/samples/unions1.py @@ -30,8 +30,7 @@ T = TypeVar("T") def func4(a: str): - def helper(value: T) -> T | None: - ... + def helper(value: T) -> T | None: ... class Baz(Generic[T]): qux: T | None @@ -44,12 +43,10 @@ T = TypeVar("T") TT = TypeVar("TT", bound=type) -def decorator1(value: type[T]) -> type[T]: - ... +def decorator1(value: type[T]) -> type[T]: ... -def decorator2(value: TT) -> TT: - ... +def decorator2(value: TT) -> TT: ... class ClassA: diff --git a/packages/pyright-internal/src/tests/samples/unions3.py b/packages/pyright-internal/src/tests/samples/unions3.py index 8f2921a44..281db0fd0 100644 --- a/packages/pyright-internal/src/tests/samples/unions3.py +++ b/packages/pyright-internal/src/tests/samples/unions3.py @@ -24,13 +24,11 @@ _T = TypeVar("_T") class Metaclass1(type): - def __or__(cls: _T, other: type) -> _T: - ... + def __or__(cls: _T, other: type) -> _T: ... class Metaclass2(type): - def __ror__(cls: _T, other: type) -> _T: - ... + def __ror__(cls: _T, other: type) -> _T: ... class ClassWithMeta1(metaclass=Metaclass1): diff --git a/packages/pyright-internal/src/tests/samples/unions4.py b/packages/pyright-internal/src/tests/samples/unions4.py index 4bee96b60..6ddfefef2 100644 --- a/packages/pyright-internal/src/tests/samples/unions4.py +++ b/packages/pyright-internal/src/tests/samples/unions4.py @@ -12,8 +12,7 @@ z = Union # This should generate an error. -def func1() -> Union: - ... +def func1() -> Union: ... # This should generate an error. diff --git a/packages/pyright-internal/src/tests/samples/unions6.py b/packages/pyright-internal/src/tests/samples/unions6.py index 15b6b87a0..35e2a3d16 100644 --- a/packages/pyright-internal/src/tests/samples/unions6.py +++ b/packages/pyright-internal/src/tests/samples/unions6.py @@ -24,18 +24,15 @@ class MyList(MutableSequence[_T]): ... @overload - def __getitem__(self, index: slice) -> MyList[_T]: - ... + def __getitem__(self, index: slice) -> MyList[_T]: ... class NestedSequence(Protocol[T_co]): @overload - def __getitem__(self, index: int, /) -> T_co | NestedSequence[T_co]: - ... + def __getitem__(self, index: int, /) -> T_co | NestedSequence[T_co]: ... @overload - def __getitem__(self, index: slice, /) -> NestedSequence[T_co]: - ... + def __getitem__(self, index: slice, /) -> NestedSequence[T_co]: ... def func1(b: MyList[int | MyList[int]]): @@ -47,9 +44,8 @@ def func2(c: MyList[MyList[int] | int]): def is_async_callable( - obj: Callable[..., _T] | Callable[..., Awaitable[_T]] -) -> TypeGuard[Callable[..., Awaitable[_T]]]: - ... + obj: Callable[..., _T] | Callable[..., Awaitable[_T]], +) -> TypeGuard[Callable[..., Awaitable[_T]]]: ... async def func3(fn: Callable[[], _T] | Callable[[], Awaitable[_T]]): diff --git a/packages/pyright-internal/src/tests/samples/unpack1.py b/packages/pyright-internal/src/tests/samples/unpack1.py index c198e41ee..0f3f2b1c9 100644 --- a/packages/pyright-internal/src/tests/samples/unpack1.py +++ b/packages/pyright-internal/src/tests/samples/unpack1.py @@ -3,12 +3,10 @@ # pyright: strictListInference=true -class Class1: - ... +class Class1: ... -class Class2: - ... +class Class2: ... a = [1, "hello", 3.4, Class1()] @@ -16,8 +14,7 @@ a = [1, "hello", 3.4, Class1()] b = [*a] -def int_only(a: int): - ... +def int_only(a: int): ... for c in b: diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar10.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar10.py index 277188393..88b70c4bc 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar10.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar10.py @@ -26,7 +26,7 @@ class Array(Generic[DType, Unpack[Shape]]): def process_batch_channels( - x: Array[Batch, Unpack[tuple[Any, ...]], Channels] + x: Array[Batch, Unpack[tuple[Any, ...]], Channels], ) -> None: ... diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar14.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar14.py index a78a322e5..003e2073e 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar14.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar14.py @@ -18,7 +18,7 @@ def call_with_params(func: Callable[[*Ts], R], *params: *Ts) -> R: def callback1(*args: int) -> int: ... -def callback2(*args: * tuple[int, int]) -> int: ... +def callback2(*args: *tuple[int, int]) -> int: ... call_with_params(callback1) @@ -36,7 +36,7 @@ call_with_params(callback2, 1, 1) call_with_params(callback2, 1, "") -def callback3(*args: * tuple[int, *tuple[str, ...], int]) -> int: ... +def callback3(*args: *tuple[int, *tuple[str, ...], int]) -> int: ... # This should generate an error. diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar17.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar17.py index 7af3c28ce..16ec9536f 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar17.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar17.py @@ -10,27 +10,27 @@ Ts = TypeVarTuple("Ts") def call0(*args: *Ts) -> tuple[*Ts]: ... -def call1(*args: * tuple[int, *Ts]) -> tuple[*Ts]: ... +def call1(*args: *tuple[int, *Ts]) -> tuple[*Ts]: ... -def call2(*args: * tuple[*Ts, float]) -> tuple[*Ts]: ... +def call2(*args: *tuple[*Ts, float]) -> tuple[*Ts]: ... -def call3(*args: * tuple[int, *Ts, float]) -> tuple[*Ts]: ... +def call3(*args: *tuple[int, *Ts, float]) -> tuple[*Ts]: ... -def call4(*args: * tuple[*tuple[int, *tuple[*Ts], float]]) -> tuple[*Ts]: ... +def call4(*args: *tuple[*tuple[int, *tuple[*Ts], float]]) -> tuple[*Ts]: ... -def func1(*args: * tuple[int, str]): +def func1(*args: *tuple[int, str]): reveal_type(call0(*args), expected_text="tuple[int, str]") -def func2(*args: * tuple[int, ...]): +def func2(*args: *tuple[int, ...]): reveal_type(call0(*args), expected_text="tuple[int, ...]") -def func3(*args: * tuple[int, *tuple[str, ...], float]): +def func3(*args: *tuple[int, *tuple[str, ...], float]): reveal_type(call0(*args), expected_text="tuple[int, *tuple[str, ...], float]") @@ -53,5 +53,5 @@ def func5(x: int, y: str, z: float): reveal_type(v4, expected_text="tuple[str]") -def func6(*args: * tuple[int, *tuple[None, ...], float]): +def func6(*args: *tuple[int, *tuple[None, ...], float]): reveal_type(call2(*args), expected_text="tuple[int, *tuple[None, ...]]") diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar21.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar21.py index b3638998c..abd017691 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar21.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar21.py @@ -11,8 +11,7 @@ T = TypeVar("T") Ts = TypeVarTuple("Ts") -def f(*args: Unpack[Ts]) -> Union[Unpack[Ts]]: - ... +def f(*args: Unpack[Ts]) -> Union[Unpack[Ts]]: ... def g(x: tuple[T, Unpack[Ts]]) -> Union[T, Unpack[Ts]]: diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar22.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar22.py index c501d07b9..03ebc5bdf 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar22.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar22.py @@ -9,8 +9,9 @@ from typing import Callable, Literal, TypeVarTuple, Union, Unpack Ts = TypeVarTuple("Ts") -def func1(f: Callable[[Unpack[Ts]], None], vs: tuple[Unpack[Ts]]) -> Union[Unpack[Ts]]: - ... +def func1( + f: Callable[[Unpack[Ts]], None], vs: tuple[Unpack[Ts]] +) -> Union[Unpack[Ts]]: ... def func2(f: Callable[[Literal[1, 2]], None], vs: tuple[Literal[1, 2]]): diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar23.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar23.py index 17c3cef73..a2a117902 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar23.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar23.py @@ -42,12 +42,12 @@ class Tree(Generic[X, Y]): def lift( - f: Callable[[*Xs], tuple[*Ys]] + f: Callable[[*Xs], tuple[*Ys]], ) -> Callable[[Tree[Z, tuple[*Xs]]], Tree[Z, tuple[*Ys]]]: ... def test( - f: Callable[[X], Y] + f: Callable[[X], Y], ) -> Callable[[Tree[Z, tuple[X, ...]]], Tree[Z, tuple[Y, ...]]]: return lift(star(f)) diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar24.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar24.py index 1293ba291..95cbaf316 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar24.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar24.py @@ -14,8 +14,7 @@ class ClassA(Generic[*Ts]): reveal_type(self.x, expected_text="list[Union[*Ts@ClassA]]") - def method(self) -> Union[*Ts]: - ... + def method(self) -> Union[*Ts]: ... a1 = ClassA[int, bool, str]() diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar25.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar25.py index 5640b48a6..e5a75c379 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar25.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar25.py @@ -6,12 +6,10 @@ from typing import Callable, TypeVarTuple Ts = TypeVarTuple("Ts") -def func1(g: Callable[[Callable[[*Ts], None]], None]) -> tuple[*Ts]: - ... +def func1(g: Callable[[Callable[[*Ts], None]], None]) -> tuple[*Ts]: ... -def func2(cb: Callable[[bytes, int], None]) -> None: - ... +def func2(cb: Callable[[bytes, int], None]) -> None: ... reveal_type(func1(func2), expected_text="tuple[bytes, int]") diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar26.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar26.py index 47d46568c..18bb712d1 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar26.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar26.py @@ -8,12 +8,10 @@ T = TypeVar("T") Ts = TypeVarTuple("Ts") -def func1(x: int, y: str = "", z: int | None = None) -> None: - ... +def func1(x: int, y: str = "", z: int | None = None) -> None: ... -def func2(callback: Callable[[*Ts], None], *args: *Ts) -> tuple[*Ts]: - ... +def func2(callback: Callable[[*Ts], None], *args: *Ts) -> tuple[*Ts]: ... v1 = func2(func1, 1) @@ -38,24 +36,21 @@ func2(func1, "") func2(func1, 3, "", None, None) -def func3(callback: Callable[[*Ts], None]) -> tuple[*Ts]: - ... +def func3(callback: Callable[[*Ts], None]) -> tuple[*Ts]: ... v5 = func3(func1) reveal_type(v5, expected_text="tuple[int, str, int | None]") -def func4(a: Literal["day", "hour"]) -> None: - ... +def func4(a: Literal["day", "hour"]) -> None: ... def func5(x: bool): func2(func4, "day" if x else "hour") -def func6(x: T, y: T, z: int | None = None) -> None: - ... +def func6(x: T, y: T, z: int | None = None) -> None: ... def func7(x: T, y: T) -> None: diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar27.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar27.py index 0be5a4208..ef20fcf17 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar27.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar27.py @@ -7,32 +7,26 @@ T = TypeVar("T") Ts = TypeVarTuple("Ts") -class A(Generic[*Ts, T]): - ... +class A(Generic[*Ts, T]): ... -def deco1(x: Callable[[*tuple[*Ts, int]], None]) -> tuple[*Ts]: - ... +def deco1(x: Callable[[*tuple[*Ts, int]], None]) -> tuple[*Ts]: ... -def deco2(x: Callable[[*tuple[*Ts, str]], None]) -> tuple[*Ts]: - ... +def deco2(x: Callable[[*tuple[*Ts, str]], None]) -> tuple[*Ts]: ... -def deco3(x: Callable[[*tuple[str, int]], None]) -> None: - ... +def deco3(x: Callable[[*tuple[str, int]], None]) -> None: ... def deco4(x: Callable[[*Ts, T], None]) -> A[*Ts, T]: return A() -def func1(a: str, b: int) -> None: - ... +def func1(a: str, b: int) -> None: ... -def func2(a: str, b: str, c: int) -> None: - ... +def func2(a: str, b: str, c: int) -> None: ... v1 = deco1(func1) diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar29.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar29.py index 6968c6d31..d551f7688 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar29.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar29.py @@ -7,11 +7,9 @@ from typing import Callable, TypeVar, TypeVarTuple def f(a: str, b: int, c: bool) -> None: ... -def curry1[ - First, *Rest, Result -](function: Callable[[First, *Rest], Result]) -> Callable[ - [*Rest], Callable[[First], Result] -]: ... +def curry1[First, *Rest, Result]( + function: Callable[[First, *Rest], Result], +) -> Callable[[*Rest], Callable[[First], Result]]: ... applied_twice1 = curry1(curry1(f)) @@ -24,7 +22,7 @@ Result = TypeVar("Result") def curry2( - function: Callable[[First, *Rest], Result] + function: Callable[[First, *Rest], Result], ) -> Callable[[*Rest], Callable[[First], Result]]: ... diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar3.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar3.py index 96cfad3d2..924daa372 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar3.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar3.py @@ -18,13 +18,16 @@ class Array(Generic[Unpack[_Xs]]): reveal_type(args, expected_text="tuple[*_Xs@Array]") # This should generate an error because _Xs is not unpacked. - def foo(self, *args: _Xs) -> None: ... + def foo(self, *args: _Xs) -> None: + ... -def linearize(value: Array[Unpack[_Xs]]) -> tuple[Unpack[_Xs]]: ... +def linearize(value: Array[Unpack[_Xs]]) -> tuple[Unpack[_Xs]]: + ... -def array_to_tuple(value: Array[Unpack[_Xs]]) -> tuple[complex, Unpack[_Xs]]: ... +def array_to_tuple(value: Array[Unpack[_Xs]]) -> tuple[complex, Unpack[_Xs]]: + ... def func1(x: Array[int, str, str, float], y: Array[()]): @@ -88,12 +91,23 @@ def func3(x: Array[Unpack[_Xs]]) -> Array[Unpack[_Xs]]: @overload -def func4(signal: Array[*_Xs], *args: *_Xs) -> None: ... +def func4(signal: Array[*_Xs], *args: *_Xs) -> None: + ... + + @overload -def func4(signal: str, *args: Any) -> None: ... -def func4(signal: Array[*_Xs] | str, *args: *_Xs) -> None: ... +def func4(signal: str, *args: Any) -> None: + ... + + +def func4(signal: Array[*_Xs] | str, *args: *_Xs) -> None: + ... def func5(a1: Array[Literal["a", "b"]], a2: Array[Literal["a"], Literal["b"]]): func4(a1, "a") func4(a2, "a", "b") + + +def func6(a: Array): + reveal_type(a, expected_text="Array[*tuple[Unknown, ...]]") diff --git a/packages/pyright-internal/src/tests/samples/variadicTypeVar9.py b/packages/pyright-internal/src/tests/samples/variadicTypeVar9.py index a2250d40b..6d7d9c054 100644 --- a/packages/pyright-internal/src/tests/samples/variadicTypeVar9.py +++ b/packages/pyright-internal/src/tests/samples/variadicTypeVar9.py @@ -26,7 +26,7 @@ TailRec = Call[Unpack[Ts]] | Return[T] def tail_rec( - fn: Callable[[Unpack[Ts]], TailRec[Unpack[Ts], T]] + fn: Callable[[Unpack[Ts]], TailRec[Unpack[Ts], T]], ) -> Callable[[Unpack[Ts]], T]: ... diff --git a/packages/pyright-internal/src/tests/samples/with1.py b/packages/pyright-internal/src/tests/samples/with1.py index 0aca6001c..da073b597 100644 --- a/packages/pyright-internal/src/tests/samples/with1.py +++ b/packages/pyright-internal/src/tests/samples/with1.py @@ -107,8 +107,7 @@ class Class5(Generic[_T1]): return None -class Class6(Class5[int]): - ... +class Class6(Class5[int]): ... async def do(): diff --git a/packages/pyright-internal/src/tests/samples/with5.py b/packages/pyright-internal/src/tests/samples/with5.py index ed4046516..b1a188263 100644 --- a/packages/pyright-internal/src/tests/samples/with5.py +++ b/packages/pyright-internal/src/tests/samples/with5.py @@ -3,12 +3,10 @@ from typing import ContextManager -def create_context() -> ContextManager[str]: - ... +def create_context() -> ContextManager[str]: ... -def possible_exception() -> None: - ... +def possible_exception() -> None: ... def func1(): diff --git a/packages/pyright-internal/src/tests/samples/with6.py b/packages/pyright-internal/src/tests/samples/with6.py index 9d97d8a75..e7bc5c96b 100644 --- a/packages/pyright-internal/src/tests/samples/with6.py +++ b/packages/pyright-internal/src/tests/samples/with6.py @@ -15,8 +15,7 @@ class ClassA(type): print("Exit A") -class ClassB(metaclass=ClassA): - ... +class ClassB(metaclass=ClassA): ... with ClassB as b: diff --git a/packages/pyright-internal/src/tests/typeEvaluator3.test.ts b/packages/pyright-internal/src/tests/typeEvaluator3.test.ts index f7660e287..5513d64a4 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator3.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator3.test.ts @@ -173,6 +173,12 @@ test('Coroutines3', () => { TestUtils.validateResults(analysisResults, 0); }); +test('Coroutines4', () => { + const analysisResults = TestUtils.typeAnalyzeSampleFiles(['coroutines4.py']); + + TestUtils.validateResults(analysisResults, 0); +}); + test('Loop1', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['loop1.py']); diff --git a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts index 686896c16..2ecba0db7 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts @@ -440,7 +440,7 @@ test('Optional2', () => { test('Tuple1', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['tuple1.py']); - TestUtils.validateResults(analysisResults, 24); + TestUtils.validateResults(analysisResults, 26); }); test('Tuple2', () => { diff --git a/packages/pyright-internal/typeshed-fallback/commit.txt b/packages/pyright-internal/typeshed-fallback/commit.txt index 79f3d310a..3caecd219 100644 --- a/packages/pyright-internal/typeshed-fallback/commit.txt +++ b/packages/pyright-internal/typeshed-fallback/commit.txt @@ -1 +1 @@ -58f2a795bac5924367d21961af53a32af7bb5727 +82199768bf2e651804cb718f4b570af6d41333d9 diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/VERSIONS b/packages/pyright-internal/typeshed-fallback/stdlib/VERSIONS index a8526aab9..89754f65f 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/VERSIONS +++ b/packages/pyright-internal/typeshed-fallback/stdlib/VERSIONS @@ -34,6 +34,7 @@ _dummy_thread: 3.0-3.8 _dummy_threading: 3.0-3.8 _heapq: 3.0- _imp: 3.0- +_interpchannels: 3.13- _json: 3.0- _locale: 3.0- _lsprof: 3.0- @@ -65,9 +66,9 @@ array: 3.0- ast: 3.0- asynchat: 3.0-3.11 asyncio: 3.4- -asyncio.mixins: 3.10- asyncio.exceptions: 3.8- asyncio.format_helpers: 3.7- +asyncio.mixins: 3.10- asyncio.runners: 3.7- asyncio.staggered: 3.8- asyncio.taskgroups: 3.11- @@ -270,6 +271,7 @@ threading: 3.0- time: 3.0- timeit: 3.0- tkinter: 3.0- +tkinter.tix: 3.0-3.12 token: 3.0- tokenize: 3.0- tomllib: 3.11- diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/_ast.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/_ast.pyi index 4d4ffbbd0..d14c6d39a 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/_ast.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/_ast.pyi @@ -11,7 +11,7 @@ if sys.version_info >= (3, 13): PyCF_OPTIMIZED_AST: Literal[33792] # Used for node end positions in constructor keyword arguments -_EndPositionT = typing_extensions.TypeVar("_EndPositionT", int, int | None, default=int | None) # noqa: Y023 +_EndPositionT = typing_extensions.TypeVar("_EndPositionT", int, int | None, default=int | None) # Alias used for fields that must always be valid identifiers # A string `x` counts as a valid identifier if both the following are True diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/_curses.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/_curses.pyi index 6f3fbd807..eb1d7b9bd 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/_curses.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/_curses.pyi @@ -63,8 +63,7 @@ A_COLOR: int A_DIM: int A_HORIZONTAL: int A_INVIS: int -if sys.platform != "darwin": - A_ITALIC: int +A_ITALIC: int A_LEFT: int A_LOW: int A_NORMAL: int diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/_interpchannels.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/_interpchannels.pyi new file mode 100644 index 000000000..b77fe321a --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stdlib/_interpchannels.pyi @@ -0,0 +1,84 @@ +from _typeshed import structseq +from typing import Final, Literal, SupportsIndex, final +from typing_extensions import Buffer, Self + +class ChannelError(RuntimeError): ... +class ChannelClosedError(ChannelError): ... +class ChannelEmptyError(ChannelError): ... +class ChannelNotEmptyError(ChannelError): ... +class ChannelNotFoundError(ChannelError): ... + +# Mark as final, since instantiating ChannelID is not supported. +@final +class ChannelID: + @property + def end(self) -> Literal["send", "recv", "both"]: ... + @property + def send(self) -> Self: ... + @property + def recv(self) -> Self: ... + def __eq__(self, other: object) -> bool: ... + def __ge__(self, other: ChannelID) -> bool: ... + def __gt__(self, other: ChannelID) -> bool: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __int__(self) -> int: ... + def __le__(self, other: ChannelID) -> bool: ... + def __lt__(self, other: ChannelID) -> bool: ... + def __ne__(self, other: object) -> bool: ... + +@final +class ChannelInfo(structseq[int], tuple[bool, bool, bool, int, int, int, int, int]): + __match_args__: Final = ( + "open", + "closing", + "closed", + "count", + "num_interp_send", + "num_interp_send_released", + "num_interp_recv", + "num_interp_recv_released", + ) + @property + def open(self) -> bool: ... + @property + def closing(self) -> bool: ... + @property + def closed(self) -> bool: ... + @property + def count(self) -> int: ... # type: ignore[override] + @property + def num_interp_send(self) -> int: ... + @property + def num_interp_send_released(self) -> int: ... + @property + def num_interp_recv(self) -> int: ... + @property + def num_interp_recv_released(self) -> int: ... + @property + def num_interp_both(self) -> int: ... + @property + def num_interp_both_recv_released(self) -> int: ... + @property + def num_interp_both_send_released(self) -> int: ... + @property + def num_interp_both_released(self) -> int: ... + @property + def recv_associated(self) -> bool: ... + @property + def recv_released(self) -> bool: ... + @property + def send_associated(self) -> bool: ... + @property + def send_released(self) -> bool: ... + +def create() -> ChannelID: ... +def destroy(cid: SupportsIndex) -> None: ... +def list_all() -> list[ChannelID]: ... +def list_interpreters(cid: SupportsIndex, *, send: bool) -> list[int]: ... +def send(cid: SupportsIndex, obj: object, *, blocking: bool = True, timeout: float | None = None) -> None: ... +def send_buffer(cid: SupportsIndex, obj: Buffer, *, blocking: bool = True, timeout: float | None = None) -> None: ... +def recv(cid: SupportsIndex, default: object = ...) -> object: ... +def close(cid: SupportsIndex, *, send: bool = False, recv: bool = False) -> None: ... +def get_info(cid: SupportsIndex) -> ChannelInfo: ... +def release(cid: SupportsIndex, *, send: bool = False, recv: bool = False, force: bool = False) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/_tkinter.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/_tkinter.pyi index 3340df424..aea74c8be 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/_tkinter.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/_tkinter.pyi @@ -1,5 +1,7 @@ import sys +from collections.abc import Callable from typing import Any, ClassVar, Literal, final +from typing_extensions import TypeAlias # _tkinter is meant to be only used internally by tkinter, but some tkinter # functions e.g. return _tkinter.Tcl_Obj objects. Tcl_Obj represents a Tcl @@ -30,6 +32,8 @@ class Tcl_Obj: class TclError(Exception): ... +_TkinterTraceFunc: TypeAlias = Callable[[tuple[str, ...]], object] + # This class allows running Tcl code. Tkinter uses it internally a lot, and # it's often handy to drop a piece of Tcl code into a tkinter program. Example: # @@ -86,6 +90,9 @@ class TkappType: def unsetvar(self, *args, **kwargs): ... def wantobjects(self, *args, **kwargs): ... def willdispatch(self): ... + if sys.version_info >= (3, 12): + def gettrace(self, /) -> _TkinterTraceFunc | None: ... + def settrace(self, func: _TkinterTraceFunc | None, /) -> None: ... # These should be kept in sync with tkinter.tix constants, except ALL_EVENTS which doesn't match TCL_ALL_EVENTS ALL_EVENTS: Literal[-3] diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/_weakref.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/_weakref.pyi index 61365645d..f142820c5 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/_weakref.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/_weakref.pyi @@ -21,8 +21,9 @@ class ProxyType(Generic[_T]): # "weakproxy" def __getattr__(self, attr: str) -> Any: ... class ReferenceType(Generic[_T]): - __callback__: Callable[[ReferenceType[_T]], Any] - def __new__(cls, o: _T, callback: Callable[[ReferenceType[_T]], Any] | None = ..., /) -> Self: ... + __callback__: Callable[[Self], Any] + def __new__(cls, o: _T, callback: Callable[[Self], Any] | None = ..., /) -> Self: ... + def __init__(self, o: _T, callback: Callable[[Self], Any] | None = ..., /) -> None: ... def __call__(self) -> _T | None: ... def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/argparse.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/argparse.pyi index 1956d08c9..bc781ec8e 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/argparse.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/argparse.pyi @@ -32,6 +32,7 @@ _T = TypeVar("_T") _ActionT = TypeVar("_ActionT", bound=Action) _ArgumentParserT = TypeVar("_ArgumentParserT", bound=ArgumentParser) _N = TypeVar("_N") +_ActionType: TypeAlias = Callable[[str], Any] | FileType | str # more precisely, Literal["store", "store_const", "store_true", # "store_false", "append", "append_const", "count", "help", "version", # "extend"], but using this would make it hard to annotate callers @@ -89,7 +90,7 @@ class _ActionsContainer: nargs: int | _NArgsStr | _SUPPRESS_T | None = None, const: Any = ..., default: Any = ..., - type: Callable[[str], _T] | FileType = ..., + type: _ActionType = ..., choices: Iterable[_T] | None = ..., required: bool = ..., help: str | None = ..., @@ -313,7 +314,7 @@ class Action(_AttributeHolder): nargs: int | str | None const: Any default: Any - type: Callable[[str], Any] | FileType | None + type: _ActionType | None choices: Iterable[Any] | None required: bool help: str | None @@ -699,6 +700,7 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): add_help: bool = ..., allow_abbrev: bool = ..., exit_on_error: bool = ..., + **kwargs: Any, # Accepting any additional kwargs for custom parser classes ) -> _ArgumentParserT: ... elif sys.version_info >= (3, 9): def add_parser( @@ -721,6 +723,7 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): add_help: bool = ..., allow_abbrev: bool = ..., exit_on_error: bool = ..., + **kwargs: Any, # Accepting any additional kwargs for custom parser classes ) -> _ArgumentParserT: ... else: def add_parser( @@ -742,6 +745,7 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): conflict_handler: str = ..., add_help: bool = ..., allow_abbrev: bool = ..., + **kwargs: Any, # Accepting any additional kwargs for custom parser classes ) -> _ArgumentParserT: ... def _get_subactions(self) -> list[Action]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/events.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/events.pyi index c0345eb1b..8c2664666 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/events.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/events.pyi @@ -16,23 +16,40 @@ from .tasks import Task from .transports import BaseTransport, DatagramTransport, ReadTransport, SubprocessTransport, Transport, WriteTransport from .unix_events import AbstractChildWatcher -__all__ = ( - "AbstractEventLoopPolicy", - "AbstractEventLoop", - "AbstractServer", - "Handle", - "TimerHandle", - "get_event_loop_policy", - "set_event_loop_policy", - "get_event_loop", - "set_event_loop", - "new_event_loop", - "get_child_watcher", - "set_child_watcher", - "_set_running_loop", - "get_running_loop", - "_get_running_loop", -) +if sys.version_info >= (3, 14): + __all__ = ( + "AbstractEventLoopPolicy", + "AbstractEventLoop", + "AbstractServer", + "Handle", + "TimerHandle", + "get_event_loop_policy", + "set_event_loop_policy", + "get_event_loop", + "set_event_loop", + "new_event_loop", + "_set_running_loop", + "get_running_loop", + "_get_running_loop", + ) +else: + __all__ = ( + "AbstractEventLoopPolicy", + "AbstractEventLoop", + "AbstractServer", + "Handle", + "TimerHandle", + "get_event_loop_policy", + "set_event_loop_policy", + "get_event_loop", + "set_event_loop", + "new_event_loop", + "get_child_watcher", + "set_child_watcher", + "_set_running_loop", + "get_running_loop", + "_get_running_loop", + ) _T = TypeVar("_T") _Ts = TypeVarTuple("_Ts") @@ -541,18 +558,19 @@ class AbstractEventLoopPolicy: @abstractmethod def new_event_loop(self) -> AbstractEventLoop: ... # Child processes handling (Unix only). - if sys.version_info >= (3, 12): - @abstractmethod - @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") - def get_child_watcher(self) -> AbstractChildWatcher: ... - @abstractmethod - @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") - def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... - else: - @abstractmethod - def get_child_watcher(self) -> AbstractChildWatcher: ... - @abstractmethod - def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... + if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + @abstractmethod + @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") + def get_child_watcher(self) -> AbstractChildWatcher: ... + @abstractmethod + @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") + def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... + else: + @abstractmethod + def get_child_watcher(self) -> AbstractChildWatcher: ... + @abstractmethod + def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy, metaclass=ABCMeta): def get_event_loop(self) -> AbstractEventLoop: ... @@ -565,15 +583,16 @@ def get_event_loop() -> AbstractEventLoop: ... def set_event_loop(loop: AbstractEventLoop | None) -> None: ... def new_event_loop() -> AbstractEventLoop: ... -if sys.version_info >= (3, 12): - @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") - def get_child_watcher() -> AbstractChildWatcher: ... - @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") - def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... +if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") + def get_child_watcher() -> AbstractChildWatcher: ... + @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") + def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... -else: - def get_child_watcher() -> AbstractChildWatcher: ... - def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... + else: + def get_child_watcher() -> AbstractChildWatcher: ... + def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... def _set_running_loop(loop: AbstractEventLoop | None, /) -> None: ... def _get_running_loop() -> AbstractEventLoop: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/tasks.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/tasks.pyi index c16a1919b..4613bca70 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/tasks.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/tasks.pyi @@ -70,7 +70,10 @@ _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") _T6 = TypeVar("_T6") _FT = TypeVar("_FT", bound=Future[Any]) -_FutureLike: TypeAlias = Future[_T] | Generator[Any, None, _T] | Awaitable[_T] +if sys.version_info >= (3, 12): + _FutureLike: TypeAlias = Future[_T] | Awaitable[_T] +else: + _FutureLike: TypeAlias = Future[_T] | Generator[Any, None, _T] | Awaitable[_T] _TaskYieldType: TypeAlias = Future[object] | None FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/unix_events.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/unix_events.pyi index e9274b853..3a2c62646 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/unix_events.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/unix_events.pyi @@ -13,51 +13,54 @@ _Ts = TypeVarTuple("_Ts") # This is also technically not available on Win, # but other parts of typeshed need this definition. # So, it is special cased. -if sys.version_info >= (3, 12): - @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") - class AbstractChildWatcher: - @abstractmethod - def add_child_handler( - self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] - ) -> None: ... - @abstractmethod - def remove_child_handler(self, pid: int) -> bool: ... - @abstractmethod - def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - @abstractmethod - def close(self) -> None: ... - @abstractmethod - def __enter__(self) -> Self: ... - @abstractmethod - def __exit__( - self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None - ) -> None: ... - @abstractmethod - def is_active(self) -> bool: ... +if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") + class AbstractChildWatcher: + @abstractmethod + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + @abstractmethod + def remove_child_handler(self, pid: int) -> bool: ... + @abstractmethod + def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + @abstractmethod + def close(self) -> None: ... + @abstractmethod + def __enter__(self) -> Self: ... + @abstractmethod + def __exit__( + self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None + ) -> None: ... + @abstractmethod + def is_active(self) -> bool: ... -else: - class AbstractChildWatcher: - @abstractmethod - def add_child_handler( - self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] - ) -> None: ... - @abstractmethod - def remove_child_handler(self, pid: int) -> bool: ... - @abstractmethod - def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - @abstractmethod - def close(self) -> None: ... - @abstractmethod - def __enter__(self) -> Self: ... - @abstractmethod - def __exit__( - self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None - ) -> None: ... - @abstractmethod - def is_active(self) -> bool: ... + else: + class AbstractChildWatcher: + @abstractmethod + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + @abstractmethod + def remove_child_handler(self, pid: int) -> bool: ... + @abstractmethod + def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + @abstractmethod + def close(self) -> None: ... + @abstractmethod + def __enter__(self) -> Self: ... + @abstractmethod + def __exit__( + self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None + ) -> None: ... + @abstractmethod + def is_active(self) -> bool: ... if sys.platform != "win32": - if sys.version_info >= (3, 9): + if sys.version_info >= (3, 14): + __all__ = ("SelectorEventLoop", "DefaultEventLoopPolicy") + elif sys.version_info >= (3, 9): __all__ = ( "SelectorEventLoop", "AbstractChildWatcher", @@ -79,118 +82,137 @@ if sys.platform != "win32": "DefaultEventLoopPolicy", ) - # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub. - # See discussion in #7412 - class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta): - def close(self) -> None: ... - def is_active(self) -> bool: ... - def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub. + # See discussion in #7412 + class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta): + def close(self) -> None: ... + def is_active(self) -> bool: ... + def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - if sys.version_info >= (3, 12): - @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") - class SafeChildWatcher(BaseChildWatcher): - def __enter__(self) -> Self: ... - def __exit__(self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None) -> None: ... - def add_child_handler( - self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] - ) -> None: ... - def remove_child_handler(self, pid: int) -> bool: ... + @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") + class SafeChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... - @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") - class FastChildWatcher(BaseChildWatcher): - def __enter__(self) -> Self: ... - def __exit__(self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None) -> None: ... - def add_child_handler( - self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] - ) -> None: ... - def remove_child_handler(self, pid: int) -> bool: ... + @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") + class FastChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... - else: - class SafeChildWatcher(BaseChildWatcher): - def __enter__(self) -> Self: ... - def __exit__(self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None) -> None: ... - def add_child_handler( - self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] - ) -> None: ... - def remove_child_handler(self, pid: int) -> bool: ... + else: + # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub. + # See discussion in #7412 + class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta): + def close(self) -> None: ... + def is_active(self) -> bool: ... + def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - class FastChildWatcher(BaseChildWatcher): - def __enter__(self) -> Self: ... - def __exit__(self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None) -> None: ... - def add_child_handler( - self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] - ) -> None: ... - def remove_child_handler(self, pid: int) -> bool: ... + class SafeChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + + class FastChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... class _UnixSelectorEventLoop(BaseSelectorEventLoop): ... class _UnixDefaultEventLoopPolicy(BaseDefaultEventLoopPolicy): - if sys.version_info >= (3, 12): - @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") - def get_child_watcher(self) -> AbstractChildWatcher: ... - @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") - def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... - else: - def get_child_watcher(self) -> AbstractChildWatcher: ... - def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... + if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") + def get_child_watcher(self) -> AbstractChildWatcher: ... + @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") + def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... + else: + def get_child_watcher(self) -> AbstractChildWatcher: ... + def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... SelectorEventLoop = _UnixSelectorEventLoop DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy - if sys.version_info >= (3, 12): - @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") - class MultiLoopChildWatcher(AbstractChildWatcher): - def is_active(self) -> bool: ... + if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + @deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14") + class MultiLoopChildWatcher(AbstractChildWatcher): + def is_active(self) -> bool: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + + else: + class MultiLoopChildWatcher(AbstractChildWatcher): + def is_active(self) -> bool: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + + if sys.version_info < (3, 14): + class ThreadedChildWatcher(AbstractChildWatcher): + def is_active(self) -> Literal[True]: ... def close(self) -> None: ... def __enter__(self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... + def __del__(self) -> None: ... def add_child_handler( self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] ) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - else: - class MultiLoopChildWatcher(AbstractChildWatcher): - def is_active(self) -> bool: ... - def close(self) -> None: ... - def __enter__(self) -> Self: ... - def __exit__( - self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None - ) -> None: ... - def add_child_handler( - self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] - ) -> None: ... - def remove_child_handler(self, pid: int) -> bool: ... - def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - - class ThreadedChildWatcher(AbstractChildWatcher): - def is_active(self) -> Literal[True]: ... - def close(self) -> None: ... - def __enter__(self) -> Self: ... - def __exit__( - self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None - ) -> None: ... - def __del__(self) -> None: ... - def add_child_handler( - self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] - ) -> None: ... - def remove_child_handler(self, pid: int) -> bool: ... - def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - - if sys.version_info >= (3, 9): - class PidfdChildWatcher(AbstractChildWatcher): - def __enter__(self) -> Self: ... - def __exit__( - self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None - ) -> None: ... - def is_active(self) -> bool: ... - def close(self) -> None: ... - def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - def add_child_handler( - self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] - ) -> None: ... - def remove_child_handler(self, pid: int) -> bool: ... + if sys.version_info >= (3, 9): + class PidfdChildWatcher(AbstractChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def is_active(self) -> bool: ... + def close(self) -> None: ... + def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/windows_events.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/windows_events.pyi index 9c150ee16..97aa52ff8 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/windows_events.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/asyncio/windows_events.pyi @@ -74,8 +74,9 @@ if sys.platform == "win32": class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): _loop_factory: ClassVar[type[SelectorEventLoop]] - def get_child_watcher(self) -> NoReturn: ... - def set_child_watcher(self, watcher: Any) -> NoReturn: ... + if sys.version_info < (3, 14): + def get_child_watcher(self) -> NoReturn: ... + def set_child_watcher(self, watcher: Any) -> NoReturn: ... class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): _loop_factory: ClassVar[type[ProactorEventLoop]] diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/builtins.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/builtins.pyi index 53e00ec6a..ef5d7f305 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/builtins.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/builtins.pyi @@ -1673,9 +1673,9 @@ def pow(base: float, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> @overload def pow(base: complex, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> complex: ... @overload -def pow(base: _SupportsPow2[_E, _T_co], exp: _E, mod: None = None) -> _T_co: ... +def pow(base: _SupportsPow2[_E, _T_co], exp: _E, mod: None = None) -> _T_co: ... # type: ignore[overload-overlap] @overload -def pow(base: _SupportsPow3NoneOnly[_E, _T_co], exp: _E, mod: None = None) -> _T_co: ... +def pow(base: _SupportsPow3NoneOnly[_E, _T_co], exp: _E, mod: None = None) -> _T_co: ... # type: ignore[overload-overlap] @overload def pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M) -> _T_co: ... @overload diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/dataclasses.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/dataclasses.pyi index 30489e6f8..626608e8a 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/dataclasses.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/dataclasses.pyi @@ -108,7 +108,7 @@ class _DefaultFactory(Protocol[_T_co]): class Field(Generic[_T]): name: str - type: Type[_T] + type: Type[_T] | str | Any default: _T | Literal[_MISSING_TYPE.MISSING] default_factory: _DefaultFactory[_T] | Literal[_MISSING_TYPE.MISSING] repr: bool diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/logging/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/logging/__init__.pyi index f25abff83..4c6163257 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/logging/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/logging/__init__.pyi @@ -8,7 +8,7 @@ from string import Template from time import struct_time from types import FrameType, TracebackType from typing import Any, ClassVar, Generic, Literal, Protocol, TextIO, TypeVar, overload -from typing_extensions import Self, TypeAlias +from typing_extensions import Self, TypeAlias, deprecated if sys.version_info >= (3, 11): from types import GenericAlias @@ -574,11 +574,8 @@ def disable(level: int = 50) -> None: ... def addLevelName(level: int, levelName: str) -> None: ... @overload def getLevelName(level: int) -> str: ... - -# The str -> int case is considered a mistake, but retained for backward -# compatibility. See -# https://docs.python.org/3/library/logging.html#logging.getLevelName. @overload +@deprecated("The str -> int case is considered a mistake.") def getLevelName(level: str) -> Any: ... if sys.version_info >= (3, 11): diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/mmap.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/mmap.pyi index 2d27e7b2a..7688970e5 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/mmap.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/mmap.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import ReadableBuffer, Unused from collections.abc import Iterable, Iterator, Sized -from typing import NoReturn, overload +from typing import Final, NoReturn, overload from typing_extensions import Self ACCESS_DEFAULT: int @@ -113,3 +113,9 @@ if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win if sys.version_info >= (3, 10) and sys.platform == "darwin": MADV_FREE_REUSABLE: int MADV_FREE_REUSE: int + +if sys.version_info >= (3, 13) and sys.platform != "win32": + MAP_32BIT: Final = 32768 + +if sys.version_info >= (3, 13) and sys.platform == "darwin": + MAP_TPRO: Final = 524288 diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/multiprocessing/context.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/multiprocessing/context.pyi index 9a45a8155..605be4686 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/multiprocessing/context.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/multiprocessing/context.pyi @@ -92,17 +92,21 @@ class BaseContext: @overload def Value(self, typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = True) -> Any: ... @overload + def Array( + self, typecode_or_type: type[_SimpleCData[_T]], size_or_initializer: int | Sequence[Any], *, lock: Literal[False] + ) -> SynchronizedArray[_T]: ... + @overload def Array( self, typecode_or_type: type[c_char], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True ) -> SynchronizedString: ... @overload def Array( - self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False] - ) -> SynchronizedArray[_CT]: ... - @overload - def Array( - self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True - ) -> SynchronizedArray[_CT]: ... + self, + typecode_or_type: type[_SimpleCData[_T]], + size_or_initializer: int | Sequence[Any], + *, + lock: Literal[True] | _LockLike = True, + ) -> SynchronizedArray[_T]: ... @overload def Array( self, typecode_or_type: str, size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/multiprocessing/sharedctypes.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/multiprocessing/sharedctypes.pyi index 4093a97e6..2b96ff047 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/multiprocessing/sharedctypes.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/multiprocessing/sharedctypes.pyi @@ -39,12 +39,20 @@ def Array( ) -> _CT: ... @overload def Array( - typecode_or_type: type[_CT], + typecode_or_type: type[c_char], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True, ctx: BaseContext | None = None, -) -> SynchronizedArray[_CT]: ... +) -> SynchronizedString: ... +@overload +def Array( + typecode_or_type: type[_SimpleCData[_T]], + size_or_initializer: int | Sequence[Any], + *, + lock: Literal[True] | _LockLike = True, + ctx: BaseContext | None = None, +) -> SynchronizedArray[_T]: ... @overload def Array( typecode_or_type: str, @@ -65,9 +73,11 @@ def copy(obj: _CT) -> _CT: ... @overload def synchronized(obj: _SimpleCData[_T], lock: _LockLike | None = None, ctx: Any | None = None) -> Synchronized[_T]: ... @overload -def synchronized(obj: ctypes.Array[c_char], lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedString: ... +def synchronized(obj: ctypes.Array[c_char], lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedString: ... # type: ignore @overload -def synchronized(obj: ctypes.Array[_CT], lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedArray[_CT]: ... +def synchronized( + obj: ctypes.Array[_SimpleCData[_T]], lock: _LockLike | None = None, ctx: Any | None = None +) -> SynchronizedArray[_T]: ... @overload def synchronized(obj: _CT, lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedBase[_CT]: ... @@ -89,19 +99,30 @@ class SynchronizedBase(Generic[_CT]): class Synchronized(SynchronizedBase[_SimpleCData[_T]], Generic[_T]): value: _T -class SynchronizedArray(SynchronizedBase[ctypes.Array[_CT]], Generic[_CT]): +class SynchronizedArray(SynchronizedBase[ctypes.Array[_SimpleCData[_T]]], Generic[_T]): def __len__(self) -> int: ... @overload - def __getitem__(self, i: slice) -> list[_CT]: ... + def __getitem__(self, i: slice) -> list[_T]: ... @overload - def __getitem__(self, i: int) -> _CT: ... + def __getitem__(self, i: int) -> _T: ... @overload - def __setitem__(self, i: slice, value: Iterable[_CT]) -> None: ... + def __setitem__(self, i: slice, value: Iterable[_T]) -> None: ... @overload - def __setitem__(self, i: int, value: _CT) -> None: ... - def __getslice__(self, start: int, stop: int) -> list[_CT]: ... - def __setslice__(self, start: int, stop: int, values: Iterable[_CT]) -> None: ... + def __setitem__(self, i: int, value: _T) -> None: ... + def __getslice__(self, start: int, stop: int) -> list[_T]: ... + def __setslice__(self, start: int, stop: int, values: Iterable[_T]) -> None: ... + +class SynchronizedString(SynchronizedArray[bytes]): + @overload # type: ignore[override] + def __getitem__(self, i: slice) -> bytes: ... + @overload # type: ignore[override] + def __getitem__(self, i: int) -> bytes: ... + @overload # type: ignore[override] + def __setitem__(self, i: slice, value: bytes) -> None: ... + @overload # type: ignore[override] + def __setitem__(self, i: int, value: bytes) -> None: ... # type: ignore[override] + def __getslice__(self, start: int, stop: int) -> bytes: ... # type: ignore[override] + def __setslice__(self, start: int, stop: int, values: bytes) -> None: ... # type: ignore[override] -class SynchronizedString(SynchronizedArray[c_char]): value: bytes raw: bytes diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/os/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/os/__init__.pyi index 31c5d2aa3..9b00117a5 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/os/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/os/__init__.pyi @@ -914,8 +914,8 @@ if sys.platform != "win32": def forkpty() -> tuple[int, int]: ... # some flavors of Unix def killpg(pgid: int, signal: int, /) -> None: ... def nice(increment: int, /) -> int: ... - if sys.platform != "darwin": - def plock(op: int, /) -> None: ... # ???op is int? + if sys.platform != "darwin" and sys.platform != "linux": + def plock(op: int, /) -> None: ... class _wrap_close(_TextIOWrapper): def __init__(self, stream: _TextIOWrapper, proc: Popen[str]) -> None: ... @@ -1141,16 +1141,16 @@ if sys.version_info >= (3, 10) and sys.platform == "linux": if sys.version_info >= (3, 12) and sys.platform == "linux": CLONE_FILES: int CLONE_FS: int - CLONE_NEWCGROUP: int - CLONE_NEWIPC: int - CLONE_NEWNET: int + CLONE_NEWCGROUP: int # Linux 4.6+ + CLONE_NEWIPC: int # Linux 2.6.19+ + CLONE_NEWNET: int # Linux 2.6.24+ CLONE_NEWNS: int - CLONE_NEWPID: int - CLONE_NEWTIME: int - CLONE_NEWUSER: int - CLONE_NEWUTS: int + CLONE_NEWPID: int # Linux 3.8+ + CLONE_NEWTIME: int # Linux 5.6+ + CLONE_NEWUSER: int # Linux 3.8+ + CLONE_NEWUTS: int # Linux 2.6.19+ CLONE_SIGHAND: int - CLONE_SYSVSEM: int + CLONE_SYSVSEM: int # Linux 2.6.26+ CLONE_THREAD: int CLONE_VM: int def unshare(flags: int) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/posixpath.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/posixpath.pyi index e5f5fa0d8..31406f8df 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/posixpath.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/posixpath.pyi @@ -77,11 +77,7 @@ pathsep: LiteralString defpath: LiteralString devnull: LiteralString -# Overloads are necessary to work around python/mypy#3644. -@overload -def abspath(path: PathLike[AnyStr]) -> AnyStr: ... -@overload -def abspath(path: AnyStr) -> AnyStr: ... +def abspath(path: PathLike[AnyStr] | AnyStr) -> AnyStr: ... @overload def basename(p: PathLike[AnyStr]) -> AnyStr: ... @overload @@ -90,14 +86,8 @@ def basename(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... def dirname(p: PathLike[AnyStr]) -> AnyStr: ... @overload def dirname(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... -@overload -def expanduser(path: PathLike[AnyStr]) -> AnyStr: ... -@overload -def expanduser(path: AnyStr) -> AnyStr: ... -@overload -def expandvars(path: PathLike[AnyStr]) -> AnyStr: ... -@overload -def expandvars(path: AnyStr) -> AnyStr: ... +def expanduser(path: PathLike[AnyStr] | AnyStr) -> AnyStr: ... +def expandvars(path: PathLike[AnyStr] | AnyStr) -> AnyStr: ... @overload def normcase(s: PathLike[AnyStr]) -> AnyStr: ... @overload diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/spwd.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/spwd.pyi index 67ad3bfc7..3a5d39997 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/spwd.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/spwd.pyi @@ -36,6 +36,11 @@ if sys.platform != "win32": def sp_expire(self) -> int: ... @property def sp_flag(self) -> int: ... + # Deprecated aliases below. + @property + def sp_nam(self) -> str: ... + @property + def sp_pwd(self) -> str: ... def getspall() -> list[struct_spwd]: ... def getspnam(arg: str, /) -> struct_spwd: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/subprocess.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/subprocess.pyi index 6234ecc02..b01bac245 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/subprocess.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/subprocess.pyi @@ -889,6 +889,7 @@ if sys.version_info >= (3, 11): start_new_session: bool = False, pass_fds: Collection[int] = ..., *, + encoding: str | None = None, timeout: float | None = None, text: bool | None = None, user: str | int | None = None, @@ -920,6 +921,7 @@ elif sys.version_info >= (3, 10): start_new_session: bool = False, pass_fds: Collection[int] = ..., *, + encoding: str | None = None, timeout: float | None = None, text: bool | None = None, user: str | int | None = None, @@ -950,6 +952,7 @@ elif sys.version_info >= (3, 9): start_new_session: bool = False, pass_fds: Collection[int] = ..., *, + encoding: str | None = None, timeout: float | None = None, text: bool | None = None, user: str | int | None = None, @@ -978,6 +981,7 @@ else: start_new_session: bool = False, pass_fds: Collection[int] = ..., *, + encoding: str | None = None, timeout: float | None = None, text: bool | None = None, ) -> int: ... @@ -1005,6 +1009,7 @@ if sys.version_info >= (3, 11): pass_fds: Collection[int] = ..., timeout: float | None = ..., *, + encoding: str | None = None, text: bool | None = None, user: str | int | None = None, group: str | int | None = None, @@ -1036,6 +1041,7 @@ elif sys.version_info >= (3, 10): pass_fds: Collection[int] = ..., timeout: float | None = ..., *, + encoding: str | None = None, text: bool | None = None, user: str | int | None = None, group: str | int | None = None, @@ -1066,6 +1072,7 @@ elif sys.version_info >= (3, 9): pass_fds: Collection[int] = ..., timeout: float | None = ..., *, + encoding: str | None = None, text: bool | None = None, user: str | int | None = None, group: str | int | None = None, @@ -1094,6 +1101,7 @@ else: pass_fds: Collection[int] = ..., timeout: float | None = ..., *, + encoding: str | None = None, text: bool | None = None, ) -> int: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/tarfile.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/tarfile.pyi index e52099464..d6adf21c1 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/tarfile.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/tarfile.pyi @@ -103,10 +103,13 @@ PAX_NAME_FIELDS: set[str] ENCODING: str +_FileCreationModes: TypeAlias = Literal["a", "w", "x"] + +@overload def open( name: StrOrBytesPath | None = None, mode: str = "r", - fileobj: IO[bytes] | None = None, # depends on mode + fileobj: IO[bytes] | None = None, bufsize: int = 10240, *, format: int | None = ..., @@ -121,6 +124,25 @@ def open( compresslevel: int | None = ..., preset: Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | None = ..., ) -> TarFile: ... +@overload +def open( + name: StrOrBytesPath | None = None, + mode: _FileCreationModes = ..., + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: int | None = ..., + errorlevel: int | None = ..., + compresslevel: int | None = ..., + preset: int | None = ..., +) -> TarFile: ... class ExFileObject(io.BufferedReader): def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/telnetlib.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/telnetlib.pyi index d244d54f2..294a1cb12 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/telnetlib.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/telnetlib.pyi @@ -88,6 +88,7 @@ NOOPT: bytes class Telnet: host: str | None # undocumented + sock: socket.socket | None # undocumented def __init__(self, host: str | None = None, port: int = 0, timeout: float = ...) -> None: ... def open(self, host: str, port: int = 0, timeout: float = ...) -> None: ... def msg(self, msg: str, *args: Any) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/typing.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/typing.pyi index f04b2d858..92427f91f 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/typing.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/typing.pyi @@ -21,7 +21,7 @@ from types import ( TracebackType, WrapperDescriptorType, ) -from typing_extensions import Never as _Never, ParamSpec as _ParamSpec +from typing_extensions import Never as _Never, ParamSpec as _ParamSpec, deprecated if sys.version_info >= (3, 9): from types import GenericAlias @@ -991,11 +991,30 @@ class ForwardRef: def __init__(self, arg: str, is_argument: bool = True) -> None: ... if sys.version_info >= (3, 13): + @overload + @deprecated( + "Failing to pass a value to the 'type_params' parameter of ForwardRef._evaluate() is deprecated, " + "as it leads to incorrect behaviour when evaluating a stringified annotation " + "that references a PEP 695 type parameter. It will be disallowed in Python 3.15." + ) + def _evaluate( + self, globalns: dict[str, Any] | None, localns: dict[str, Any] | None, *, recursive_guard: frozenset[str] + ) -> Any | None: ... + @overload def _evaluate( self, globalns: dict[str, Any] | None, localns: dict[str, Any] | None, - type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = ..., + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...], + *, + recursive_guard: frozenset[str], + ) -> Any | None: ... + elif sys.version_info >= (3, 12): + def _evaluate( + self, + globalns: dict[str, Any] | None, + localns: dict[str, Any] | None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None, *, recursive_guard: frozenset[str], ) -> Any | None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/weakref.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/weakref.pyi index e34512423..aaba7ffc9 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/weakref.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/weakref.pyi @@ -41,7 +41,10 @@ _P = ParamSpec("_P") ProxyTypes: tuple[type[Any], ...] class WeakMethod(ref[_CallableT]): - def __new__(cls, meth: _CallableT, callback: Callable[[Self], object] | None = None) -> Self: ... + # `ref` is implemented in `C` so positional-only arguments are enforced, but not in `WeakMethod`. + def __new__( # pyright: ignore[reportInconsistentConstructor] + cls, meth: _CallableT, callback: Callable[[Self], Any] | None = None + ) -> Self: ... def __call__(self) -> _CallableT | None: ... def __eq__(self, other: object) -> bool: ... def __ne__(self, other: object) -> bool: ... diff --git a/packages/pyright-internal/typeshed-fallback/stdlib/xml/sax/handler.pyi b/packages/pyright-internal/typeshed-fallback/stdlib/xml/sax/handler.pyi index 30fe31d51..7b7c69048 100644 --- a/packages/pyright-internal/typeshed-fallback/stdlib/xml/sax/handler.pyi +++ b/packages/pyright-internal/typeshed-fallback/stdlib/xml/sax/handler.pyi @@ -14,7 +14,7 @@ class ContentHandler: def startDocument(self) -> None: ... def endDocument(self) -> None: ... def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ... - def endPrefixMapping(self, prefix) -> None: ... + def endPrefixMapping(self, prefix: str | None) -> None: ... def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ... def endElement(self, name: str) -> None: ... def startElementNS(self, name: tuple[str, str], qname: str, attrs: xmlreader.AttributesNSImpl) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/Flask-SocketIO/flask_socketio/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/Flask-SocketIO/flask_socketio/__init__.pyi index ca444323b..68fdd4cf9 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/Flask-SocketIO/flask_socketio/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/Flask-SocketIO/flask_socketio/__init__.pyi @@ -7,8 +7,8 @@ from typing_extensions import ParamSpec, TypeAlias from flask import Flask from flask.testing import FlaskClient -from .namespace import Namespace -from .test_client import SocketIOTestClient +from .namespace import Namespace as Namespace +from .test_client import SocketIOTestClient as SocketIOTestClient _P = ParamSpec("_P") _R_co = TypeVar("_R_co", covariant=True) @@ -96,9 +96,9 @@ class SocketIO: port: int | None = None, *, debug: bool = True, - use_reloader: bool, + use_reloader: bool = ..., reloader_options: dict[str, Incomplete] = {}, - log_output: bool, + log_output: bool = ..., allow_unsafe_werkzeug: bool = False, **kwargs, ) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/METADATA.toml index 950f1bd80..d649874b9 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/METADATA.toml @@ -1,4 +1,4 @@ -version = "23.2.*" +version = "24.1.*" upstream_repository = "https://github.com/Tinche/aiofiles" [tool.stubtest] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/base.pyi b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/base.pyi index c705acb30..ea79abf48 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/base.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/base.pyi @@ -1,12 +1,11 @@ -from collections.abc import Callable, Coroutine, Generator, Iterator -from types import CodeType, FrameType, TracebackType, coroutine +from collections.abc import Awaitable, Callable, Generator +from contextlib import AbstractAsyncContextManager +from types import TracebackType from typing import Any, BinaryIO, Generic, TextIO, TypeVar from typing_extensions import Self _T = TypeVar("_T") -_T_co = TypeVar("_T_co", covariant=True) _V_co = TypeVar("_V_co", covariant=True) -_T_contra = TypeVar("_T_contra", contravariant=True) class AsyncBase(Generic[_T]): def __init__(self, file: str, loop: Any, executor: Any) -> None: ... @@ -16,22 +15,9 @@ class AsyncBase(Generic[_T]): class AsyncIndirectBase(AsyncBase[_T]): def __init__(self, name: str, loop: Any, executor: Any, indirect: Callable[[], TextIO | BinaryIO]) -> None: ... -class AiofilesContextManager(Generic[_T_co, _T_contra, _V_co]): - def __init__(self, coro: Coroutine[_T_co, _T_contra, _V_co]) -> None: ... - def send(self, value: _T_contra) -> _T_co: ... - def throw(self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None) -> _T_co: ... - def close(self) -> None: ... - @property - def gi_frame(self) -> FrameType: ... - @property - def gi_running(self) -> bool: ... - @property - def gi_code(self) -> CodeType: ... - def __next__(self) -> _T_co: ... - @coroutine - def __iter__(self) -> Iterator[Coroutine[_T_co, _T_contra, _V_co]]: ... - def __await__(self) -> Generator[Any, None, _V_co]: ... - async def __anext__(self) -> _V_co: ... +class AiofilesContextManager(Awaitable[_V_co], AbstractAsyncContextManager[_V_co]): + def __init__(self, coro: Awaitable[_V_co]) -> None: ... + def __await__(self) -> Generator[Any, Any, _V_co]: ... async def __aenter__(self) -> _V_co: ... async def __aexit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None diff --git a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/os.pyi b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/os.pyi index 54e601040..5a3de3b59 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/os.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/os.pyi @@ -27,6 +27,7 @@ __all__ = [ "scandir", "access", "wrap", + "getcwd", ] if sys.platform != "win32": @@ -118,6 +119,7 @@ async def listdir(path: int, *, loop: AbstractEventLoop | None = ..., executor: async def access( path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, effective_ids: bool = False, follow_symlinks: bool = True ) -> bool: ... +async def getcwd() -> str: ... if sys.platform != "win32": from os import statvfs_result diff --git a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/ospath.pyi b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/ospath.pyi index 384996d24..a58637536 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/ospath.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/ospath.pyi @@ -1,7 +1,8 @@ from _typeshed import FileDescriptorOrPath from asyncio.events import AbstractEventLoop from collections.abc import Awaitable, Callable -from typing import Any, TypeVar +from os import PathLike +from typing import Any, AnyStr, TypeVar _R = TypeVar("_R") @@ -9,6 +10,8 @@ def wrap(func: Callable[..., _R]) -> Callable[..., Awaitable[_R]]: ... async def exists(path: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Any = ...) -> bool: ... async def isfile(path: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Any = ...) -> bool: ... async def isdir(s: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Any = ...) -> bool: ... +async def islink(path: FileDescriptorOrPath) -> bool: ... +async def ismount(path: FileDescriptorOrPath) -> bool: ... async def getsize(filename: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Any = ...) -> int: ... async def getmtime(filename: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Any = ...) -> float: ... async def getatime(filename: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Any = ...) -> float: ... @@ -17,5 +20,4 @@ async def samefile( f1: FileDescriptorOrPath, f2: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Any = ... ) -> bool: ... async def sameopenfile(fp1: int, fp2: int, *, loop: AbstractEventLoop | None = ..., executor: Any = ...) -> bool: ... -async def islink(path: FileDescriptorOrPath) -> bool: ... -async def ismount(path: FileDescriptorOrPath) -> bool: ... +async def abspath(path: PathLike[AnyStr] | AnyStr) -> AnyStr: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/tempfile/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/tempfile/__init__.pyi index bfee5b17a..e8016aa8d 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/tempfile/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/tempfile/__init__.pyi @@ -1,3 +1,4 @@ +import sys from _typeshed import ( BytesPath, Incomplete, @@ -10,77 +11,13 @@ from _typeshed import ( StrPath, ) from asyncio import AbstractEventLoop -from typing import AnyStr, Literal, TypeVar, overload +from typing import AnyStr, Literal, overload from ..base import AiofilesContextManager from ..threadpool.binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO from ..threadpool.text import AsyncTextIOWrapper from .temptypes import AsyncTemporaryDirectory -_T_co = TypeVar("_T_co", covariant=True) -_V_co = TypeVar("_V_co", covariant=True) -_T_contra = TypeVar("_T_contra", contravariant=True) - -# Text mode: always returns AsyncTextIOWrapper -@overload -def NamedTemporaryFile( - mode: OpenTextMode, - buffering: int = -1, - encoding: str | None = None, - newline: str | None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: StrOrBytesPath | None = None, - delete: bool = True, - loop: AbstractEventLoop | None = None, - executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncTextIOWrapper]: ... - -# Unbuffered binary: returns a FileIO -@overload -def NamedTemporaryFile( - mode: OpenBinaryMode, - buffering: Literal[0], - encoding: None = None, - newline: None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: StrOrBytesPath | None = None, - delete: bool = True, - loop: AbstractEventLoop | None = None, - executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncFileIO]: ... - -# Buffered binary reading/updating: AsyncBufferedReader -@overload -def NamedTemporaryFile( - mode: OpenBinaryModeReading | OpenBinaryModeUpdating = "w+b", - buffering: Literal[-1, 1] = -1, - encoding: None = None, - newline: None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: StrOrBytesPath | None = None, - delete: bool = True, - loop: AbstractEventLoop | None = None, - executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncBufferedReader]: ... - -# Buffered binary writing: AsyncBufferedIOBase -@overload -def NamedTemporaryFile( - mode: OpenBinaryModeWriting, - buffering: Literal[-1, 1] = -1, - encoding: None = None, - newline: None = None, - suffix: AnyStr | None = None, - prefix: AnyStr | None = None, - dir: StrOrBytesPath | None = None, - delete: bool = True, - loop: AbstractEventLoop | None = None, - executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncBufferedIOBase]: ... - # Text mode: always returns AsyncTextIOWrapper @overload def TemporaryFile( @@ -93,7 +30,7 @@ def TemporaryFile( dir: StrOrBytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncTextIOWrapper]: ... +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... # Unbuffered binary: returns a FileIO @overload @@ -107,7 +44,7 @@ def TemporaryFile( dir: StrOrBytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncFileIO]: ... +) -> AiofilesContextManager[AsyncFileIO]: ... # Buffered binary reading/updating: AsyncBufferedReader @overload @@ -121,7 +58,7 @@ def TemporaryFile( dir: StrOrBytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncBufferedReader]: ... +) -> AiofilesContextManager[AsyncBufferedReader]: ... # Buffered binary writing: AsyncBufferedIOBase @overload @@ -135,7 +72,134 @@ def TemporaryFile( dir: StrOrBytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncBufferedIOBase]: ... +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... + +# 3.12 added `delete_on_close` +if sys.version_info >= (3, 12): + # Text mode: always returns AsyncTextIOWrapper + @overload + def NamedTemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Incomplete | None = None, + ) -> AiofilesContextManager[AsyncTextIOWrapper]: ... + + # Unbuffered binary: returns a FileIO + @overload + def NamedTemporaryFile( + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Incomplete | None = None, + ) -> AiofilesContextManager[AsyncFileIO]: ... + + # Buffered binary reading/updating: AsyncBufferedReader + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeReading | OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Incomplete | None = None, + ) -> AiofilesContextManager[AsyncBufferedReader]: ... + + # Buffered binary writing: AsyncBufferedIOBase + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Incomplete | None = None, + ) -> AiofilesContextManager[AsyncBufferedIOBase]: ... + +else: + # Text mode: always returns AsyncTextIOWrapper + @overload + def NamedTemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Incomplete | None = None, + ) -> AiofilesContextManager[AsyncTextIOWrapper]: ... + + # Unbuffered binary: returns a FileIO + @overload + def NamedTemporaryFile( + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Incomplete | None = None, + ) -> AiofilesContextManager[AsyncFileIO]: ... + + # Buffered binary reading/updating: AsyncBufferedReader + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeReading | OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Incomplete | None = None, + ) -> AiofilesContextManager[AsyncBufferedReader]: ... + + # Buffered binary writing: AsyncBufferedIOBase + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Incomplete | None = None, + ) -> AiofilesContextManager[AsyncBufferedIOBase]: ... # Text mode: always returns AsyncTextIOWrapper @overload @@ -151,7 +215,7 @@ def SpooledTemporaryFile( dir: StrOrBytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncTextIOWrapper]: ... +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... @overload def SpooledTemporaryFile( max_size: int, @@ -164,7 +228,7 @@ def SpooledTemporaryFile( dir: StrOrBytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncTextIOWrapper]: ... +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... # Unbuffered binary: returns a FileIO @overload @@ -180,7 +244,7 @@ def SpooledTemporaryFile( dir: StrOrBytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncFileIO]: ... +) -> AiofilesContextManager[AsyncFileIO]: ... @overload def SpooledTemporaryFile( max_size: int, @@ -193,7 +257,7 @@ def SpooledTemporaryFile( dir: StrOrBytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncFileIO]: ... +) -> AiofilesContextManager[AsyncFileIO]: ... # Buffered binary reading/updating: AsyncBufferedReader @overload @@ -208,7 +272,7 @@ def SpooledTemporaryFile( dir: StrOrBytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncBufferedReader]: ... +) -> AiofilesContextManager[AsyncBufferedReader]: ... # Buffered binary writing: AsyncBufferedIOBase @overload @@ -224,7 +288,7 @@ def SpooledTemporaryFile( dir: StrOrBytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncBufferedIOBase]: ... +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... @overload def SpooledTemporaryFile( max_size: int, @@ -237,7 +301,7 @@ def SpooledTemporaryFile( dir: StrOrBytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncBufferedIOBase]: ... +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... @overload def TemporaryDirectory( suffix: str | None = None, @@ -245,7 +309,7 @@ def TemporaryDirectory( dir: StrPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManagerTempDir[None, None, AsyncTemporaryDirectory]: ... +) -> AiofilesContextManagerTempDir: ... @overload def TemporaryDirectory( suffix: bytes | None = None, @@ -253,7 +317,7 @@ def TemporaryDirectory( dir: BytesPath | None = None, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManagerTempDir[None, None, AsyncTemporaryDirectory]: ... +) -> AiofilesContextManagerTempDir: ... -class AiofilesContextManagerTempDir(AiofilesContextManager[_T_co, _T_contra, _V_co]): +class AiofilesContextManagerTempDir(AiofilesContextManager[AsyncTemporaryDirectory]): async def __aenter__(self) -> str: ... # type: ignore[override] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/threadpool/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/threadpool/__init__.pyi index a7154e759..00c587ccd 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/threadpool/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/aiofiles/aiofiles/threadpool/__init__.pyi @@ -32,7 +32,7 @@ def open( *, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncTextIOWrapper]: ... +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... # Unbuffered binary: returns a FileIO @overload @@ -48,7 +48,7 @@ def open( *, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncFileIO]: ... +) -> AiofilesContextManager[AsyncFileIO]: ... # Buffered binary reading/updating: AsyncBufferedReader @overload @@ -64,7 +64,7 @@ def open( *, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncBufferedReader]: ... +) -> AiofilesContextManager[AsyncBufferedReader]: ... # Buffered binary writing: AsyncBufferedIOBase @overload @@ -80,7 +80,7 @@ def open( *, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, AsyncBufferedIOBase]: ... +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... # Buffering cannot be determined: fall back to _UnknownAsyncBinaryIO @overload @@ -96,7 +96,7 @@ def open( *, loop: AbstractEventLoop | None = None, executor: Incomplete | None = None, -) -> AiofilesContextManager[None, None, _UnknownAsyncBinaryIO]: ... +) -> AiofilesContextManager[_UnknownAsyncBinaryIO]: ... stdin: AsyncTextIndirectIOWrapper stdout: AsyncTextIndirectIOWrapper diff --git a/packages/pyright-internal/typeshed-fallback/stubs/assertpy/assertpy/extracting.pyi b/packages/pyright-internal/typeshed-fallback/stubs/assertpy/assertpy/extracting.pyi index c8de113d3..da161a870 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/assertpy/assertpy/extracting.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/assertpy/assertpy/extracting.pyi @@ -1,7 +1,13 @@ +from collections.abc import Callable, Iterable as _Iterable, Mapping from typing import Any from typing_extensions import Self __tracebackhide__: bool class ExtractingMixin: - def extracting(self, *names: Any, **kwargs: dict[str, Any]) -> Self: ... + def extracting( + self, + *names: str, + filter: str | Mapping[str, Any] | Callable[[Any], bool], + sort: str | _Iterable[str] | Callable[[Any], Any], + ) -> Self: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/_types.pyi b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/_types.pyi new file mode 100644 index 000000000..a146f2a1e --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/_types.pyi @@ -0,0 +1,8 @@ +# Internal-use module for types shared by multiple modules. +# This does not match a module in docker-py. + +from typing_extensions import TypeAlias + +# Type alias for JSON, explained at: +# https://github.com/python/typing/issues/182#issuecomment-1320974824. +JSON: TypeAlias = dict[str, JSON] | list[JSON] | str | int | float | bool | None diff --git a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/container.pyi b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/container.pyi index 453863adc..e87d26cca 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/container.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/container.pyi @@ -154,10 +154,10 @@ class ContainerApiMixin: def rename(self, container: _Container, name: str) -> None: ... def resize(self, container: _Container, height: int, width: int) -> None: ... def restart(self, container: _Container, timeout: int = 10) -> None: ... - def start(self, container: _Container, *args, **kwargs) -> None: ... + def start(self, container: _Container) -> None: ... def stats(self, container: _Container, decode: bool | None = None, stream: bool = True, one_shot: bool | None = None): ... def stop(self, container: _Container, timeout: int | None = None) -> None: ... - def top(self, container: _Container, ps_args: str | None = None): ... + def top(self, container: _Container, ps_args: str | None = None) -> str: ... def unpause(self, container: _Container) -> None: ... def update_container( self, diff --git a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/image.pyi b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/image.pyi index f274a2338..034bd633b 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/image.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/image.pyi @@ -1,4 +1,5 @@ from _typeshed import Incomplete +from typing import Any log: Incomplete @@ -39,9 +40,9 @@ class ImageApiMixin: repository: str, tag: str | None = None, stream: bool = False, - auth_config: Incomplete | None = None, + auth_config: dict[str, Any] | None = None, decode: bool = False, - platform: Incomplete | None = None, + platform: str | None = None, all_tags: bool = False, ): ... def push( diff --git a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/network.pyi b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/network.pyi index f387a42e3..fff9fdfdb 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/network.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/api/network.pyi @@ -1,28 +1,45 @@ from _typeshed import Incomplete +from typing import Any, Literal, TypedDict, type_check_only +from typing_extensions import TypeAlias + +from docker.types import IPAMConfig + +@type_check_only +class _HasId(TypedDict): + Id: str + +@type_check_only +class _HasID(TypedDict): + ID: str + +_Network: TypeAlias = _HasId | _HasID | str +_Container: TypeAlias = _HasId | _HasID | str class NetworkApiMixin: def networks(self, names: Incomplete | None = None, ids: Incomplete | None = None, filters: Incomplete | None = None): ... def create_network( self, - name, - driver: Incomplete | None = None, - options: Incomplete | None = None, - ipam: Incomplete | None = None, - check_duplicate: Incomplete | None = None, + name: str, + driver: str | None = None, + options: dict[str, Any] | None = None, + ipam: IPAMConfig | None = None, + check_duplicate: bool | None = None, internal: bool = False, - labels: Incomplete | None = None, + labels: dict[str, Any] | None = None, enable_ipv6: bool = False, - attachable: Incomplete | None = None, - scope: Incomplete | None = None, - ingress: Incomplete | None = None, - ): ... + attachable: bool | None = None, + scope: Literal["local", "global", "swarm"] | None = None, + ingress: bool | None = None, + ) -> dict[str, str]: ... def prune_networks(self, filters: Incomplete | None = None): ... - def remove_network(self, net_id) -> None: ... - def inspect_network(self, net_id, verbose: Incomplete | None = None, scope: Incomplete | None = None): ... + def remove_network(self, net_id: _Network) -> None: ... + def inspect_network( + self, net_id: _Network, verbose: bool | None = None, scope: Literal["local", "global", "swarm"] | None = None + ): ... def connect_container_to_network( self, - container, - net_id, + container: _Container, + net_id: str, ipv4_address: Incomplete | None = None, ipv6_address: Incomplete | None = None, aliases: Incomplete | None = None, @@ -31,4 +48,4 @@ class NetworkApiMixin: driver_opt: Incomplete | None = None, mac_address: Incomplete | None = None, ) -> None: ... - def disconnect_container_from_network(self, container, net_id, force: bool = False) -> None: ... + def disconnect_container_from_network(self, container: _Container, net_id: str, force: bool = False) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/containers.pyi b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/containers.pyi index eeb40ee19..7ffe863dc 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/containers.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/containers.pyi @@ -71,22 +71,37 @@ class Container(Model): follow: bool | None = None, until: datetime.datetime | float | None = None, ) -> bytes: ... - def pause(self): ... + def pause(self) -> None: ... def put_archive(self, path: str, data) -> bool: ... - def remove(self, **kwargs) -> None: ... + def remove(self, *, v: bool = False, link: bool = False, force: bool = False) -> None: ... def rename(self, name: str): ... def resize(self, height: int, width: int): ... - def restart(self, **kwargs): ... - def start(self, **kwargs) -> None: ... + def restart(self, *, timeout: float | None = 10): ... + def start(self) -> None: ... def stats(self, **kwargs): ... def stop(self, *, timeout: float | None = None) -> None: ... - def top(self, **kwargs): ... + def top(self, *, ps_args: str | None = None) -> str: ... def unpause(self): ... - def update(self, **kwargs): ... + def update( + self, + *, + blkio_weight: int | None = None, + cpu_period: int | None = None, + cpu_quota: int | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + cpuset_mems: str | None = None, + mem_limit: float | str | None = None, + mem_reservation: float | str | None = None, + memswap_limit: int | str | None = None, + kernel_memory: int | str | None = None, + restart_policy: Incomplete | None = None, + ): ... def wait(self, *, timeout: float | None = None, condition: Literal["not-running", "next-exit", "removed"] | None = None): ... class ContainerCollection(Collection[Container]): model: type[Container] + @overload def run( self, image: str | Image, @@ -94,8 +109,22 @@ class ContainerCollection(Collection[Container]): stdout: bool = True, stderr: bool = False, remove: bool = False, + *, + detach: Literal[False] = False, **kwargs, - ): ... + ) -> bytes: ... + @overload + def run( + self, + image: str | Image, + command: str | list[str] | None = None, + stdout: bool = True, + stderr: bool = False, + remove: bool = False, + *, + detach: Literal[True], + **kwargs, + ) -> Container: ... def create(self, image: str, command: str | list[str] | None = None, **kwargs) -> Container: ... # type:ignore[override] def get(self, container_id: str) -> Container: ... def list( diff --git a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/images.pyi b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/images.pyi index 8646399ce..279bd6dcf 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/images.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/images.pyi @@ -1,11 +1,21 @@ from collections.abc import Iterator -from typing import Any, Literal, overload +from io import StringIO +from typing import IO, Any, Literal, TypedDict, overload, type_check_only from typing_extensions import TypeAlias +from docker._types import JSON + from .resource import Collection, Model _ImageList: TypeAlias = list[Image] # To resolve conflicts with a method called "list" +@type_check_only +class _ContainerLimits(TypedDict, total=False): + memory: int + memswap: int + cpushares: int + cpusetcpus: str + class Image(Model): @property def labels(self) -> dict[str, Any]: ... @@ -31,17 +41,69 @@ class RegistryData(Model): class ImageCollection(Collection[Image]): model: type[Image] - def build(self, **kwargs) -> tuple[Image, Iterator[Any]]: ... + def build( + self, + *, + path: str | None = None, + fileobj: StringIO | IO[bytes] | None = None, + tag: str | None = None, + quiet: bool = False, + nocache: bool = False, + rm: bool = False, + timeout: int | None = None, + custom_context: bool = False, + encoding: str | None = None, + pull: bool = False, + forcerm: bool = False, + dockerfile: str | None = None, + buildargs: dict[str, Any] | None = None, + container_limits: _ContainerLimits | None = None, + shmsize: int | None = None, + labels: dict[str, Any] | None = None, + # need to use list, because the type must be json serializable + cache_from: list[str] | None = None, + target: str | None = None, + network_mode: str | None = None, + squash: bool | None = None, + extra_hosts: list[str] | dict[str, str] | None = None, + platform: str | None = None, + isolation: str | None = None, + use_config_proxy: bool = True, + ) -> tuple[Image, Iterator[JSON]]: ... def get(self, name: str) -> Image: ... def get_registry_data(self, name, auth_config: dict[str, Any] | None = None) -> RegistryData: ... def list(self, name: str | None = None, all: bool = False, filters: dict[str, Any] | None = None) -> _ImageList: ... def load(self, data: bytes) -> _ImageList: ... @overload - def pull(self, repository: str, tag: str | None = None, all_tags: Literal[False] = False, **kwargs) -> Image: ... + def pull( + self, + repository: str, + tag: str | None = None, + all_tags: Literal[False] = False, + *, + platform: str | None = None, + auth_config: dict[str, Any] | None = None, + ) -> Image: ... @overload - def pull(self, repository: str, tag: str | None = None, *, all_tags: Literal[True], **kwargs) -> _ImageList: ... + def pull( + self, + repository: str, + tag: str | None = None, + *, + all_tags: Literal[True], + auth_config: dict[str, Any] | None = None, + platform: str | None = None, + ) -> _ImageList: ... @overload - def pull(self, repository: str, tag: str | None, all_tags: Literal[True], **kwargs) -> _ImageList: ... + def pull( + self, + repository: str, + tag: str | None, + all_tags: Literal[True], + *, + auth_config: dict[str, Any] | None = None, + platform: str | None = None, + ) -> _ImageList: ... def push(self, repository: str, tag: str | None = None, **kwargs): ... def remove(self, *args, **kwargs) -> None: ... def search(self, *args, **kwargs): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/networks.pyi b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/networks.pyi index e84babdfe..86cca6416 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/networks.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/models/networks.pyi @@ -1,4 +1,6 @@ -from typing import Any +from typing import Any, Literal + +from docker.types import IPAMConfig from .containers import Container from .resource import Collection, Model @@ -14,7 +16,22 @@ class Network(Model): class NetworkCollection(Collection[Network]): model: type[Network] - def create(self, name: str, *args, **kwargs) -> Network: ... # type:ignore[override] - def get(self, network_id: str, *args, **kwargs) -> Network: ... # type:ignore[override] + def create( # type:ignore[override] + self, + name: str, + driver: str | None = None, + options: dict[str, Any] | None = None, + ipam: IPAMConfig | None = None, + check_duplicate: bool | None = None, + internal: bool = False, + labels: dict[str, Any] | None = None, + enable_ipv6: bool = False, + attachable: bool | None = None, + scope: Literal["local", "global", "swarm"] | None = None, + ingress: bool | None = None, + ) -> Network: ... + def get( + self, network_id: str, verbose: bool | None = None, scope: Literal["local", "global", "swarm"] | None = None + ) -> Network: ... # type:ignore[override] def list(self, *args, **kwargs) -> list[Network]: ... def prune(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/types/containers.pyi b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/types/containers.pyi index 891137e94..d3b3a2fb6 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/types/containers.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/types/containers.pyi @@ -1,6 +1,14 @@ from _typeshed import Incomplete +from pathlib import Path +from typing import Literal, TypedDict, type_check_only from .base import DictType +from .services import Mount + +@type_check_only +class ContainerWeightDevice(TypedDict): + Path: Path + Weight: int class LogConfigTypesEnum: JSON: Incomplete @@ -63,71 +71,71 @@ class DeviceRequest(DictType): class HostConfig(dict[str, Incomplete]): def __init__( self, - version, + version: str, binds: Incomplete | None = None, port_bindings: Incomplete | None = None, - lxc_conf: Incomplete | None = None, + lxc_conf: dict[Incomplete, Incomplete] | None = None, publish_all_ports: bool = False, - links: Incomplete | None = None, + links: dict[str, str | None] | None = None, privileged: bool = False, - dns: Incomplete | None = None, - dns_search: Incomplete | None = None, - volumes_from: Incomplete | None = None, - network_mode: Incomplete | None = None, - restart_policy: Incomplete | None = None, - cap_add: Incomplete | None = None, - cap_drop: Incomplete | None = None, - devices: Incomplete | None = None, - extra_hosts: Incomplete | None = None, - read_only: Incomplete | None = None, - pid_mode: Incomplete | None = None, - ipc_mode: Incomplete | None = None, - security_opt: Incomplete | None = None, - ulimits: Incomplete | None = None, - log_config: Incomplete | None = None, - mem_limit: Incomplete | None = None, - memswap_limit: Incomplete | None = None, - mem_reservation: Incomplete | None = None, - kernel_memory: Incomplete | None = None, - mem_swappiness: Incomplete | None = None, - cgroup_parent: Incomplete | None = None, - group_add: Incomplete | None = None, - cpu_quota: Incomplete | None = None, - cpu_period: Incomplete | None = None, - blkio_weight: Incomplete | None = None, - blkio_weight_device: Incomplete | None = None, + dns: list[Incomplete] | None = None, + dns_search: list[Incomplete] | None = None, + volumes_from: list[str] | None = None, + network_mode: str | None = None, + restart_policy: dict[Incomplete, Incomplete] | None = None, + cap_add: list[str] | None = None, + cap_drop: list[str] | None = None, + devices: list[str] | None = None, + extra_hosts: dict[Incomplete, Incomplete] | None = None, + read_only: bool | None = None, + pid_mode: str | None = None, + ipc_mode: str | None = None, + security_opt: list[str] | None = None, + ulimits: list[Ulimit] | None = None, + log_config: LogConfig | None = None, + mem_limit: str | int | None = None, + memswap_limit: str | int | None = None, + mem_reservation: str | int | None = None, + kernel_memory: str | int | None = None, + mem_swappiness: int | None = None, + cgroup_parent: str | None = None, + group_add: list[str | int] | None = None, + cpu_quota: int | None = None, + cpu_period: int | None = None, + blkio_weight: int | None = None, + blkio_weight_device: list[ContainerWeightDevice] | None = None, device_read_bps: Incomplete | None = None, device_write_bps: Incomplete | None = None, device_read_iops: Incomplete | None = None, device_write_iops: Incomplete | None = None, oom_kill_disable: bool = False, - shm_size: Incomplete | None = None, - sysctls: Incomplete | None = None, - tmpfs: Incomplete | None = None, - oom_score_adj: Incomplete | None = None, - dns_opt: Incomplete | None = None, - cpu_shares: Incomplete | None = None, - cpuset_cpus: Incomplete | None = None, - userns_mode: Incomplete | None = None, - uts_mode: Incomplete | None = None, - pids_limit: Incomplete | None = None, - isolation: Incomplete | None = None, + shm_size: str | int | None = None, + sysctls: dict[Incomplete, Incomplete] | None = None, + tmpfs: dict[str, str] | None = None, + oom_score_adj: int | None = None, + dns_opt: list[Incomplete] | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + pids_limit: int | None = None, + isolation: str | None = None, auto_remove: bool = False, - storage_opt: Incomplete | None = None, - init: Incomplete | None = None, - init_path: Incomplete | None = None, - volume_driver: Incomplete | None = None, - cpu_count: Incomplete | None = None, - cpu_percent: Incomplete | None = None, - nano_cpus: Incomplete | None = None, - cpuset_mems: Incomplete | None = None, - runtime: Incomplete | None = None, - mounts: Incomplete | None = None, - cpu_rt_period: Incomplete | None = None, - cpu_rt_runtime: Incomplete | None = None, - device_cgroup_rules: Incomplete | None = None, - device_requests: Incomplete | None = None, - cgroupns: Incomplete | None = None, + storage_opt: dict[Incomplete, Incomplete] | None = None, + init: bool | None = None, + init_path: str | None = None, + volume_driver: str | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + nano_cpus: int | None = None, + cpuset_mems: str | None = None, + runtime: str | None = None, + mounts: list[Mount] | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + device_cgroup_rules: list[Incomplete] | None = None, + device_requests: list[DeviceRequest] | None = None, + cgroupns: Literal["private", "host"] | None = None, ) -> None: ... def host_config_type_error(param, param_value, expected): ... @@ -138,27 +146,27 @@ def host_config_incompatible_error(param, param_value, incompatible_param): ... class ContainerConfig(dict[str, Incomplete]): def __init__( self, - version, + version: str, image, - command, - hostname: Incomplete | None = None, - user: Incomplete | None = None, + command: str | list[str], + hostname: str | None = None, + user: str | int | None = None, detach: bool = False, stdin_open: bool = False, tty: bool = False, - ports: Incomplete | None = None, - environment: Incomplete | None = None, - volumes: Incomplete | None = None, + ports: dict[str, int | None] | None = None, + environment: dict[str, str] | list[str] | None = None, + volumes: str | list[str] | None = None, network_disabled: bool = False, - entrypoint: Incomplete | None = None, - working_dir: Incomplete | None = None, - domainname: Incomplete | None = None, + entrypoint: str | list[str] | None = None, + working_dir: str | None = None, + domainname: str | None = None, host_config: Incomplete | None = None, - mac_address: Incomplete | None = None, - labels: Incomplete | None = None, - stop_signal: Incomplete | None = None, + mac_address: str | None = None, + labels: dict[str, str] | list[str] | None = None, + stop_signal: str | None = None, networking_config: Incomplete | None = None, healthcheck: Incomplete | None = None, - stop_timeout: Incomplete | None = None, - runtime: Incomplete | None = None, + stop_timeout: int | None = None, + runtime: str | None = None, ) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/utils/json_stream.pyi b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/utils/json_stream.pyi index 39ddd9d18..883144018 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/utils/json_stream.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/docker/docker/utils/json_stream.pyi @@ -1,17 +1,14 @@ import json from collections.abc import Callable, Generator, Iterator from typing import Any -from typing_extensions import TypeAlias + +from docker._types import JSON json_decoder: json.JSONDecoder -# Type alias for JSON, explained at: -# https://github.com/python/typing/issues/182#issuecomment-1320974824. -_JSON: TypeAlias = dict[str, _JSON] | list[_JSON] | str | int | float | bool | None - def stream_as_text(stream: Iterator[str | bytes]) -> Generator[str, None, None]: ... -def json_splitter(buffer: str) -> tuple[_JSON, str] | None: ... -def json_stream(stream: Iterator[str]) -> Generator[_JSON, None, None]: ... +def json_splitter(buffer: str) -> tuple[JSON, str] | None: ... +def json_stream(stream: Iterator[str]) -> Generator[JSON, None, None]: ... def line_splitter(buffer: str, separator: str = "\n") -> tuple[str, str] | None: ... def split_buffer( stream: Iterator[str | bytes], splitter: Callable[[str], tuple[str, str]] | None = None, decoder: Callable[[str], Any] = ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/flake8/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/flake8/METADATA.toml index 36c0facd5..8400594dc 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/flake8/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/flake8/METADATA.toml @@ -1,3 +1,3 @@ -version = "7.0.*" +version = "7.1.*" upstream_repository = "https://github.com/pycqa/flake8" requires = ["types-pyflakes"] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/fpdf.pyi b/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/fpdf.pyi index 9c891c60c..f364de981 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/fpdf.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/fpdf.pyi @@ -25,9 +25,11 @@ from .enums import ( RenderStyle, TableBordersLayout, TableCellFillMode, + TableHeadingsDisplay, TextDirection, TextMarkupType, TextMode as TextMode, + VAlign, WrapMode as WrapMode, XPos as XPos, YPos as YPos, @@ -41,14 +43,14 @@ from .image_datastructures import ( ImageInfo as ImageInfo, RasterImageInfo as RasterImageInfo, VectorImageInfo as VectorImageInfo, - _AlignLiteral, + _TextAlign, ) from .output import OutputProducer, PDFPage from .recorder import FPDFRecorder from .structure_tree import StructureTreeBuilder from .syntax import DestinationXYZ from .table import Table -from .util import _Unit +from .util import Padding, _Unit __all__ = [ "FPDF", @@ -489,7 +491,7 @@ class FPDF(GraphicsStateMixin): ncols: int = 1, gutter: float = 10, balance: bool = False, - text_align: Align | _AlignLiteral = "LEFT", + text_align: str | _TextAlign | tuple[_TextAlign | str, ...] = "LEFT", line_height: float = 1, l_margin: float | None = None, r_margin: float | None = None, @@ -570,17 +572,26 @@ class FPDF(GraphicsStateMixin): self, rows: Iterable[Incomplete] = (), *, - align: str | Align = "CENTER", + # Keep in sync with `fpdf.table.Table`: + align: str | _TextAlign = "CENTER", + v_align: str | VAlign = "MIDDLE", borders_layout: str | TableBordersLayout = ..., cell_fill_color: int | tuple[Incomplete, ...] | DeviceGray | DeviceRGB | None = None, cell_fill_mode: str | TableCellFillMode = ..., col_widths: int | tuple[int, ...] | None = None, first_row_as_headings: bool = True, + gutter_height: float = 0, + gutter_width: float = 0, headings_style: FontFace = ..., line_height: int | None = None, markdown: bool = False, - text_align: str | Align = "JUSTIFY", + text_align: str | _TextAlign | tuple[str | _TextAlign, ...] = "JUSTIFY", width: int | None = None, + wrapmode: WrapMode = ..., + padding: float | Padding | None = None, + outer_border_width: float | None = None, + num_heading_rows: int = 1, + repeat_headings: TableHeadingsDisplay | int = 1, ) -> _GeneratorContextManager[Table]: ... @overload def output( # type: ignore[overload-overlap] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/image_datastructures.pyi b/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/image_datastructures.pyi index 06f422893..b81fb5865 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/image_datastructures.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/image_datastructures.pyi @@ -31,6 +31,7 @@ _AlignLiteral: TypeAlias = Literal[ "r", "j", ] +_TextAlign: TypeAlias = Align | _AlignLiteral class ImageInfo(dict[str, Any]): @property @@ -43,7 +44,7 @@ class ImageInfo(dict[str, Any]): def rendered_height(self) -> int: ... def scale_inside_box(self, x: float, y: float, w: float, h: float) -> tuple[float, float, float, float]: ... @staticmethod - def x_by_align(x: Align | _AlignLiteral, w: float, pdf: FPDF, keep_aspect_ratio: Literal[False]) -> float: ... + def x_by_align(x: _TextAlign, w: float, pdf: FPDF, keep_aspect_ratio: Literal[False]) -> float: ... class RasterImageInfo(ImageInfo): def size_in_document_units(self, w: float, h: float, scale=1) -> tuple[float, float]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/table.pyi b/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/table.pyi index daea652fd..a3430949d 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/table.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/table.pyi @@ -10,6 +10,7 @@ from .drawing import DeviceGray, DeviceRGB from .enums import Align, TableBordersLayout, TableCellFillMode, TableHeadingsDisplay, TableSpan, VAlign, WrapMode from .fonts import FontFace from .fpdf import FPDF +from .image_datastructures import _TextAlign from .util import Padding DEFAULT_HEADINGS_STYLE: FontFace @@ -22,7 +23,8 @@ class Table: fpdf: FPDF, rows: Iterable[str] = (), *, - align: str | Align = "CENTER", + # Keep in sync with `fpdf.fpdf.FPDF.table`: + align: str | _TextAlign = "CENTER", v_align: str | VAlign = "MIDDLE", borders_layout: str | TableBordersLayout = ..., cell_fill_color: int | tuple[Incomplete, ...] | DeviceGray | DeviceRGB | None = None, @@ -34,7 +36,7 @@ class Table: headings_style: FontFace = ..., line_height: int | None = None, markdown: bool = False, - text_align: str | Align = "JUSTIFY", + text_align: str | _TextAlign | tuple[str | _TextAlign, ...] = "JUSTIFY", width: int | None = None, wrapmode: WrapMode = ..., padding: float | Padding | None = None, diff --git a/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/text_region.pyi b/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/text_region.pyi index bbdf463b3..a9d4c2920 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/text_region.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/fpdf2/fpdf/text_region.pyi @@ -4,7 +4,7 @@ from typing import NamedTuple from typing_extensions import Self from .enums import Align, WrapMode -from .image_datastructures import RasterImageInfo, VectorImageInfo, _AlignLiteral +from .image_datastructures import RasterImageInfo, VectorImageInfo, _TextAlign class Extents(NamedTuple): left: float @@ -24,7 +24,7 @@ class LineWrapper(NamedTuple): class Paragraph: pdf: Incomplete - text_align: Incomplete + text_align: Align line_height: Incomplete top_margin: Incomplete bottom_margin: Incomplete @@ -34,7 +34,7 @@ class Paragraph: def __init__( self, region, - text_align: Incomplete | None = None, + text_align: _TextAlign | None = None, line_height: Incomplete | None = None, top_margin: float = 0, bottom_margin: float = 0, @@ -67,7 +67,7 @@ class ImageParagraph: self, region, name, - align: Align | _AlignLiteral | None = None, + align: _TextAlign | None = None, width: float | None = None, height: float | None = None, fill_width: bool = False, @@ -93,7 +93,7 @@ class ParagraphCollectorMixin: pdf, *args, text: str | None = None, - text_align: Align | _AlignLiteral = "LEFT", + text_align: _TextAlign = "LEFT", line_height: float = 1.0, print_sh: bool = False, skip_leading_spaces: bool = False, @@ -108,7 +108,7 @@ class ParagraphCollectorMixin: def ln(self, h: float | None = None) -> None: ... def paragraph( self, - text_align: Incomplete | None = None, + text_align: _TextAlign | None = None, line_height: Incomplete | None = None, skip_leading_spaces: bool = False, top_margin: int = 0, @@ -119,7 +119,7 @@ class ParagraphCollectorMixin: def image( self, name, - align: Align | _AlignLiteral | None = None, + align: _TextAlign | None = None, width: float | None = None, height: float | None = None, fill_width: bool = False, diff --git a/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/METADATA.toml index 77829fb62..cbdd4b60f 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/METADATA.toml @@ -1,2 +1,2 @@ -version = "2.20.*" +version = "2.21.*" # upstream_repository = closed-source diff --git a/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/hdbcli/dbapi.pyi b/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/hdbcli/dbapi.pyi index c9fb23f17..4ba75f81b 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/hdbcli/dbapi.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/hdbcli/hdbcli/dbapi.pyi @@ -38,6 +38,7 @@ class Connection: def rollback(self) -> None: ... def setautocommit(self, auto: bool = ...) -> None: ... def setclientinfo(self, key: str, value: str | None = ...) -> None: ... + def ontrace(self) -> None: ... connect = Connection diff --git a/packages/pyright-internal/typeshed-fallback/stubs/hvac/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/hvac/METADATA.toml index 911834e93..f16271580 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/hvac/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/hvac/METADATA.toml @@ -1,3 +1,3 @@ -version = "2.2.*" +version = "2.3.*" upstream_repository = "https://github.com/hvac/hvac" requires = ["types-requests"] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/hvac/hvac/api/system_backend/raft.pyi b/packages/pyright-internal/typeshed-fallback/stubs/hvac/hvac/api/system_backend/raft.pyi index 7a13149ed..ebd9051d1 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/hvac/hvac/api/system_backend/raft.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/hvac/hvac/api/system_backend/raft.pyi @@ -1,6 +1,8 @@ from _typeshed import Incomplete +from typing import Any from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin +from requests import Response class Raft(SystemBackendMixin): def join_raft_cluster( @@ -16,3 +18,10 @@ class Raft(SystemBackendMixin): def take_raft_snapshot(self): ... def restore_raft_snapshot(self, snapshot): ... def force_restore_raft_snapshot(self, snapshot): ... + def read_raft_auto_snapshot_status(self, name: str) -> Response: ... + def read_raft_auto_snapshot_config(self, name: str) -> Response: ... + def list_raft_auto_snapshot_configs(self) -> Response: ... + def create_or_update_raft_auto_snapshot_config( + self, name: str, interval: str, storage_type: str, retain: int = 1, **kwargs: Any + ) -> Response: ... + def delete_raft_auto_snapshot_config(self, name: str) -> Response: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/hvac/hvac/api/system_backend/wrapping.pyi b/packages/pyright-internal/typeshed-fallback/stubs/hvac/hvac/api/system_backend/wrapping.pyi index 4ca4167cb..450f9c841 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/hvac/hvac/api/system_backend/wrapping.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/hvac/hvac/api/system_backend/wrapping.pyi @@ -4,3 +4,4 @@ from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin class Wrapping(SystemBackendMixin): def unwrap(self, token: Incomplete | None = None): ... + def wrap(self, payload: dict[Incomplete, Incomplete] | None = None, ttl: int = 60): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/METADATA.toml index e8b3b5471..74f497ce4 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/METADATA.toml @@ -1,4 +1,4 @@ -version = "1.43.*" +version = "1.44.*" upstream_repository = "https://github.com/influxdata/influxdb-client-python" # requires a version of urllib3 with a py.typed file requires = ["urllib3>=2"] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/client/_pages.pyi b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/client/_pages.pyi new file mode 100644 index 000000000..1ecf38d5f --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/client/_pages.pyi @@ -0,0 +1,37 @@ +from collections.abc import Callable +from typing import Any, Generic, Protocol, TypeVar +from typing_extensions import Self + +class _HasId(Protocol): + @property + def id(self) -> str | None: ... + +_R = TypeVar("_R", default=Any) +_T = TypeVar("_T", bound=_HasId) + +class _Page(Generic[_T]): + has_next: bool + values: list[_T] + next_after: str | None + + def __init__(self, values: list[_T], has_next: bool, next_after: str | None) -> None: ... + @staticmethod + def empty() -> _Page[_T]: ... + @staticmethod + def initial(after: str | None) -> _Page[_T]: ... + +class _PageIterator(Generic[_T]): + page: _Page[_T] + get_next_page: Callable[[_Page[_T]], _Page[_T]] + + def __init__(self, page: _Page[_T], get_next_page: Callable[[_Page[_T]], _Page[_T]]) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + +class _Paginated(Generic[_T, _R]): + paginated_getter: Callable[..., _R] # Gets passed additional kwargs to find_iter(). + pluck_page_resources_from_response: Callable[[_R], list[_T]] + def __init__( + self, paginated_getter: Callable[..., _R], pluck_page_resources_from_response: Callable[[_R], list[_T]] + ) -> None: ... + def find_iter(self, *, after: str | None = None, **kwargs: Any) -> _PageIterator[_T]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/client/bucket_api.pyi b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/client/bucket_api.pyi index b50467a24..d1cd792d3 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/client/bucket_api.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/client/bucket_api.pyi @@ -1,6 +1,7 @@ from _typeshed import Incomplete -from influxdb_client import Bucket +from ..domain.bucket import Bucket +from ._pages import _PageIterator class BucketsApi: def __init__(self, influxdb_client) -> None: ... @@ -18,3 +19,6 @@ class BucketsApi: def find_bucket_by_id(self, id): ... def find_bucket_by_name(self, bucket_name): ... def find_buckets(self, **kwargs): ... + def find_buckets_iter( + self, *, name: str = ..., org: str = ..., org_id: str = ..., after: str | None = None, limit: int = ... + ) -> _PageIterator[Bucket]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/client/tasks_api.pyi b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/client/tasks_api.pyi index 36f2d63ea..15a5110df 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/client/tasks_api.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/client/tasks_api.pyi @@ -1,9 +1,10 @@ -from collections.abc import Iterator from datetime import datetime from influxdb_client import LabelResponse, LogEvent, Run, TaskCreateRequest, TaskUpdateRequest from influxdb_client.domain.task import Task +from ._pages import _PageIterator + class TasksApi: def __init__(self, influxdb_client) -> None: ... def find_task_by_id(self, task_id) -> Task: ... @@ -11,8 +12,8 @@ class TasksApi: self, *, name: str = ..., after: str = ..., user: str = ..., org: str = ..., org_id: str = ..., limit: int = ..., **kwargs ) -> list[Task]: ... def find_tasks_iter( - self, *, name: str = ..., after: str = ..., user: str = ..., org: str = ..., org_id: str = ..., limit: int = ..., **kwargs - ) -> Iterator[Task]: ... + self, *, name: str = ..., after: str | None = None, user: str = ..., org: str = ..., org_id: str = ..., limit: int = ... + ) -> _PageIterator[Task]: ... def create_task(self, task: Task | None = None, task_create_request: TaskCreateRequest | None = None) -> Task: ... def create_task_every(self, name, flux, every, organization) -> Task: ... def create_task_cron(self, name: str, flux: str, cron: str, org_id: str) -> Task: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/domain/bucket.pyi b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/domain/bucket.pyi index c0110c298..fe7a86461 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/domain/bucket.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/domain/bucket.pyi @@ -7,11 +7,11 @@ class Bucket: def __init__( self, links: Incomplete | None = None, - id: Incomplete | None = None, + id: str | None = None, type: str = "user", name: Incomplete | None = None, description: Incomplete | None = None, - org_id: Incomplete | None = None, + org_id: str | None = None, rp: Incomplete | None = None, schema_type: Incomplete | None = None, created_at: Incomplete | None = None, @@ -24,9 +24,9 @@ class Bucket: @links.setter def links(self, links) -> None: ... @property - def id(self): ... + def id(self) -> str | None: ... @id.setter - def id(self, id) -> None: ... + def id(self, id: str) -> None: ... @property def type(self): ... @type.setter @@ -40,9 +40,9 @@ class Bucket: @description.setter def description(self, description) -> None: ... @property - def org_id(self): ... + def org_id(self) -> str | None: ... @org_id.setter - def org_id(self, org_id) -> None: ... + def org_id(self, org_id: str) -> None: ... @property def rp(self): ... @rp.setter diff --git a/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/domain/task.pyi b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/domain/task.pyi index 84140e219..1d0d63102 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/domain/task.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/influxdb-client/influxdb_client/domain/task.pyi @@ -6,8 +6,8 @@ class Task: discriminator: Incomplete def __init__( self, - id: Incomplete | None = None, - org_id: Incomplete | None = None, + id: str | None = None, + org_id: str | None = None, org: Incomplete | None = None, name: Incomplete | None = None, owner_id: Incomplete | None = None, @@ -27,13 +27,13 @@ class Task: links: Incomplete | None = None, ) -> None: ... @property - def id(self): ... + def id(self) -> str | None: ... @id.setter - def id(self, id) -> None: ... + def id(self, id: str) -> None: ... @property - def org_id(self): ... + def org_id(self) -> str | None: ... @org_id.setter - def org_id(self, org_id) -> None: ... + def org_id(self, org_id: str) -> None: ... @property def org(self): ... @org.setter diff --git a/packages/pyright-internal/typeshed-fallback/stubs/networkx/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/networkx/METADATA.toml index d572cfc2e..d808108cf 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/networkx/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/networkx/METADATA.toml @@ -1,6 +1,8 @@ version = "3.2.1" upstream_repository = "https://github.com/networkx/networkx" -requires = ["numpy"] +# requires a version of numpy with a `py.typed` file +# TODO: Lots of stubtest errors when using numpy 2 +requires = ["numpy>=1.20,<2"] partial_stub = true [tool.stubtest] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/olefile/olefile/olefile.pyi b/packages/pyright-internal/typeshed-fallback/stubs/olefile/olefile/olefile.pyi index b1df2da29..7637bf9d3 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/olefile/olefile/olefile.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/olefile/olefile/olefile.pyi @@ -4,8 +4,8 @@ import io import logging import traceback from collections.abc import Sequence -from typing import IO -from typing_extensions import Self +from typing import IO, AnyStr, Generic +from typing_extensions import Self, TypeAlias __date__: str __version__: str @@ -137,7 +137,7 @@ class OleMetadata: DOCSUM_ATTRIBS: list[str] def __init__(self) -> None: ... - def parse_properties(self, ole_file: OleFileIO) -> None: ... + def parse_properties(self, ole_file: OleFileIO[AnyStr]) -> None: ... def dump(self) -> None: ... class OleFileIONotClosed(RuntimeWarning): @@ -153,29 +153,34 @@ class OleStream(io.BytesIO): sectorsize: int, fat: list[int], filesize: int, - olefileio: OleFileIO, + olefileio: OleFileIO[AnyStr], ) -> None: ... -class OleDirectoryEntry: +class OleDirectoryEntry(Generic[AnyStr]): STRUCT_DIRENTRY: str DIRENTRY_SIZE: int + clsid: str - def __init__(self, entry: bytes, sid: int, ole_file: OleFileIO) -> None: ... - def build_sect_chain(self, ole_file: OleFileIO) -> None: ... + def __init__(self, entry: bytes, sid: int, ole_file: OleFileIO[AnyStr]) -> None: ... + def build_sect_chain(self, ole_file: OleFileIO[AnyStr]) -> None: ... def build_storage_tree(self) -> None: ... def append_kids(self, child_sid: int) -> None: ... - def __eq__(self, other: OleDirectoryEntry) -> bool: ... # type: ignore[override] - def __lt__(self, other: OleDirectoryEntry) -> bool: ... # type: ignore[override] - def __ne__(self, other: OleDirectoryEntry) -> bool: ... # type: ignore[override] - def __le__(self, other: OleDirectoryEntry) -> bool: ... # type: ignore[override] + def __eq__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... # type: ignore[override] + def __lt__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... # type: ignore[override] + def __ne__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... # type: ignore[override] + def __le__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... # type: ignore[override] def dump(self, tab: int = 0) -> None: ... def getmtime(self) -> datetime.datetime | None: ... def getctime(self) -> datetime.datetime | None: ... -class OleFileIO: +_Property: TypeAlias = int | str | bytes | bool | None + +class OleFileIO(Generic[AnyStr]): + root: OleDirectoryEntry[AnyStr] | None + def __init__( self, - filename: IO[bytes] | bytes | str | None = None, + filename: IO[bytes] | AnyStr | None = None, raise_defects: int = 40, write_mode: bool = False, debug: bool = False, @@ -187,8 +192,8 @@ class OleFileIO: def _raise_defect( self, defect_level: int, message: str, exception_type: type[Exception] = OleFileError # noqa: Y011 ) -> None: ... - def _decode_utf16_str(self, utf16_str: bytes, errors: str = "replace") -> bytes: ... - def open(self, filename: IO[bytes] | bytes | str, write_mode: bool = False) -> None: ... + def _decode_utf16_str(self, utf16_str: bytes, errors: str = "replace") -> str | bytes: ... + def open(self, filename: IO[bytes] | AnyStr, write_mode: bool = False) -> None: ... def close(self) -> None: ... def _close(self, warn: bool = False) -> None: ... def _check_duplicate_stream(self, first_sect: int, minifat: bool = False) -> None: ... @@ -202,36 +207,41 @@ class OleFileIO: def write_sect(self, sect: int, data: bytes, padding: bytes = b"\x00") -> None: ... def _write_mini_sect(self, fp_pos: int, data: bytes, padding: bytes = b"\x00") -> None: ... def loaddirectory(self, sect: int) -> None: ... - def _load_direntry(self, sid: int) -> OleDirectoryEntry: ... + def _load_direntry(self, sid: int) -> OleDirectoryEntry[AnyStr]: ... def dumpdirectory(self) -> None: ... def _open(self, start: int, size: int = 0x7FFFFFFF, force_FAT: bool = False) -> OleStream: ... def _list( - self, files: list[list[bytes]], prefix: list[bytes], node: OleDirectoryEntry, streams: bool = True, storages: bool = False + self, + files: list[list[AnyStr]], + prefix: list[AnyStr], + node: OleDirectoryEntry[AnyStr], + streams: bool = True, + storages: bool = False, ) -> None: ... - def listdir(self, streams: bool = True, storages: bool = False) -> list[list[bytes]]: ... + def listdir(self, streams: bool = True, storages: bool = False) -> list[list[AnyStr]]: ... def _find(self, filename: str | Sequence[str]) -> int: ... - def openstream(self, filename: str | Sequence[str]) -> OleStream: ... - def _write_mini_stream(self, entry: OleDirectoryEntry, data_to_write: bytes) -> None: ... + def openstream(self, filename: AnyStr | Sequence[AnyStr]) -> OleStream: ... + def _write_mini_stream(self, entry: OleDirectoryEntry[AnyStr], data_to_write: bytes) -> None: ... def write_stream(self, stream_name: str | Sequence[str], data: bytes) -> None: ... - def get_type(self, filename: str | Sequence[str]) -> bool | int: ... - def getclsid(self, filename: str | Sequence[str]) -> str: ... - def getmtime(self, filename: str | Sequence[str]) -> datetime.datetime | None: ... - def getctime(self, filename: str | Sequence[str]) -> datetime.datetime | None: ... - def exists(self, filename: str | Sequence[str]) -> bool: ... - def get_size(self, filename: str | Sequence[str]) -> int: ... + def get_type(self, filename: AnyStr | Sequence[AnyStr]) -> bool | int: ... + def getclsid(self, filename: AnyStr | Sequence[AnyStr]) -> str: ... + def getmtime(self, filename: AnyStr | Sequence[AnyStr]) -> datetime.datetime | None: ... + def getctime(self, filename: AnyStr | Sequence[AnyStr]) -> datetime.datetime | None: ... + def exists(self, filename: AnyStr | Sequence[AnyStr]) -> bool: ... + def get_size(self, filename: AnyStr | Sequence[AnyStr]) -> int: ... def get_rootentry_name(self) -> bytes: ... def getproperties( - self, filename: str | Sequence[str], convert_time: bool = False, no_conversion: list[int] | None = None - ) -> dict[int, list[int | str | bytes | bool | None]]: ... + self, filename: AnyStr | Sequence[AnyStr], convert_time: bool = False, no_conversion: list[int] | None = None + ) -> dict[int, list[_Property] | _Property]: ... def _parse_property( self, s: bytes, offset: int, property_id: int, property_type: int, convert_time: bool, no_conversion: list[int] - ) -> list[int | str | bytes | bool | None] | None: ... + ) -> list[_Property] | _Property: ... def _parse_property_basic( self, s: bytes, offset: int, property_id: int, property_type: int, convert_time: bool, no_conversion: list[int] - ) -> tuple[int | str | bytes | bool | None, int]: ... + ) -> tuple[_Property, int]: ... def get_metadata(self) -> OleMetadata: ... def get_userdefined_properties( - self, filename: str | Sequence[str], convert_time: bool = False, no_conversion: list[int] | None = None + self, filename: AnyStr | Sequence[AnyStr], convert_time: bool = False, no_conversion: list[int] | None = None ) -> list[dict[str, bytes | int | None]]: ... def main() -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/METADATA.toml index f2743c5bf..eef134504 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/METADATA.toml @@ -1,2 +1,2 @@ -version = "3.1.2" +version = "3.1.4" upstream_repository = "https://foss.heptapod.net/openpyxl/openpyxl" diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/cell/rich_text.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/cell/rich_text.pyi index a5168ddf6..7f098a1b8 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/cell/rich_text.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/cell/rich_text.pyi @@ -5,6 +5,7 @@ from typing_extensions import Self from openpyxl.cell.text import InlineFont from openpyxl.descriptors import Strict, String, Typed from openpyxl.descriptors.serialisable import _ChildSerialisableTreeElement +from openpyxl.xml.functions import Element class TextBlock(Strict): font: Typed[InlineFont, Literal[False]] @@ -12,6 +13,7 @@ class TextBlock(Strict): def __init__(self, font: InlineFont, text: str) -> None: ... def __eq__(self, other: TextBlock) -> bool: ... # type: ignore[override] + def to_tree(self) -> Element: ... class CellRichText(list[str | TextBlock]): @overload @@ -24,3 +26,4 @@ class CellRichText(list[str | TextBlock]): def append(self, arg: str | TextBlock) -> None: ... def extend(self, arg: Iterable[str | TextBlock]) -> None: ... def as_list(self) -> list[str]: ... + def to_tree(self) -> Element: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/trendline.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/trendline.pyi index 88b6fd46d..e76da34ef 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/trendline.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/chart/trendline.pyi @@ -10,8 +10,7 @@ from openpyxl.descriptors.base import Alias, String, Typed, _ConvertibleToBool from openpyxl.descriptors.excel import ExtensionList from openpyxl.descriptors.nested import NestedBool, NestedFloat, NestedInteger, NestedSet from openpyxl.descriptors.serialisable import Serialisable - -from ..xml._functions_overloads import _HasTagAndGet +from openpyxl.xml._functions_overloads import _HasTagAndGet _TrendlineTrendlineType: TypeAlias = Literal["exp", "linear", "log", "movingAvg", "poly", "power"] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/base.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/base.pyi index 0bd080428..e7f9515bf 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/base.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/base.pyi @@ -12,7 +12,7 @@ from openpyxl.worksheet.cell_range import CellRange, MultiCellRange _T = TypeVar("_T") _P = TypeVar("_P", str, ReadableBuffer) -_N = TypeVar("_N", bound=bool) +_N = TypeVar("_N", bound=bool, default=Literal[False]) _L = TypeVar("_L", bound=Sized) _M = TypeVar("_M", int, float) diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/container.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/container.pyi new file mode 100644 index 000000000..52106f1e6 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/container.pyi @@ -0,0 +1,18 @@ +from typing import TypeVar +from typing_extensions import Self + +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +_T = TypeVar("_T", bound=Serialisable) + +# Abstract base class. +class ElementList(list[_T]): + @property + def tagname(self) -> str: ... # abstract + @property + def expected_type(self) -> type[_T]: ... # abstract + @classmethod + def from_tree(cls, tree: Element) -> Self: ... + def to_tree(self) -> Element: ... + def append(self, value: _T) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/sequence.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/sequence.pyi index 6a86831bf..246ab1164 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/sequence.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/descriptors/sequence.pyi @@ -11,6 +11,7 @@ from openpyxl.xml.functions import Element from .base import Alias, Descriptor _T = TypeVar("_T") +_ContainerT = TypeVar("_ContainerT") class _SupportsFromTree(Protocol): @classmethod @@ -19,22 +20,27 @@ class _SupportsFromTree(Protocol): class _SupportsToTree(Protocol): def to_tree(self) -> Element: ... -class Sequence(Descriptor[Incomplete]): - expected_type: type[Incomplete] - seq_types: tuple[type, ...] +# `_ContainerT` is the internal container type (which defaults to `list`), or +# `IndexedList` if unique is `True`. +class Sequence(Descriptor[_ContainerT]): + expected_type: type[Any] # expected type of the sequence elements + seq_types: tuple[type, ...] # allowed settable sequence types, defaults to `list`, `tuple` idx_base: int unique: bool - container: type - def __set__(self, instance: Serialisable | Strict, seq) -> None: ... + container: type # internal container type, defaults to `list` + # seq must be an instance of any of the declared `seq_types`. + def __set__(self, instance: Serialisable | Strict, seq: Any) -> None: ... def to_tree( self, tagname: str | None, obj: Iterable[object], namespace: str | None = None ) -> Generator[Element, None, None]: ... -class UniqueSequence(Sequence): - seq_types: tuple[type, ...] - container: type +# `_T` is the type of the elements in the sequence. +class UniqueSequence(Sequence[set[_T]]): + seq_types: tuple[type[list[_T]], type[tuple[_T, ...]], type[set[_T]]] + container: type[set[_T]] -class ValueSequence(Sequence): +# See `Sequence` for the meaning of `_ContainerT`. +class ValueSequence(Sequence[_ContainerT]): attribute: str def to_tree( self, tagname: str, obj: Iterable[object], namespace: str | None = None # type: ignore[override] @@ -43,7 +49,8 @@ class ValueSequence(Sequence): class _NestedSequenceToTreeObj(Sized, Iterable[_SupportsToTree], Protocol): ... -class NestedSequence(Sequence): +# See `Sequence` for the meaning of `_ContainerT`. +class NestedSequence(Sequence[_ContainerT]): count: bool expected_type: type[_SupportsFromTree] def to_tree( # type: ignore[override] @@ -53,8 +60,9 @@ class NestedSequence(Sequence): # Which can really be anything given the wildly different, and sometimes generic, from_tree return types def from_tree(self, node: Iterable[_SerialisableTreeElement]) -> list[Any]: ... -class MultiSequence(Sequence): - def __set__(self, instance: Serialisable | Strict, seq) -> None: ... +# `_T` is the type of the elements in the sequence. +class MultiSequence(Sequence[list[_T]]): + def __set__(self, instance: Serialisable | Strict, seq: tuple[_T, ...] | list[_T]) -> None: ... def to_tree( self, tagname: Unused, obj: Iterable[_SupportsToTree], namespace: str | None = None # type: ignore[override] ) -> Generator[Element, None, None]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/custom.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/custom.pyi index a01a5a098..ec95af53f 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/custom.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/custom.pyi @@ -52,7 +52,7 @@ CLASS_MAPPING: Final[dict[type[_MappingPropertyType], str]] XML_MAPPING: Final[dict[str, type[_MappingPropertyType]]] class CustomPropertyList(Strict, Generic[_T]): - props: Sequence + props: Sequence[list[_TypedProperty[_T]]] def __init__(self) -> None: ... @classmethod def from_tree(cls, tree: _ChildSerialisableTreeElement) -> Self: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/extended.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/extended.pyi index 9eedb949f..3a729711c 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/extended.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/extended.pyi @@ -76,8 +76,8 @@ class ExtendedProperties(Serialisable): HLinks: Unused = None, HyperlinksChanged: object = None, DigSig: Unused = None, - Application: object = "Microsoft Excel", - AppVersion: object = None, + Application: Unused = None, + AppVersion: str | None = None, DocSecurity: ConvertibleToInt | None = None, ) -> None: ... def to_tree(self) -> Element: ... # type: ignore[override] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/relationship.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/relationship.pyi index e0ddf4c8b..1a1ea10a1 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/relationship.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/packaging/relationship.pyi @@ -4,11 +4,11 @@ from typing import ClassVar, Literal, TypeVar, overload from zipfile import ZipFile from openpyxl.descriptors.base import Alias, String +from openpyxl.descriptors.container import ElementList from openpyxl.descriptors.serialisable import Serialisable from openpyxl.pivot.cache import CacheDefinition from openpyxl.pivot.record import RecordList from openpyxl.pivot.table import TableDefinition -from openpyxl.xml.functions import Element _SerialisableT = TypeVar("_SerialisableT", bound=Serialisable) _SerialisableRelTypeT = TypeVar("_SerialisableRelTypeT", bound=CacheDefinition | RecordList | TableDefinition) @@ -32,16 +32,11 @@ class Relationship(Serialisable): self, Id: str, Type: str, type: None = None, Target: str | None = None, TargetMode: str | None = None ) -> None: ... -class RelationshipList(Serialisable): - tagname: ClassVar[str] - Relationship: Incomplete - def __init__(self, Relationship=()) -> None: ... - def append(self, value) -> None: ... - def __len__(self) -> int: ... - def __bool__(self) -> bool: ... - def find(self, content_type) -> Generator[Incomplete, None, None]: ... - def __getitem__(self, key): ... - def to_tree(self) -> Element: ... # type: ignore[override] +class RelationshipList(ElementList[Relationship]): + expected_type: type[Relationship] + def find(self, content_type: str) -> Generator[Relationship, None, None]: ... + def get(self, key: str) -> Relationship: ... + def to_dict(self) -> dict[Incomplete, Relationship]: ... def get_rels_path(path): ... def get_dependents(archive: ZipFile, filename: str) -> RelationshipList: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/pivot/cache.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/pivot/cache.pyi index 5cb3571cd..bd8c5f6ca 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/pivot/cache.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/pivot/cache.pyi @@ -3,9 +3,10 @@ from datetime import datetime from typing import ClassVar, Literal, overload from typing_extensions import TypeAlias -from openpyxl.descriptors.base import Bool, DateTime, Float, Integer, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.base import Bool, DateTime, Float, Integer, NoneSet, Set, String, Typed, _ConvertibleToBool from openpyxl.descriptors.excel import ExtensionList from openpyxl.descriptors.nested import NestedInteger +from openpyxl.descriptors.sequence import NestedSequence from openpyxl.descriptors.serialisable import Serialisable from openpyxl.pivot.fields import Error, Missing, Number, Text, TupleList from openpyxl.pivot.table import PivotArea @@ -43,10 +44,10 @@ class CalculatedMember(Serialisable): tagname: ClassVar[str] name: String[Literal[False]] mdx: String[Literal[False]] - memberName: String[Literal[False]] - hierarchy: String[Literal[False]] - parent: String[Literal[False]] - solveOrder: Integer[Literal[False]] + memberName: String[Literal[True]] + hierarchy: String[Literal[True]] + parent: String[Literal[True]] + solveOrder: Integer[Literal[True]] set: Bool[Literal[False]] extLst: Typed[ExtensionList, Literal[True]] __elements__: ClassVar[tuple[str, ...]] @@ -84,15 +85,6 @@ class ServerFormat(Serialisable): format: String[Literal[True]] def __init__(self, culture: str | None = None, format: str | None = None) -> None: ... -class ServerFormatList(Serialisable): - tagname: ClassVar[str] - serverFormat: Incomplete - __elements__: ClassVar[tuple[str, ...]] - __attrs__: ClassVar[tuple[str, ...]] - def __init__(self, count: Incomplete | None = None, serverFormat: Incomplete | None = None) -> None: ... - @property - def count(self) -> int: ... - class Query(Serialisable): tagname: ClassVar[str] mdx: String[Literal[False]] @@ -100,13 +92,6 @@ class Query(Serialisable): __elements__: ClassVar[tuple[str, ...]] def __init__(self, mdx: str, tpls: TupleList | None = None) -> None: ... -class QueryCache(Serialisable): - tagname: ClassVar[str] - count: Integer[Literal[False]] - query: Typed[Query, Literal[False]] - __elements__: ClassVar[tuple[str, ...]] - def __init__(self, count: ConvertibleToInt, query: Query) -> None: ... - class OLAPSet(Serialisable): tagname: ClassVar[str] count: Integer[Literal[False]] @@ -128,82 +113,59 @@ class OLAPSet(Serialisable): sortByTuple: TupleList | None = None, ) -> None: ... -class OLAPSets(Serialisable): - count: Integer[Literal[False]] - set: Typed[OLAPSet, Literal[False]] - __elements__: ClassVar[tuple[str, ...]] - def __init__(self, count: ConvertibleToInt, set: OLAPSet) -> None: ... - class PCDSDTCEntries(Serialisable): tagname: ClassVar[str] - count: Integer[Literal[False]] - m: Typed[Missing, Literal[False]] - n: Typed[Number, Literal[False]] - e: Typed[Error, Literal[False]] - s: Typed[Text, Literal[False]] + count: Integer[Literal[True]] + m: Typed[Missing, Literal[True]] + n: Typed[Number, Literal[True]] + e: Typed[Error, Literal[True]] + s: Typed[Text, Literal[True]] __elements__: ClassVar[tuple[str, ...]] def __init__(self, count: ConvertibleToInt, m: Missing, n: Number, e: Error, s: Text) -> None: ... class TupleCache(Serialisable): tagname: ClassVar[str] entries: Typed[PCDSDTCEntries, Literal[True]] - sets: Typed[OLAPSets, Literal[True]] - queryCache: Typed[QueryCache, Literal[True]] - serverFormats: Typed[ServerFormatList, Literal[True]] + sets: NestedSequence[list[OLAPSet]] + queryCache: NestedSequence[list[Query]] + serverFormats: NestedSequence[list[ServerFormat]] extLst: Typed[ExtensionList, Literal[True]] __elements__: ClassVar[tuple[str, ...]] def __init__( self, entries: PCDSDTCEntries | None = None, - sets: OLAPSets | None = None, - queryCache: QueryCache | None = None, - serverFormats: ServerFormatList | None = None, + sets: list[OLAPSet] | tuple[OLAPSet, ...] = (), + queryCache: list[Query] | tuple[Query, ...] = (), + serverFormats: list[ServerFormat] | tuple[ServerFormat, ...] = (), extLst: ExtensionList | None = None, ) -> None: ... -class PCDKPI(Serialisable): +class OLAPKPI(Serialisable): tagname: ClassVar[str] uniqueName: String[Literal[False]] caption: String[Literal[True]] - displayFolder: String[Literal[False]] - measureGroup: String[Literal[False]] - parent: String[Literal[False]] + displayFolder: String[Literal[True]] + measureGroup: String[Literal[True]] + parent: String[Literal[True]] value: String[Literal[False]] - goal: String[Literal[False]] - status: String[Literal[False]] - trend: String[Literal[False]] - weight: String[Literal[False]] - time: String[Literal[False]] - @overload + goal: String[Literal[True]] + status: String[Literal[True]] + trend: String[Literal[True]] + weight: String[Literal[True]] + time: String[Literal[True]] def __init__( self, - uniqueName: str, + uniqueName: str | None = None, caption: str | None = None, - *, - displayFolder: str, - measureGroup: str, - parent: str, - value: str, - goal: str, - status: str, - trend: str, - weight: str, - time: str, - ) -> None: ... - @overload - def __init__( - self, - uniqueName: str, - caption: str | None, - displayFolder: str, - measureGroup: str, - parent: str, - value: str, - goal: str, - status: str, - trend: str, - weight: str, - time: str, + displayFolder: str | None = None, + measureGroup: str | None = None, + parent: str | None = None, + value: str | None = None, + goal: str | None = None, + status: str | None = None, + trend: str | None = None, + weight: str | None = None, + time: str | None = None, ) -> None: ... class GroupMember(Serialisable): @@ -212,12 +174,6 @@ class GroupMember(Serialisable): group: Bool[Literal[False]] def __init__(self, uniqueName: str, group: _ConvertibleToBool = None) -> None: ... -class GroupMembers(Serialisable): - count: Integer[Literal[False]] - groupMember: Typed[GroupMember, Literal[False]] - __elements__: ClassVar[tuple[str, ...]] - def __init__(self, count: ConvertibleToInt, groupMember: GroupMember) -> None: ... - class LevelGroup(Serialisable): tagname: ClassVar[str] name: String[Literal[False]] @@ -225,26 +181,25 @@ class LevelGroup(Serialisable): caption: String[Literal[False]] uniqueParent: String[Literal[False]] id: Integer[Literal[False]] - groupMembers: Typed[GroupMembers, Literal[False]] + groupMembers: NestedSequence[list[GroupMember]] __elements__: ClassVar[tuple[str, ...]] def __init__( - self, name: str, uniqueName: str, caption: str, uniqueParent: str, id: ConvertibleToInt, groupMembers: GroupMembers + self, + name: str, + uniqueName: str, + caption: str, + uniqueParent: str, + id: ConvertibleToInt, + groupMembers: list[GroupMember] | tuple[GroupMember, ...] = (), ) -> None: ... -class Groups(Serialisable): - tagname: ClassVar[str] - count: Integer[Literal[False]] - group: Typed[LevelGroup, Literal[False]] - __elements__: ClassVar[tuple[str, ...]] - def __init__(self, count: ConvertibleToInt, group: LevelGroup) -> None: ... - class GroupLevel(Serialisable): tagname: ClassVar[str] uniqueName: String[Literal[False]] caption: String[Literal[False]] user: Bool[Literal[False]] customRollUp: Bool[Literal[False]] - groups: Typed[Groups, Literal[True]] + groups: NestedSequence[list[LevelGroup]] extLst: Typed[ExtensionList, Literal[True]] __elements__: ClassVar[tuple[str, ...]] def __init__( @@ -253,27 +208,15 @@ class GroupLevel(Serialisable): caption: str, user: _ConvertibleToBool = None, customRollUp: _ConvertibleToBool = None, - groups: Groups | None = None, + groups: list[LevelGroup] | tuple[LevelGroup, ...] = (), extLst: ExtensionList | None = None, ) -> None: ... -class GroupLevels(Serialisable): - count: Integer[Literal[False]] - groupLevel: Typed[GroupLevel, Literal[False]] - __elements__: ClassVar[tuple[str, ...]] - def __init__(self, count: ConvertibleToInt, groupLevel: GroupLevel) -> None: ... - class FieldUsage(Serialisable): tagname: ClassVar[str] x: Integer[Literal[False]] def __init__(self, x: ConvertibleToInt) -> None: ... -class FieldsUsage(Serialisable): - count: Integer[Literal[False]] - fieldUsage: Typed[FieldUsage, Literal[True]] - __elements__: ClassVar[tuple[str, ...]] - def __init__(self, count: ConvertibleToInt, fieldUsage: FieldUsage | None = None) -> None: ... - class CacheHierarchy(Serialisable): tagname: ClassVar[str] uniqueName: String[Literal[False]] @@ -298,8 +241,8 @@ class CacheHierarchy(Serialisable): unbalanced: Bool[Literal[True]] unbalancedGroup: Bool[Literal[True]] hidden: Bool[Literal[False]] - fieldsUsage: Typed[FieldsUsage, Literal[True]] - groupLevels: Typed[GroupLevels, Literal[True]] + fieldsUsage: NestedSequence[list[FieldUsage]] + groupLevels: NestedSequence[list[GroupLevel]] extLst: Typed[ExtensionList, Literal[True]] __elements__: ClassVar[tuple[str, ...]] @overload @@ -328,8 +271,8 @@ class CacheHierarchy(Serialisable): unbalanced: _ConvertibleToBool | None = None, unbalancedGroup: _ConvertibleToBool | None = None, hidden: _ConvertibleToBool = None, - fieldsUsage: FieldsUsage | None = None, - groupLevels: GroupLevels | None = None, + fieldsUsage: list[FieldUsage] | tuple[FieldUsage, ...] = (), + groupLevels: list[FieldUsage] | tuple[FieldUsage, ...] = (), extLst: ExtensionList | None = None, ) -> None: ... @overload @@ -357,8 +300,8 @@ class CacheHierarchy(Serialisable): unbalanced: _ConvertibleToBool | None = None, unbalancedGroup: _ConvertibleToBool | None = None, hidden: _ConvertibleToBool = None, - fieldsUsage: FieldsUsage | None = None, - groupLevels: GroupLevels | None = None, + fieldsUsage: list[FieldUsage] | tuple[FieldUsage, ...] = (), + groupLevels: list[FieldUsage] | tuple[FieldUsage, ...] = (), extLst: ExtensionList | None = None, ) -> None: ... @@ -376,20 +319,11 @@ class GroupItems(Serialisable): @property def count(self) -> int: ... -class DiscretePr(Serialisable): - tagname: ClassVar[str] - count: Integer[Literal[False]] - x: NestedInteger[Literal[True]] - __elements__: ClassVar[tuple[str, ...]] - def __init__( - self, count: ConvertibleToInt, x: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None - ) -> None: ... - class RangePr(Serialisable): tagname: ClassVar[str] autoStart: Bool[Literal[True]] autoEnd: Bool[Literal[True]] - groupBy: Set[_RangePrGroupBy] + groupBy: NoneSet[_RangePrGroupBy] startNum: Float[Literal[True]] endNum: Float[Literal[True]] startDate: DateTime[Literal[True]] @@ -412,7 +346,7 @@ class FieldGroup(Serialisable): par: Integer[Literal[True]] base: Integer[Literal[True]] rangePr: Typed[RangePr, Literal[True]] - discretePr: Typed[DiscretePr, Literal[True]] + discretePr: NestedSequence[list[NestedInteger[Literal[False]]]] groupItems: Typed[GroupItems, Literal[True]] __elements__: ClassVar[tuple[str, ...]] def __init__( @@ -420,7 +354,7 @@ class FieldGroup(Serialisable): par: ConvertibleToInt | None = None, base: ConvertibleToInt | None = None, rangePr: RangePr | None = None, - discretePr: DiscretePr | None = None, + discretePr: list[NestedInteger[Literal[False]]] | tuple[NestedInteger[Literal[False]], ...] = (), groupItems: GroupItems | None = None, ) -> None: ... @@ -569,21 +503,18 @@ class PageItem(Serialisable): name: String[Literal[False]] def __init__(self, name: str) -> None: ... -class Page(Serialisable): - tagname: ClassVar[str] - pageItem: Incomplete - __elements__: ClassVar[tuple[str, ...]] - def __init__(self, count: Incomplete | None = None, pageItem: Incomplete | None = None) -> None: ... - @property - def count(self) -> int: ... - class Consolidation(Serialisable): tagname: ClassVar[str] autoPage: Bool[Literal[True]] - pages: Incomplete - rangeSets: Incomplete + pages: NestedSequence[list[PageItem]] + rangeSets: NestedSequence[list[RangeSet]] __elements__: ClassVar[tuple[str, ...]] - def __init__(self, autoPage: _ConvertibleToBool | None = None, pages=(), rangeSets=()) -> None: ... + def __init__( + self, + autoPage: _ConvertibleToBool | None = None, + pages: list[PageItem] | tuple[PageItem, ...] = (), + rangeSets: list[RangeSet] | tuple[RangeSet, ...] = (), + ) -> None: ... class WorksheetSource(Serialisable): tagname: ClassVar[str] @@ -629,13 +560,13 @@ class CacheDefinition(Serialisable): minRefreshableVersion: Integer[Literal[True]] recordCount: Integer[Literal[True]] upgradeOnRefresh: Bool[Literal[True]] - tupleCache: Typed[TupleCache, Literal[True]] supportSubquery: Bool[Literal[True]] supportAdvancedDrill: Bool[Literal[True]] cacheSource: Typed[CacheSource, Literal[True]] cacheFields: Incomplete cacheHierarchies: Incomplete - kpis: Incomplete + kpis: NestedSequence[list[OLAPKPI]] + tupleCache: Typed[TupleCache, Literal[True]] calculatedItems: Incomplete calculatedMembers: Incomplete dimensions: Incomplete @@ -669,7 +600,7 @@ class CacheDefinition(Serialisable): cacheSource: CacheSource, cacheFields=(), cacheHierarchies=(), - kpis=(), + kpis: list[OLAPKPI] | tuple[OLAPKPI, ...] = (), calculatedItems=(), calculatedMembers=(), dimensions=(), diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/pivot/fields.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/pivot/fields.pyi index 3076fed4a..a35b43114 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/pivot/fields.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/pivot/fields.pyi @@ -11,8 +11,8 @@ class Index(Serialisable): def __init__(self, v: ConvertibleToInt | None = 0) -> None: ... class Tuple(Serialisable): - fld: Integer[Literal[False]] - hier: Integer[Literal[False]] + fld: Integer[Literal[True]] + hier: Integer[Literal[True]] item: Integer[Literal[False]] def __init__(self, fld: ConvertibleToInt, hier: ConvertibleToInt, item: ConvertibleToInt) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/alignment.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/alignment.pyi index d2b96de0a..6bad3b071 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/alignment.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/alignment.pyi @@ -16,7 +16,6 @@ vertical_aligments: Final[tuple[_VerticalAlignmentsType, ...]] class Alignment(Serialisable): tagname: ClassVar[str] - __fields__: ClassVar[tuple[str, ...]] horizontal: NoneSet[_HorizontalAlignmentsType] vertical: NoneSet[_VerticalAlignmentsType] textRotation: NoneSet[int] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/borders.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/borders.pyi index 5c05d5666..c54e2e55d 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/borders.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/borders.pyi @@ -39,7 +39,6 @@ BORDER_THICK: Final = "thick" BORDER_THIN: Final = "thin" class Side(Serialisable): - __fields__: ClassVar[tuple[str, ...]] color: ColorDescriptor[Literal[True]] style: NoneSet[_SideStyle] border_style: Alias @@ -52,7 +51,6 @@ class Side(Serialisable): class Border(Serialisable): tagname: ClassVar[str] - __fields__: ClassVar[tuple[str, ...]] __elements__: ClassVar[tuple[str, ...]] start: Typed[Side, Literal[True]] end: Typed[Side, Literal[True]] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fills.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fills.pyi index 7e1a62a98..85be254a9 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fills.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/fills.pyi @@ -88,9 +88,9 @@ class Stop(Serialisable): color: Incomplete def __init__(self, color, position: ConvertibleToFloat) -> None: ... -class StopList(Sequence): - expected_type: type[Incomplete] - def __set__(self, obj: Serialisable | Strict, values) -> None: ... +class StopList(Sequence[list[Stop]]): + expected_type: type[Stop] + def __set__(self, obj: Serialisable | Strict, values: list[Stop] | tuple[Stop, ...]) -> None: ... class GradientFill(Fill): tagname: ClassVar[str] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/named_styles.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/named_styles.pyi index 2cb2b2451..2e598cdb3 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/named_styles.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/styles/named_styles.pyi @@ -4,6 +4,7 @@ from typing import ClassVar, Literal from openpyxl.descriptors.base import Bool, Integer, String, Typed, _ConvertibleToBool from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.sequence import Sequence from openpyxl.descriptors.serialisable import Serialisable from openpyxl.styles.alignment import Alignment from openpyxl.styles.borders import Border @@ -22,8 +23,6 @@ class NamedStyle(Serialisable): protection: Typed[Protection, Literal[False]] builtinId: Integer[Literal[True]] hidden: Bool[Literal[True]] - # Overwritten by property below - # xfId: Integer name: String[Literal[False]] def __init__( self, @@ -36,12 +35,9 @@ class NamedStyle(Serialisable): protection: Protection | None = None, builtinId: ConvertibleToInt | None = None, hidden: _ConvertibleToBool | None = False, - xfId: Unused = None, ) -> None: ... def __setattr__(self, attr: str, value) -> None: ... def __iter__(self) -> Iterator[tuple[str, str]]: ... - @property - def xfId(self) -> int | None: ... def bind(self, wb: Workbook) -> None: ... def as_tuple(self) -> StyleArray: ... def as_xf(self) -> CellStyle: ... @@ -77,11 +73,10 @@ class _NamedCellStyle(Serialisable): class _NamedCellStyleList(Serialisable): tagname: ClassVar[str] # Overwritten by property below - # count: Integer - cellStyle: Incomplete + # count: Integer[Literal[True]] + cellStyle: Sequence[list[_NamedCellStyle]] __attrs__: ClassVar[tuple[str, ...]] - def __init__(self, count: Unused = None, cellStyle=()) -> None: ... + def __init__(self, count: Unused = None, cellStyle: list[_NamedCellStyle] | tuple[_NamedCellStyle, ...] = ()) -> None: ... @property def count(self) -> int: ... - @property - def names(self) -> NamedStyleList: ... + def remove_duplicates(self) -> list[_NamedCellStyle]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/utils/cell.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/utils/cell.pyi index 1d3b0b8e2..22a05774e 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/utils/cell.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/utils/cell.pyi @@ -17,8 +17,8 @@ SHEETRANGE_RE: Final[Pattern[str]] def get_column_interval(start: str | int, end: str | int) -> list[str]: ... def coordinate_from_string(coord_string: str) -> tuple[str, int]: ... def absolute_coordinate(coord_string: str) -> str: ... -def get_column_letter(idx: int) -> str: ... -def column_index_from_string(str_col: str) -> int: ... +def get_column_letter(col_idx: int) -> str: ... +def column_index_from_string(col: str) -> int: ... def range_boundaries(range_string: str) -> _RangeBoundariesTuple: ... def rows_from_range(range_string: str) -> Generator[tuple[str, ...], None, None]: ... def cols_from_range(range_string: str) -> Generator[tuple[str, ...], None, None]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/utils/indexed_list.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/utils/indexed_list.pyi index 417198076..9bf453a04 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/utils/indexed_list.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/utils/indexed_list.pyi @@ -7,6 +7,6 @@ class IndexedList(list[_T]): clean: bool def __init__(self, iterable: Iterable[_T] | None = None) -> None: ... def __contains__(self, value: object) -> bool: ... - def index(self, value: _T): ... # type: ignore[override] + def index(self, value: _T) -> int: ... # type: ignore[override] def append(self, value: _T) -> None: ... - def add(self, value: _T): ... + def add(self, value: _T) -> int: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/workbook/defined_name.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/workbook/defined_name.pyi index 0e7393ccf..4c456d189 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/workbook/defined_name.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/workbook/defined_name.pyi @@ -65,7 +65,7 @@ class DefinedNameDict(dict[str, DefinedName]): class DefinedNameList(Serialisable): tagname: ClassVar[str] - definedName: Sequence - def __init__(self, definedName=()) -> None: ... + definedName: Sequence[list[DefinedName]] + def __init__(self, definedName: list[DefinedName] | tuple[DefinedName, ...] = ()) -> None: ... def by_sheet(self) -> defaultdict[int, DefinedNameDict]: ... def __len__(self) -> int: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/_read_only.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/_read_only.pyi index 98d2c10cf..d5a32d36a 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/_read_only.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/_read_only.pyi @@ -1,5 +1,6 @@ from _typeshed import SupportsGetItem -from collections.abc import Generator +from collections.abc import Generator, Iterator +from typing import Any, overload from openpyxl import _VisibilityType from openpyxl.cell import _CellValue @@ -21,8 +22,15 @@ class ReadOnlyWorksheet: # https://github.com/python/mypy/issues/6700 @property def rows(self) -> Generator[tuple[Cell, ...], None, None]: ... - __getitem__ = Worksheet.__getitem__ - __iter__ = Worksheet.__iter__ + # From Worksheet.__getitem__ + @overload + def __getitem__(self, key: int) -> tuple[Cell, ...]: ... + @overload + def __getitem__(self, key: slice) -> tuple[Any, ...]: ... # tuple[AnyOf[Cell, tuple[Cell, ...]]] + @overload + def __getitem__(self, key: str) -> Any: ... # AnyOf[Cell, tuple[Cell, ...], tuple[tuple[Cell, ...], ...]] + # From Worksheet.__iter__ + def __iter__(self) -> Iterator[tuple[Cell, ...]]: ... parent: Workbook title: str sheet_state: _VisibilityType diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/datavalidation.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/datavalidation.pyi index cd44c40a1..85f40baea 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/datavalidation.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/datavalidation.pyi @@ -72,7 +72,7 @@ class DataValidation(Serialisable): showErrorMessage: _ConvertibleToBool | None = False, showInputMessage: _ConvertibleToBool | None = False, showDropDown: _ConvertibleToBool | None = False, - allowBlank: _ConvertibleToBool | None = False, + allowBlank: _ConvertibleToBool = False, sqref: _ConvertibleToMultiCellRange = (), promptTitle: str | None = None, errorStyle: _DataValidationErrorStyle | Literal["none"] | None = None, @@ -81,7 +81,7 @@ class DataValidation(Serialisable): errorTitle: str | None = None, imeMode: _DataValidationImeMode | Literal["none"] | None = None, operator: _DataValidationOperator | Literal["none"] | None = None, - allow_blank: Incomplete | None = False, + allow_blank: _ConvertibleToBool | None = None, ) -> None: ... def add(self, cell) -> None: ... def __contains__(self, cell: _HasCoordinate | str | CellRange) -> bool: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/dimensions.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/dimensions.pyi index 644e5684a..03a849348 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/dimensions.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/dimensions.pyi @@ -1,6 +1,6 @@ from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused from collections.abc import Callable, Iterator -from typing import ClassVar, Generic, Literal, TypeVar +from typing import ClassVar, Literal, TypeVar from typing_extensions import Self from openpyxl.descriptors import Strict @@ -12,6 +12,7 @@ from openpyxl.utils.cell import _RangeBoundariesTuple from openpyxl.worksheet.worksheet import Worksheet from openpyxl.xml.functions import Element +_DimKeyT = TypeVar("_DimKeyT", bound=str | int) _DimT = TypeVar("_DimT", bound=Dimension) class Dimension(Strict, StyleableObject): @@ -101,9 +102,11 @@ class ColumnDimension(Dimension): @property def customWidth(self) -> bool: ... def reindex(self) -> None: ... + @property + def range(self) -> str: ... def to_tree(self) -> Element | None: ... -class DimensionHolder(BoundDictionary[str, _DimT], Generic[_DimT]): +class DimensionHolder(BoundDictionary[_DimKeyT, _DimT]): worksheet: Worksheet max_outline: int | None default_factory: Callable[[], _DimT] | None @@ -111,7 +114,7 @@ class DimensionHolder(BoundDictionary[str, _DimT], Generic[_DimT]): def __init__( self, worksheet: Worksheet, reference: str = "index", default_factory: Callable[[], _DimT] | None = None ) -> None: ... - def group(self, start: str, end: str | None = None, outline_level: int = 1, hidden: bool = False) -> None: ... + def group(self, start: _DimKeyT, end: _DimKeyT | None = None, outline_level: int = 1, hidden: bool = False) -> None: ... def to_tree(self) -> Element | None: ... class SheetFormatProperties(Serialisable): diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/filters.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/filters.pyi index 30d12af81..4a641e818 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/filters.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/filters.pyi @@ -1,14 +1,11 @@ from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused from datetime import datetime -from re import Pattern -from typing import ClassVar, Literal, overload +from typing import ClassVar, Final, Literal, overload from typing_extensions import TypeAlias -from openpyxl.descriptors import Strict from openpyxl.descriptors.base import ( Alias, Bool, - Convertible, DateTime, Float, Integer, @@ -22,8 +19,6 @@ from openpyxl.descriptors.base import ( from openpyxl.descriptors.excel import ExtensionList from openpyxl.descriptors.serialisable import Serialisable -from ..descriptors.base import _N - _SortConditionSortBy: TypeAlias = Literal["value", "cellColor", "fontColor", "icon"] _IconSet: TypeAlias = Literal[ "3Arrows", @@ -48,6 +43,7 @@ _SortStateSortMethod: TypeAlias = Literal["stroke", "pinYin"] _CustomFilterOperator: TypeAlias = Literal[ "equal", "lessThan", "lessThanOrEqual", "notEqual", "greaterThanOrEqual", "greaterThan" ] +_StringFilterOperator: TypeAlias = Literal["contains", "startswith", "endswith", "wildcard"] _FiltersCalendarType: TypeAlias = Literal[ "gregorian", "gregorianUs", @@ -170,24 +166,32 @@ class DynamicFilter(Serialisable): maxValIso: datetime | str | None = None, ) -> None: ... -class CustomFilterValueDescriptor(Convertible[float | str, _N]): - pattern: Pattern[str] - expected_type: type[float | str] - @overload # type: ignore[override] # Different restrictions - def __set__( - self: CustomFilterValueDescriptor[Literal[True]], instance: Serialisable | Strict, value: str | ConvertibleToFloat | None - ) -> None: ... - @overload - def __set__( - self: CustomFilterValueDescriptor[Literal[False]], instance: Serialisable | Strict, value: str | ConvertibleToFloat - ) -> None: ... - class CustomFilter(Serialisable): tagname: ClassVar[str] - operator: NoneSet[_CustomFilterOperator] - val: Incomplete + val: String[Literal[False]] + operator: Set[_CustomFilterOperator] + def __init__(self, operator: _CustomFilterOperator = "equal", val: str | None = None) -> None: ... + def convert(self) -> BlankFilter | NumberFilter | StringFilter: ... + +class BlankFilter(CustomFilter): + def __init__(self, **kw: Unused) -> None: ... + @property + def operator(self) -> Literal["notEqual"]: ... # type: ignore[override] + @property + def val(self) -> Literal[" "]: ... # type: ignore[override] + +class NumberFilter(CustomFilter): + val: Float[Literal[False]] # type: ignore[assignment] + def __init__(self, operator: _CustomFilterOperator = "equal", val: ConvertibleToFloat | None = None) -> None: ... + +string_format_mapping: Final[dict[_StringFilterOperator, str]] + +class StringFilter(CustomFilter): + operator: Set[_StringFilterOperator] # type: ignore[assignment] + val: String[Literal[False]] + exclude: Bool[Literal[False]] def __init__( - self, operator: _CustomFilterOperator | Literal["none"] | None = None, val: Incomplete | None = None + self, operator: _StringFilterOperator = "contains", val: str | None = None, exclude: _ConvertibleToBool = False ) -> None: ... class CustomFilters(Serialisable): @@ -195,7 +199,7 @@ class CustomFilters(Serialisable): _and: Bool[Literal[True]] # Not private. Avoids name clash customFilter: Incomplete __elements__: ClassVar[tuple[str, ...]] - def __init__(self, _and: _ConvertibleToBool | None = False, customFilter=()) -> None: ... + def __init__(self, _and: _ConvertibleToBool | None = None, customFilter=()) -> None: ... class Top10(Serialisable): tagname: ClassVar[str] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/hyperlink.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/hyperlink.pyi index 03fa57ea7..1e8c5e166 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/hyperlink.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/hyperlink.pyi @@ -2,6 +2,7 @@ from _typeshed import Incomplete from typing import ClassVar, Literal from openpyxl.descriptors.base import String +from openpyxl.descriptors.sequence import Sequence from openpyxl.descriptors.serialisable import Serialisable class Hyperlink(Serialisable): @@ -25,8 +26,5 @@ class Hyperlink(Serialisable): class HyperlinkList(Serialisable): tagname: ClassVar[str] - hyperlink: Incomplete - def __init__(self, hyperlink=()) -> None: ... - def __bool__(self) -> bool: ... - def __len__(self) -> int: ... - def append(self, value) -> None: ... + hyperlink: Sequence[list[Hyperlink]] + def __init__(self, hyperlink: list[Hyperlink] | tuple[Hyperlink, ...] = ()) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/views.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/views.pyi index 0663b9ea4..6ea3c2acf 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/views.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/views.pyi @@ -4,6 +4,7 @@ from typing_extensions import TypeAlias from openpyxl.descriptors.base import Bool, Float, Integer, NoneSet, Set, String, Typed, _ConvertibleToBool from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.sequence import Sequence from openpyxl.descriptors.serialisable import Serialisable _Pane: TypeAlias = Literal["bottomRight", "topRight", "bottomLeft", "topLeft"] @@ -90,7 +91,9 @@ class SheetView(Serialisable): class SheetViewList(Serialisable): tagname: ClassVar[str] - sheetView: Incomplete + sheetView: Sequence[list[SheetView]] extLst: Typed[ExtensionList, Literal[True]] __elements__: ClassVar[tuple[str, ...]] - def __init__(self, sheetView: Incomplete | None = None, extLst: Unused = None) -> None: ... + def __init__(self, sheetView: SheetView | None = None, extLst: Unused = None) -> None: ... + @property + def active(self) -> SheetView: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi index 4adb8a835..436b4a114 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi @@ -51,8 +51,8 @@ class Worksheet(_WorkbookChild): ORIENTATION_PORTRAIT: Final = "portrait" ORIENTATION_LANDSCAPE: Final = "landscape" - row_dimensions: DimensionHolder[RowDimension] - column_dimensions: DimensionHolder[ColumnDimension] + row_dimensions: DimensionHolder[int, RowDimension] + column_dimensions: DimensionHolder[str, ColumnDimension] row_breaks: RowBreak col_breaks: ColBreak merged_cells: MultiCellRange @@ -190,6 +190,8 @@ class Worksheet(_WorkbookChild): ) -> Generator[tuple[Cell, ...], None, None] | Generator[tuple[str | float | datetime | None, ...], None, None]: ... @property def columns(self) -> Generator[tuple[Cell, ...], None, None]: ... + @property + def column_groups(self) -> list[str]: ... def set_printer_settings( self, paper_size: int | None, orientation: Literal["default", "portrait", "landscape"] | None ) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/peewee/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/peewee/METADATA.toml index aa10ee81b..f4f90b5e4 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/peewee/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/peewee/METADATA.toml @@ -1,4 +1,4 @@ -version = "3.17.3" +version = "3.17.5" upstream_repository = "https://github.com/coleifer/peewee" # We're not providing stubs for all playhouse modules right now # https://github.com/python/typeshed/pull/11731#issuecomment-2065729058 diff --git a/packages/pyright-internal/typeshed-fallback/stubs/peewee/peewee.pyi b/packages/pyright-internal/typeshed-fallback/stubs/peewee/peewee.pyi index 1df82987e..a03db334f 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/peewee/peewee.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/peewee/peewee.pyi @@ -459,7 +459,12 @@ class ForUpdate(Node): def __init__(self, expr, of: Incomplete | None = ..., nowait: Incomplete | None = ...) -> None: ... def __sql__(self, ctx): ... -def Case(predicate, expression_tuples, default: Incomplete | None = ...): ... +class Case(ColumnBase): + predicate: Incomplete + expression_tuples: Incomplete + default: Incomplete | None + def __init__(self, predicate, expression_tuples, default: Incomplete | None = None) -> None: ... + def __sql__(self, ctx): ... class NodeList(ColumnBase): nodes: Incomplete diff --git a/packages/pyright-internal/typeshed-fallback/stubs/protobuf/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/protobuf/METADATA.toml index ad7078f37..9e402da86 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/protobuf/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/protobuf/METADATA.toml @@ -1,8 +1,8 @@ # Whenever you update version here, PROTOBUF_VERSION should be updated # in scripts/generate_proto_stubs.sh and vice-versa. -version = "5.26.*" +version = "5.27.*" upstream_repository = "https://github.com/protocolbuffers/protobuf" -extra_description = "Generated using [mypy-protobuf==3.6.0](https://github.com/nipunn1313/mypy-protobuf/tree/v3.6.0) and libprotoc 25.1 on [protobuf v26.1](https://github.com/protocolbuffers/protobuf/releases/tag/v26.1) (python protobuf==5.26.1)" +extra_description = "Partially generated using [mypy-protobuf==3.6.0](https://github.com/nipunn1313/mypy-protobuf/tree/v3.6.0) and libprotoc 26.1 on [protobuf v27.1](https://github.com/protocolbuffers/protobuf/releases/tag/v27.1) (python protobuf==5.27.1)." partial_stub = true [tool.stubtest] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/protobuf/google/protobuf/descriptor_pb2.pyi b/packages/pyright-internal/typeshed-fallback/stubs/protobuf/google/protobuf/descriptor_pb2.pyi index b7a063ec6..020c3fccc 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/protobuf/google/protobuf/descriptor_pb2.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/protobuf/google/protobuf/descriptor_pb2.pyi @@ -35,6 +35,10 @@ class _EditionEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTy DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor EDITION_UNKNOWN: _Edition.ValueType # 0 """A placeholder for an unknown edition value.""" + EDITION_LEGACY: _Edition.ValueType # 900 + """A placeholder edition for specifying default behaviors *before* a feature + was first introduced. This is effectively an "infinite past". + """ EDITION_PROTO2: _Edition.ValueType # 998 """Legacy syntax "editions". These pre-date editions, but behave much like distinct editions. These can't be used to specify the edition of proto @@ -67,6 +71,10 @@ class Edition(_Edition, metaclass=_EditionEnumTypeWrapper): EDITION_UNKNOWN: Edition.ValueType # 0 """A placeholder for an unknown edition value.""" +EDITION_LEGACY: Edition.ValueType # 900 +"""A placeholder edition for specifying default behaviors *before* a feature +was first introduced. This is effectively an "infinite past". +""" EDITION_PROTO2: Edition.ValueType # 998 """Legacy syntax "editions". These pre-date editions, but behave much like distinct editions. These can't be used to specify the edition of proto @@ -898,12 +906,16 @@ class FileOptions(google.protobuf.message.Message): java_generate_equals_and_hash: builtins.bool """This option does nothing.""" java_string_check_utf8: builtins.bool - """If set true, then the Java2 code generator will generate code that - throws an exception whenever an attempt is made to assign a non-UTF-8 - byte sequence to a string field. - Message reflection will do the same. - However, an extension field still accepts non-UTF-8 byte sequences. - This option has no effect on when used with the lite runtime. + """A proto2 file can set this to true to opt in to UTF-8 checking for Java, + which will throw an exception if invalid UTF-8 is parsed from the wire or + assigned to a string field. + + TODO: clarify exactly what kinds of field types this option + applies to, and update these docs accordingly. + + Proto3 files already perform these checks. Setting the option explicitly to + false has no effect: it cannot be used to opt proto3 files out of UTF-8 + checks. """ optimize_for: global___FileOptions.OptimizeMode.ValueType go_package: builtins.str @@ -1238,6 +1250,45 @@ class FieldOptions(google.protobuf.message.Message): def HasField(self, field_name: typing.Literal["edition", b"edition", "value", b"value"]) -> builtins.bool: ... def ClearField(self, field_name: typing.Literal["edition", b"edition", "value", b"value"]) -> None: ... + @typing.final + class FeatureSupport(google.protobuf.message.Message): + """Information about the support window of a feature.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EDITION_INTRODUCED_FIELD_NUMBER: builtins.int + EDITION_DEPRECATED_FIELD_NUMBER: builtins.int + DEPRECATION_WARNING_FIELD_NUMBER: builtins.int + EDITION_REMOVED_FIELD_NUMBER: builtins.int + edition_introduced: global___Edition.ValueType + """The edition that this feature was first available in. In editions + earlier than this one, the default assigned to EDITION_LEGACY will be + used, and proto files will not be able to override it. + """ + edition_deprecated: global___Edition.ValueType + """The edition this feature becomes deprecated in. Using this after this + edition may trigger warnings. + """ + deprecation_warning: builtins.str + """The deprecation warning text if this feature is used after the edition it + was marked deprecated in. + """ + edition_removed: global___Edition.ValueType + """The edition this feature is no longer available in. In editions after + this one, the last default assigned will be used, and proto files will + not be able to override it. + """ + def __init__( + self, + *, + edition_introduced: global___Edition.ValueType | None = ..., + edition_deprecated: global___Edition.ValueType | None = ..., + deprecation_warning: builtins.str | None = ..., + edition_removed: global___Edition.ValueType | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["deprecation_warning", b"deprecation_warning", "edition_deprecated", b"edition_deprecated", "edition_introduced", b"edition_introduced", "edition_removed", b"edition_removed"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["deprecation_warning", b"deprecation_warning", "edition_deprecated", b"edition_deprecated", "edition_introduced", b"edition_introduced", "edition_removed", b"edition_removed"]) -> None: ... + CTYPE_FIELD_NUMBER: builtins.int PACKED_FIELD_NUMBER: builtins.int JSTYPE_FIELD_NUMBER: builtins.int @@ -1250,6 +1301,7 @@ class FieldOptions(google.protobuf.message.Message): TARGETS_FIELD_NUMBER: builtins.int EDITION_DEFAULTS_FIELD_NUMBER: builtins.int FEATURES_FIELD_NUMBER: builtins.int + FEATURE_SUPPORT_FIELD_NUMBER: builtins.int UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int ctype: global___FieldOptions.CType.ValueType """The ctype option instructs the C++ code generator to use a different @@ -1331,6 +1383,8 @@ class FieldOptions(google.protobuf.message.Message): def features(self) -> global___FeatureSet: """Any features defined in the specific edition.""" + @property + def feature_support(self) -> global___FieldOptions.FeatureSupport: ... @property def uninterpreted_option(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: """The parser stores options it doesn't recognize here. See above.""" @@ -1350,10 +1404,11 @@ class FieldOptions(google.protobuf.message.Message): targets: collections.abc.Iterable[global___FieldOptions.OptionTargetType.ValueType] | None = ..., edition_defaults: collections.abc.Iterable[global___FieldOptions.EditionDefault] | None = ..., features: global___FeatureSet | None = ..., + feature_support: global___FieldOptions.FeatureSupport | None = ..., uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., ) -> None: ... - def HasField(self, field_name: typing.Literal["ctype", b"ctype", "debug_redact", b"debug_redact", "deprecated", b"deprecated", "features", b"features", "jstype", b"jstype", "lazy", b"lazy", "packed", b"packed", "retention", b"retention", "unverified_lazy", b"unverified_lazy", "weak", b"weak"]) -> builtins.bool: ... - def ClearField(self, field_name: typing.Literal["ctype", b"ctype", "debug_redact", b"debug_redact", "deprecated", b"deprecated", "edition_defaults", b"edition_defaults", "features", b"features", "jstype", b"jstype", "lazy", b"lazy", "packed", b"packed", "retention", b"retention", "targets", b"targets", "uninterpreted_option", b"uninterpreted_option", "unverified_lazy", b"unverified_lazy", "weak", b"weak"]) -> None: ... + def HasField(self, field_name: typing.Literal["ctype", b"ctype", "debug_redact", b"debug_redact", "deprecated", b"deprecated", "feature_support", b"feature_support", "features", b"features", "jstype", b"jstype", "lazy", b"lazy", "packed", b"packed", "retention", b"retention", "unverified_lazy", b"unverified_lazy", "weak", b"weak"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["ctype", b"ctype", "debug_redact", b"debug_redact", "deprecated", b"deprecated", "edition_defaults", b"edition_defaults", "feature_support", b"feature_support", "features", b"features", "jstype", b"jstype", "lazy", b"lazy", "packed", b"packed", "retention", b"retention", "targets", b"targets", "uninterpreted_option", b"uninterpreted_option", "unverified_lazy", b"unverified_lazy", "weak", b"weak"]) -> None: ... global___FieldOptions = FieldOptions @@ -1438,6 +1493,7 @@ class EnumValueOptions(google.protobuf.message.Message): DEPRECATED_FIELD_NUMBER: builtins.int FEATURES_FIELD_NUMBER: builtins.int DEBUG_REDACT_FIELD_NUMBER: builtins.int + FEATURE_SUPPORT_FIELD_NUMBER: builtins.int UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int deprecated: builtins.bool """Is this enum value deprecated? @@ -1454,6 +1510,10 @@ class EnumValueOptions(google.protobuf.message.Message): def features(self) -> global___FeatureSet: """Any features defined in the specific edition.""" + @property + def feature_support(self) -> global___FieldOptions.FeatureSupport: + """Information about the support window of a feature value.""" + @property def uninterpreted_option(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: """The parser stores options it doesn't recognize here. See above.""" @@ -1464,10 +1524,11 @@ class EnumValueOptions(google.protobuf.message.Message): deprecated: builtins.bool | None = ..., features: global___FeatureSet | None = ..., debug_redact: builtins.bool | None = ..., + feature_support: global___FieldOptions.FeatureSupport | None = ..., uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., ) -> None: ... - def HasField(self, field_name: typing.Literal["debug_redact", b"debug_redact", "deprecated", b"deprecated", "features", b"features"]) -> builtins.bool: ... - def ClearField(self, field_name: typing.Literal["debug_redact", b"debug_redact", "deprecated", b"deprecated", "features", b"features", "uninterpreted_option", b"uninterpreted_option"]) -> None: ... + def HasField(self, field_name: typing.Literal["debug_redact", b"debug_redact", "deprecated", b"deprecated", "feature_support", b"feature_support", "features", b"features"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["debug_redact", b"debug_redact", "deprecated", b"deprecated", "feature_support", b"feature_support", "features", b"features", "uninterpreted_option", b"uninterpreted_option"]) -> None: ... global___EnumValueOptions = EnumValueOptions @@ -1799,18 +1860,26 @@ class FeatureSetDefaults(google.protobuf.message.Message): DESCRIPTOR: google.protobuf.descriptor.Descriptor EDITION_FIELD_NUMBER: builtins.int - FEATURES_FIELD_NUMBER: builtins.int + OVERRIDABLE_FEATURES_FIELD_NUMBER: builtins.int + FIXED_FEATURES_FIELD_NUMBER: builtins.int edition: global___Edition.ValueType @property - def features(self) -> global___FeatureSet: ... + def overridable_features(self) -> global___FeatureSet: + """Defaults of features that can be overridden in this edition.""" + + @property + def fixed_features(self) -> global___FeatureSet: + """Defaults of features that can't be overridden in this edition.""" + def __init__( self, *, edition: global___Edition.ValueType | None = ..., - features: global___FeatureSet | None = ..., + overridable_features: global___FeatureSet | None = ..., + fixed_features: global___FeatureSet | None = ..., ) -> None: ... - def HasField(self, field_name: typing.Literal["edition", b"edition", "features", b"features"]) -> builtins.bool: ... - def ClearField(self, field_name: typing.Literal["edition", b"edition", "features", b"features"]) -> None: ... + def HasField(self, field_name: typing.Literal["edition", b"edition", "fixed_features", b"fixed_features", "overridable_features", b"overridable_features"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["edition", b"edition", "fixed_features", b"fixed_features", "overridable_features", b"overridable_features"]) -> None: ... DEFAULTS_FIELD_NUMBER: builtins.int MINIMUM_EDITION_FIELD_NUMBER: builtins.int diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psutil/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/psutil/METADATA.toml index 9cd22571b..aeea3dbe0 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psutil/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/psutil/METADATA.toml @@ -1,4 +1,4 @@ -version = "5.9.*" +version = "6.0.*" upstream_repository = "https://github.com/giampaolo/psutil" [tool.stubtest] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/__init__.pyi index c68c1d214..b01ee3549 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/__init__.pyi @@ -3,7 +3,7 @@ from _typeshed import Incomplete from collections.abc import Callable, Iterable, Iterator from contextlib import AbstractContextManager from typing import Any, Literal, overload -from typing_extensions import Self, TypeAlias +from typing_extensions import Self, TypeAlias, deprecated from psutil._common import ( AIX as AIX, @@ -216,6 +216,7 @@ class Process: def memory_full_info(self) -> pfullmem: ... def memory_percent(self, memtype: str = "rss") -> float: ... def open_files(self) -> list[popenfile]: ... + @deprecated('use "net_connections" method instead') def connections(self, kind: str = "inet") -> list[pconn]: ... def send_signal(self, sig: int) -> None: ... def suspend(self) -> None: ... @@ -223,6 +224,7 @@ class Process: def terminate(self) -> None: ... def kill(self) -> None: ... def wait(self, timeout: float | None = None) -> int: ... + def net_connections(self, kind: str = "inet") -> list[pconn]: ... class Popen(Process): def __init__(self, *args, **kwargs) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_common.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_common.pyi index d755aa61d..7ea0bbb81 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_common.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_common.pyi @@ -89,8 +89,6 @@ class sdiskpart(NamedTuple): mountpoint: str fstype: str opts: str - maxfile: int - maxpath: int class snetio(NamedTuple): bytes_sent: int diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_compat.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_compat.pyi index 49fd95621..9bdcbe7d1 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_compat.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_compat.pyi @@ -20,7 +20,6 @@ xrange = range unicode = str basestring = str -def u(s): ... def b(s): ... SubprocessTimeoutExpired = TimeoutExpired diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psaix.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psaix.pyi index 4b0dabdbe..c74f03021 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psaix.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psaix.pyi @@ -85,7 +85,7 @@ class Process: def create_time(self): ... def num_threads(self): ... def threads(self): ... - def connections(self, kind: str = ...): ... + def net_connections(self, kind: str = ...): ... def nice_get(self): ... def nice_set(self, value): ... def ppid(self): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psbsd.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psbsd.pyi index 16895183f..9e85dd9de 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psbsd.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psbsd.pyi @@ -136,7 +136,7 @@ class Process: def num_threads(self): ... def num_ctx_switches(self): ... def threads(self): ... - def connections(self, kind: str = ...): ... + def net_connections(self, kind: str = ...): ... def wait(self, timeout: Incomplete | None = ...): ... def nice_get(self): ... def nice_set(self, value): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pslinux.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pslinux.pyi index 3e390fda7..70b78688a 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pslinux.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pslinux.pyi @@ -148,7 +148,7 @@ net_if_addrs: Any class _Ipv6UnsupportedError(Exception): ... -class Connections: +class NetConnections: tmap: Any def __init__(self) -> None: ... def get_proc_inodes(self, pid): ... @@ -220,7 +220,7 @@ class Process: def rlimit(self, resource_, limits: Incomplete | None = ...): ... def status(self): ... def open_files(self): ... - def connections(self, kind: str = ...): ... + def net_connections(self, kind: str = ...): ... def num_fds(self): ... def ppid(self): ... def uids(self, _uids_re=...): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psosx.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psosx.pyi index 895d66f79..85bb909e5 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psosx.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psosx.pyi @@ -99,7 +99,7 @@ class Process: def num_ctx_switches(self): ... def num_threads(self): ... def open_files(self): ... - def connections(self, kind: str = ...): ... + def net_connections(self, kind: str = ...): ... def num_fds(self): ... def wait(self, timeout: Incomplete | None = ...): ... def nice_get(self): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pssunos.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pssunos.pyi index f5782aa0b..480dedfe7 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pssunos.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pssunos.pyi @@ -114,7 +114,7 @@ class Process: def status(self): ... def threads(self): ... def open_files(self): ... - def connections(self, kind: str = ...): ... + def net_connections(self, kind: str = ...): ... class nt_mmap_grouped(NamedTuple): path: Incomplete diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psutil_osx.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psutil_osx.pyi index 79f291bf9..3a6ea7372 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psutil_osx.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_psutil_osx.pyi @@ -33,7 +33,7 @@ def net_io_counters(*args, **kwargs) -> Any: ... def per_cpu_times(*args, **kwargs) -> Any: ... def pids(*args, **kwargs) -> Any: ... def proc_cmdline(*args, **kwargs) -> Any: ... -def proc_connections(*args, **kwargs) -> Any: ... +def proc_net_connections(*args, **kwargs) -> Any: ... def proc_cwd(*args, **kwargs) -> Any: ... def proc_environ(*args, **kwargs) -> Any: ... def proc_exe(*args, **kwargs) -> Any: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pswindows.pyi b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pswindows.pyi index eb3bd612c..606383aef 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pswindows.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/psutil/psutil/_pswindows.pyi @@ -190,7 +190,7 @@ class Process: def resume(self) -> None: ... def cwd(self): ... def open_files(self): ... - def connections(self, kind: str = "inet"): ... + def net_connections(self, kind: str = "inet"): ... def nice_get(self): ... def nice_set(self, value): ... def ionice_get(self): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/METADATA.toml index f39bc8b31..e024779a5 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/METADATA.toml @@ -1,4 +1,4 @@ -version = "6.6.*" +version = "6.8.*" upstream_repository = "https://github.com/pyinstaller/pyinstaller" requires = ["types-setuptools"] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/__main__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/__main__.pyi index 87e980344..8b295520d 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/__main__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/__main__.pyi @@ -9,3 +9,4 @@ _PyIConfig: TypeAlias = ( # https://pyinstaller.org/en/stable/usage.html#running-pyinstaller-from-python-code def run(pyi_args: Iterable[str] | None = None, pyi_config: _PyIConfig | None = None) -> None: ... +def check_unsafe_privileges() -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/building/splash.pyi b/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/building/splash.pyi index a6dd06f71..da76b1162 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/building/splash.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/building/splash.pyi @@ -12,7 +12,6 @@ class Splash(Target): name: Incomplete script_name: Incomplete minify_script: Incomplete - rundir: Incomplete max_img_size: Incomplete text_pos: Incomplete text_size: Incomplete @@ -37,7 +36,6 @@ class Splash(Target): text_default: str = "Initializing", full_tk: bool = False, minify_script: bool = True, - rundir: str = "__splash", name: str = ..., script_name: str = ..., max_img_size: tuple[int, int] | None = (760, 480), diff --git a/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/compat.pyi b/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/compat.pyi index 8b5fae0da..72e3d48b0 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/compat.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/pyinstaller/PyInstaller/compat.pyi @@ -1,8 +1,8 @@ # https://pyinstaller.org/en/stable/hooks.html#module-PyInstaller.compat -from _typeshed import FileDescriptorOrPath, GenericPath +from _typeshed import FileDescriptorOrPath from collections.abc import Iterable from types import ModuleType -from typing import AnyStr, Final, Literal, overload +from typing import Final, Literal, overload strict_collect_mode: bool is_64bits: Final[bool] @@ -65,7 +65,6 @@ def exec_command_all( ) -> tuple[int, str, str]: ... def exec_python(*args: str, **kwargs: str | None) -> str: ... def exec_python_rc(*args: str, **kwargs: str | None) -> int: ... -def expand_path(path: GenericPath[AnyStr]) -> AnyStr: ... def getsitepackages(prefixes: Iterable[str] | None = None) -> list[str]: ... def importlib_load_source(name: str, pathname: str) -> ModuleType: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/reportlab/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/reportlab/METADATA.toml index 0b276f0d6..fa3e5c756 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/reportlab/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/reportlab/METADATA.toml @@ -1,5 +1,6 @@ -version = "4.2.*" -# NOTE: There is no public upstream repository +version = "4.2.0" +# GitHub mirror of https://hg.reportlab.com/hg-public/reportlab/file +upstream_repository = "https://github.com/MrBitBucket/reportlab-mirror" [tool.stubtest] apt_dependencies = ["libcairo2-dev"] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/requests/requests/models.pyi b/packages/pyright-internal/typeshed-fallback/stubs/requests/requests/models.pyi index 7e1a2e2de..e63d44f73 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/requests/requests/models.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/requests/requests/models.pyi @@ -1,5 +1,5 @@ import datetime -from _typeshed import Incomplete, Unused +from _typeshed import Incomplete, MaybeNone, Unused from collections.abc import Callable, Iterator from json import JSONDecoder from typing import Any @@ -144,7 +144,7 @@ class Response: self, chunk_size: int | None = 512, decode_unicode: bool = False, delimiter: str | bytes | None = None ) -> Iterator[Incomplete]: ... @property - def content(self) -> bytes: ... + def content(self) -> bytes | MaybeNone: ... @property def text(self) -> str: ... def json( diff --git a/packages/pyright-internal/typeshed-fallback/stubs/seaborn/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/seaborn/METADATA.toml index 4c5367456..d853169a8 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/seaborn/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/seaborn/METADATA.toml @@ -1,6 +1,7 @@ version = "0.13.2" # Requires a version of numpy and matplotlib with a `py.typed` file -requires = ["matplotlib>=3.8", "numpy>=1.20", "pandas-stubs"] +# TODO: stubtest errors when using numpy 2 +requires = ["matplotlib>=3.8", "numpy>=1.20,<2", "pandas-stubs"] # matplotlib>=3.8 requires Python >=3.9 requires_python = ">=3.9" upstream_repository = "https://github.com/mwaskom/seaborn" diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/METADATA.toml index 6d7b157b2..ba9bae6d6 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/METADATA.toml @@ -1,4 +1,4 @@ -version = "70.0.*" +version = "70.1.*" upstream_repository = "https://github.com/pypa/setuptools" [tool.stubtest] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/pkg_resources/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/pkg_resources/__init__.pyi index f31960dcf..6cfc305c1 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/pkg_resources/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/pkg_resources/__init__.pyi @@ -1,4 +1,3 @@ -import sys import types import zipimport from _typeshed import BytesPath, Incomplete, StrOrBytesPath, StrPath, Unused @@ -7,30 +6,32 @@ from io import BytesIO from itertools import chain from pkgutil import get_importer as get_importer from re import Pattern -from typing import IO, Any, ClassVar, Final, Literal, NoReturn, Protocol, TypeVar, overload, type_check_only +from typing import IO, Any, ClassVar, Final, Literal, NamedTuple, NoReturn, Protocol, TypeVar, overload from typing_extensions import Self, TypeAlias from zipfile import ZipInfo from ._vendored_packaging import requirements as packaging_requirements, version as packaging_version -# TODO: Use _typeshed.importlib.LoaderProtocol once mypy has included it in its vendored typeshed -class _LoaderProtocol(Protocol): - def load_module(self, fullname: str, /) -> types.ModuleType: ... - +# defined in setuptools _T = TypeVar("_T") -_D = TypeVar("_D", bound=Distribution) +_DistributionT = TypeVar("_DistributionT", bound=Distribution) _NestedStr: TypeAlias = str | Iterable[_NestedStr] -_StrictInstallerType: TypeAlias = Callable[[Requirement], _D] -_InstallerType: TypeAlias = Callable[[Requirement], Distribution | None] | None +_InstallerTypeT: TypeAlias = Callable[[Requirement], _DistributionT] # noqa: Y043 +_InstallerType: TypeAlias = Callable[[Requirement], Distribution | None] _PkgReqType: TypeAlias = str | Requirement _EPDistType: TypeAlias = Distribution | _PkgReqType _MetadataType: TypeAlias = IResourceProvider | None _ResolvedEntryPoint: TypeAlias = Any # Can be any attribute in the module +_ResourceStream: TypeAlias = Incomplete # A readable file-like object _ModuleLike: TypeAlias = object | types.ModuleType # Any object that optionally has __loader__ or __file__, usually a module -_ProviderFactoryType: TypeAlias = Callable[[_ModuleLike], IResourceProvider] +# Any: Should be _ModuleLike but we end up with issues where _ModuleLike doesn't have _ZipLoaderModule's __loader__ +_ProviderFactoryType: TypeAlias = Callable[[Any], IResourceProvider] _DistFinderType: TypeAlias = Callable[[_T, str, bool], Iterable[Distribution]] _NSHandlerType: TypeAlias = Callable[[_T, str, str, types.ModuleType], str | None] -_ResourceStream: TypeAlias = Incomplete # A readable file-like object + +# TODO: Use _typeshed.importlib.LoaderProtocol after mypy 1.11 is released +class _LoaderProtocol(Protocol): + def load_module(self, fullname: str, /) -> types.ModuleType: ... __all__ = [ "require", @@ -106,7 +107,6 @@ __all__ = [ "AvailableDistributions", ] -@type_check_only class _ZipLoaderModule(Protocol): __loader__: zipimport.zipimporter @@ -128,48 +128,52 @@ class WorkingSet: self, requirements: Iterable[Requirement], env: Environment | None, - installer: _StrictInstallerType[_D], + installer: _InstallerTypeT[_DistributionT], replace_conflicting: bool = False, extras: tuple[str, ...] | None = None, - ) -> list[_D]: ... + ) -> list[_DistributionT]: ... @overload def resolve( # type: ignore[overload-overlap] self, requirements: Iterable[Requirement], env: Environment | None = None, *, - installer: _StrictInstallerType[_D], + installer: _InstallerTypeT[_DistributionT], replace_conflicting: bool = False, extras: tuple[str, ...] | None = None, - ) -> list[_D]: ... + ) -> list[_DistributionT]: ... @overload - def resolve( + def resolve( # type: ignore[overload-overlap] self, requirements: Iterable[Requirement], env: Environment | None = None, - installer: _InstallerType = None, + installer: _InstallerType | None = None, replace_conflicting: bool = False, extras: tuple[str, ...] | None = None, ) -> list[Distribution]: ... @overload def find_plugins( # type: ignore[overload-overlap] - self, plugin_env: Environment, full_env: Environment | None, installer: _StrictInstallerType[_D], fallback: bool = True - ) -> tuple[list[_D], dict[Distribution, Exception]]: ... + self, + plugin_env: Environment, + full_env: Environment | None, + installer: _InstallerTypeT[_DistributionT], + fallback: bool = True, + ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ... @overload def find_plugins( # type: ignore[overload-overlap] self, plugin_env: Environment, full_env: Environment | None = None, *, - installer: _StrictInstallerType[_D], + installer: _InstallerTypeT[_DistributionT], fallback: bool = True, - ) -> tuple[list[_D], dict[Distribution, Exception]]: ... + ) -> tuple[list[_DistributionT], dict[Distribution, Exception]]: ... @overload def find_plugins( self, plugin_env: Environment, full_env: Environment | None = None, - installer: _InstallerType = None, + installer: _InstallerType | None = None, fallback: bool = True, ) -> tuple[list[Distribution], dict[Distribution, Exception]]: ... def require(self, *requirements: _NestedStr) -> Sequence[Distribution]: ... @@ -186,18 +190,26 @@ class Environment: def add(self, dist: Distribution) -> None: ... @overload def best_match( - self, req: Requirement, working_set: WorkingSet, installer: _StrictInstallerType[_D], replace_conflicting: bool = False - ) -> _D: ... + self, + req: Requirement, + working_set: WorkingSet, + installer: _InstallerTypeT[_DistributionT], + replace_conflicting: bool = False, + ) -> _DistributionT: ... @overload def best_match( - self, req: Requirement, working_set: WorkingSet, installer: _InstallerType = None, replace_conflicting: bool = False + self, + req: Requirement, + working_set: WorkingSet, + installer: _InstallerType | None = None, + replace_conflicting: bool = False, ) -> Distribution | None: ... @overload - def obtain(self, requirement: Requirement, installer: _StrictInstallerType[_D]) -> _D: ... # type: ignore[overload-overlap] + def obtain(self, requirement: Requirement, installer: _InstallerTypeT[_DistributionT]) -> _DistributionT: ... # type: ignore[overload-overlap] @overload def obtain(self, requirement: Requirement, installer: Callable[[Requirement], None] | None = None) -> None: ... @overload - def obtain(self, requirement: Requirement, installer: _InstallerType = None) -> Distribution | None: ... + def obtain(self, requirement: Requirement, installer: _InstallerType | None = None) -> Distribution | None: ... def __iter__(self) -> Iterator[str]: ... def __iadd__(self, other: Distribution | Environment) -> Self: ... def __add__(self, other: Distribution | Environment) -> Self: ... @@ -239,12 +251,12 @@ class EntryPoint: ) -> None: ... @overload def load( - self, require: Literal[True] = True, env: Environment | None = None, installer: _InstallerType = None + self, require: Literal[True] = True, env: Environment | None = None, installer: _InstallerType | None = None ) -> _ResolvedEntryPoint: ... @overload - def load(self, require: Literal[False], *args: Unused, **kwargs: Unused) -> _ResolvedEntryPoint: ... + def load(self, require: Literal[False], *args: Any, **kwargs: Any) -> _ResolvedEntryPoint: ... def resolve(self) -> _ResolvedEntryPoint: ... - def require(self, env: Environment | None = None, installer: _InstallerType = None) -> None: ... + def require(self, env: Environment | None = None, installer: _InstallerType | None = None) -> None: ... pattern: ClassVar[Pattern[str]] @classmethod def parse(cls, src: str, dist: Distribution | None = None) -> Self: ... @@ -256,8 +268,17 @@ class EntryPoint: ) -> dict[str, dict[str, Self]]: ... def find_distributions(path_item: str, only: bool = False) -> Generator[Distribution, None, None]: ... +def find_eggs_in_zip(importer: zipimport.zipimporter, path_item: str, only: bool = False) -> Iterator[Distribution]: ... +def find_nothing(importer: object | None, path_item: str | None, only: bool | None = False) -> tuple[Distribution, ...]: ... +def find_on_path(importer: object | None, path_item: str, only: bool = False) -> Generator[Distribution, None, None]: ... +def dist_factory(path_item: StrPath, entry: str, only: bool) -> Callable[[str], Iterable[Distribution]]: ... + +class NoDists: + def __bool__(self) -> Literal[False]: ... + def __call__(self, fullpath: Unused) -> Iterator[Distribution]: ... + @overload -def get_distribution(dist: _D) -> _D: ... +def get_distribution(dist: _DistributionT) -> _DistributionT: ... @overload def get_distribution(dist: _PkgReqType) -> Distribution: ... @@ -279,7 +300,7 @@ class ResourceManager: def resource_listdir(self, package_or_requirement: _PkgReqType, resource_name: str) -> list[str]: ... def extraction_error(self) -> NoReturn: ... def get_cache_path(self, archive_name: str, names: Iterable[StrPath] = ()) -> str: ... - def postprocess(self, tempname: StrOrBytesPath, filename: str) -> None: ... + def postprocess(self, tempname: StrOrBytesPath, filename: StrOrBytesPath) -> None: ... def set_extraction_path(self, path: str) -> None: ... def cleanup_resources(self, force: bool = False) -> list[str]: ... @@ -298,16 +319,6 @@ class IMetadataProvider(Protocol): class ResolutionError(Exception): ... -class DistributionNotFound(ResolutionError): - def __init__(self, req: Requirement, requirers: set[str] | None, /, *args: object) -> None: ... - @property - def req(self) -> Requirement: ... - @property - def requirers(self) -> set[str] | None: ... - @property - def requirers_str(self) -> str: ... - def report(self) -> str: ... - class VersionConflict(ResolutionError): def __init__(self, dist: Distribution, req: Requirement, /, *args: object) -> None: ... @property @@ -322,6 +333,16 @@ class ContextualVersionConflict(VersionConflict): @property def required_by(self) -> set[str]: ... +class DistributionNotFound(ResolutionError): + def __init__(self, req: Requirement, requirers: set[str] | None, /, *args: object) -> None: ... + @property + def req(self) -> Requirement: ... + @property + def requirers(self) -> set[str] | None: ... + @property + def requirers_str(self) -> str: ... + def report(self) -> str: ... + class UnknownExtra(ResolutionError): ... class ExtractionError(Exception): @@ -331,6 +352,7 @@ class ExtractionError(Exception): def register_finder(importer_type: type[_T], distribution_finder: _DistFinderType[_T]) -> None: ... def register_loader_type(loader_type: type[_ModuleLike], provider_factory: _ProviderFactoryType) -> None: ... +def resolve_egg_link(path: str) -> Iterable[Distribution]: ... def register_namespace_handler(importer_type: type[_T], namespace_handler: _NSHandlerType[_T]) -> None: ... class IResourceProvider(IMetadataProvider, Protocol): @@ -348,7 +370,7 @@ class NullProvider: egg_name: str | None egg_info: str | None loader: _LoaderProtocol | None - module_path: str | None + module_path: str def __init__(self, module: _ModuleLike) -> None: ... def get_resource_filename(self, manager: ResourceManager, resource_name: str) -> str: ... @@ -449,11 +471,24 @@ class EggMetadata(ZipProvider): def __init__(self, importer: zipimport.zipimporter) -> None: ... class EmptyProvider(NullProvider): - module_path: None + # A special case, we don't want all Providers inheriting from NullProvider to have a potentially None module_path + module_path: str | None # type:ignore[assignment] def __init__(self) -> None: ... empty_provider: EmptyProvider +class ZipManifests(dict[str, MemoizedZipManifests.manifest_mod]): + @classmethod + def build(cls, path: str) -> dict[str, ZipInfo]: ... + load = build + +class MemoizedZipManifests(ZipManifests): + class manifest_mod(NamedTuple): + manifest: dict[str, ZipInfo] + mtime: float + + def load(self, path: str) -> dict[str, ZipInfo]: ... # type: ignore[override] + class FileMetadata(EmptyProvider): path: StrPath def __init__(self, path: StrPath) -> None: ... @@ -499,8 +534,3 @@ iter_entry_points = working_set.iter_entry_points add_activation_listener = working_set.subscribe run_script = working_set.run_script run_main = run_script - -if sys.version_info >= (3, 10): - LOCALE_ENCODING: Final = "locale" -else: - LOCALE_ENCODING: Final = None diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/__init__.pyi index 75dbef9ba..e16ea2449 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/__init__.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/__init__.pyi @@ -1,7 +1,7 @@ from _typeshed import StrPath from abc import abstractmethod from collections.abc import Iterable, Mapping, Sequence -from typing import Any, Literal +from typing import Any from ._distutils.cmd import Command as _Command from .depends import Require as Require @@ -76,9 +76,7 @@ class Command(_Command): distribution: Distribution def __init__(self, dist: Distribution, **kw: Any) -> None: ... def ensure_string_list(self, option: str | list[str]) -> None: ... - def reinitialize_command( - self, command: _Command | str, reinit_subcommands: bool | Literal[0, 1] = 0, **kw: Any - ) -> _Command: ... + def reinitialize_command(self, command: _Command | str, reinit_subcommands: bool = False, **kw: Any) -> _Command: ... # type: ignore[override] @abstractmethod def initialize_options(self) -> None: ... @abstractmethod diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/build_meta.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/build_meta.pyi index 3097252d1..cf04af017 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/build_meta.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/build_meta.pyi @@ -1,6 +1,7 @@ from _typeshed import StrPath from collections.abc import Mapping from typing import Any +from typing_extensions import TypeAlias from . import dist @@ -17,6 +18,8 @@ __all__ = [ "SetupRequirementsError", ] +_ConfigSettings: TypeAlias = dict[str, str | list[str] | None] | None + class SetupRequirementsError(BaseException): specifiers: Any def __init__(self, specifiers) -> None: ... @@ -34,11 +37,11 @@ class _BuildMetaBackend: self, metadata_directory: str, config_settings: Mapping[str, Any] | None = None ) -> str: ... def build_wheel( - self, wheel_directory: StrPath, config_settings: Mapping[str, Any] | None = None, metadata_directory: str | None = None + self, wheel_directory: StrPath, config_settings: _ConfigSettings | None = None, metadata_directory: StrPath | None = None ) -> str: ... - def build_sdist(self, sdist_directory: StrPath, config_settings: Mapping[str, Any] | None = None) -> str: ... + def build_sdist(self, sdist_directory: StrPath, config_settings: _ConfigSettings | None = None) -> str: ... def build_editable( - self, wheel_directory: StrPath, config_settings: Mapping[str, Any] | None = None, metadata_directory: str | None = None + self, wheel_directory: StrPath, config_settings: _ConfigSettings | None = None, metadata_directory: str | None = None ) -> str: ... def get_requires_for_build_editable(self, config_settings: Mapping[str, Any] | None = None) -> list[str]: ... def prepare_metadata_for_build_editable( diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/bdist_egg.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/bdist_egg.pyi index aec617755..356df96c7 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/bdist_egg.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/bdist_egg.pyi @@ -1,6 +1,5 @@ from _typeshed import Incomplete from collections.abc import Generator -from typing import Literal from .. import Command @@ -14,9 +13,9 @@ class bdist_egg(Command): boolean_options: Incomplete bdist_dir: Incomplete plat_name: Incomplete - keep_temp: int + keep_temp: bool dist_dir: Incomplete - skip_build: int + skip_build: bool egg_output: Incomplete exclude_source_files: Incomplete def initialize_options(self) -> None: ... @@ -48,10 +47,5 @@ def can_scan(): ... INSTALL_DIRECTORY_ATTRS: Incomplete def make_zipfile( - zip_filename, - base_dir, - verbose: bool | Literal[0, 1] = 0, - dry_run: bool | Literal[0, 1] = 0, - compress: bool = True, - mode: str = "w", + zip_filename, base_dir, verbose: bool = False, dry_run: bool = False, compress: bool = True, mode: str = "w" ): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/bdist_wheel.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/bdist_wheel.pyi new file mode 100644 index 000000000..9f416a7c4 --- /dev/null +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/bdist_wheel.pyi @@ -0,0 +1,61 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable +from types import TracebackType +from typing import Any, ClassVar, Final, Literal + +from setuptools import Command + +def safe_name(name: str) -> str: ... +def safe_version(version: str) -> str: ... + +setuptools_major_version: Final[int] + +PY_LIMITED_API_PATTERN: Final[str] + +def python_tag() -> str: ... +def get_platform(archive_root: str | None) -> str: ... +def get_flag(var: str, fallback: bool, expected: bool = True, warn: bool = True) -> bool: ... +def get_abi_tag() -> str | None: ... +def safer_name(name: str) -> str: ... +def safer_version(version: str) -> str: ... +def remove_readonly( + func: Callable[..., object], path: str, excinfo: tuple[type[Exception], Exception, TracebackType] +) -> None: ... +def remove_readonly_exc(func: Callable[..., object], path: str, exc: Exception) -> None: ... + +class bdist_wheel(Command): + description: ClassVar[str] + supported_compressions: ClassVar[dict[str, int]] + user_options: ClassVar[list[tuple[Any, ...]]] + boolean_options: ClassVar[list[str]] + + bdist_dir: str | None + data_dir: Incomplete | None + plat_name: str | None + plat_tag: Incomplete | None + format: str + keep_temp: bool + dist_dir: str | None + egginfo_dir: Incomplete | None + root_is_pure: bool | None + skip_build: Incomplete | None + relative: bool + owner: Incomplete | None + group: Incomplete | None + universal: bool + compression: str | int + python_tag: str + build_number: str | None + py_limited_api: str | Literal[False] + plat_name_supplied: bool + + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + @property + def wheel_dist_name(self) -> str: ... + def get_tag(self) -> tuple[str, str, str]: ... + def run(self) -> None: ... + def write_wheelfile(self, wheelfile_base: str, generator: str = ...) -> None: ... + @property + def license_paths(self) -> Iterable[str]: ... + def egg2dist(self, egginfo_path: str, distinfo_path: str) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/build_ext.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/build_ext.pyi index 70f9c6c8f..584bfbbc2 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/build_ext.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/build_ext.pyi @@ -1,5 +1,5 @@ from _typeshed import Incomplete -from typing import Any, ClassVar, Literal +from typing import Any, ClassVar from .._distutils.command.build_ext import build_ext as _build_ext @@ -40,7 +40,7 @@ def link_shared_object( library_dirs: Incomplete | None = None, runtime_library_dirs: Incomplete | None = None, export_symbols: Incomplete | None = None, - debug: bool | Literal[0, 1] = 0, + debug: bool = False, extra_preargs: Incomplete | None = None, extra_postargs: Incomplete | None = None, build_temp: Incomplete | None = None, diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/build_py.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/build_py.pyi index 3bdce5ca6..ea6e94ea1 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/build_py.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/build_py.pyi @@ -1,6 +1,7 @@ -from _typeshed import Incomplete +from _typeshed import Incomplete, StrPath from typing import Any, ClassVar +from .._distutils.cmd import _StrPathT from .._distutils.command import build_py as orig def make_writable(target) -> None: ... @@ -10,12 +11,22 @@ class build_py(orig.build_py): package_data: Any exclude_package_data: Any def finalize_options(self) -> None: ... + def copy_file( # type: ignore[override] + self, + infile: StrPath, + outfile: _StrPathT, + preserve_mode: bool = True, + preserve_times: bool = True, + link: str | None = None, + level=1, + ) -> tuple[_StrPathT | str, bool]: ... def run(self) -> None: ... data_files: Any def __getattr__(self, attr: str): ... def build_module(self, module, module_file, package): ... def get_data_files_without_manifest(self) -> list[tuple[Incomplete, Incomplete, Incomplete, list[Incomplete]]]: ... def find_data_files(self, package, src_dir): ... + def get_outputs(self, include_bytecode: bool = True) -> list[str]: ... # type: ignore[override] def build_package_data(self) -> None: ... manifest_files: Any def get_output_mapping(self) -> dict[str, str]: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/easy_install.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/easy_install.pyi index cc3b8121a..9700eabb1 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/easy_install.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/easy_install.pyi @@ -16,7 +16,7 @@ class easy_install(Command): boolean_options: Incomplete negative_opt: Incomplete create_index: Incomplete - user: int + user: bool zip_ok: Incomplete install_dir: Incomplete index_url: Incomplete diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/egg_info.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/egg_info.pyi index 594159d8d..b5fba6b76 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/egg_info.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/egg_info.pyi @@ -59,10 +59,10 @@ class FileList(_FileList): class manifest_maker(sdist): template: str - use_defaults: int - prune: int - manifest_only: int - force_manifest: int + use_defaults: bool + prune: bool + manifest_only: bool + force_manifest: bool def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... filelist: Incomplete diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/install_lib.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/install_lib.pyi index b9c3e4fdb..79e3e59e0 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/install_lib.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/command/install_lib.pyi @@ -1,5 +1,4 @@ from _typeshed import StrPath, Unused -from typing import Literal from .._distutils.command import install_lib as orig @@ -10,9 +9,9 @@ class install_lib(orig.install_lib): self, infile: StrPath, outfile: str, - preserve_mode: bool | Literal[0, 1] = 1, - preserve_times: bool | Literal[0, 1] = 1, - preserve_symlinks: bool | Literal[0, 1] = 0, + preserve_mode: bool = True, # type: ignore[override] + preserve_times: bool = True, # type: ignore[override] + preserve_symlinks: bool = False, # type: ignore[override] level: Unused = 1, ): ... def get_outputs(self): ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/compat/py311.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/compat/py311.pyi index aef113fc9..a71f08223 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/compat/py311.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/compat/py311.pyi @@ -1,4 +1,4 @@ from _typeshed import StrOrBytesPath from shutil import _OnExcCallback -def shutil_rmtree(path: StrOrBytesPath, ignore_errors: bool = False, onexc: _OnExcCallback | None = None): ... +def shutil_rmtree(path: StrOrBytesPath, ignore_errors: bool = False, onexc: _OnExcCallback | None = None) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/config/expand.pyi b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/config/expand.pyi index 0b0ccf550..8695c8605 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/config/expand.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/setuptools/setuptools/config/expand.pyi @@ -7,7 +7,6 @@ from typing_extensions import Self from ..dist import Distribution -chain_iter: Incomplete _K = TypeVar("_K") _VCo = TypeVar("_VCo", covariant=True) diff --git a/packages/pyright-internal/typeshed-fallback/stubs/shapely/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/shapely/METADATA.toml index e12eb3f77..32d94d6e9 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/shapely/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/shapely/METADATA.toml @@ -1,4 +1,5 @@ version = "2.0.*" # Requires a version of numpy with a `py.typed` file -requires = ["numpy>=1.20"] +# TODO: stubtest errors when using numpy 2 +requires = ["numpy>=1.20,<2"] upstream_repository = "https://github.com/shapely/shapely" diff --git a/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/_geometry.pyi b/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/_geometry.pyi index 5f1833533..874dc42ab 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/_geometry.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/_geometry.pyi @@ -162,9 +162,9 @@ def get_precision(geometry: Geometry | None, **kwargs) -> float: ... def get_precision(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... class SetPrecisionMode(ParamEnum): - valid_output = 0 # noqa: Y052 - pointwise = 1 # noqa: Y052 - keep_collapsed = 2 # noqa: Y052 + valid_output = 0 + pointwise = 1 + keep_collapsed = 2 @overload def set_precision(geometry: OptGeoT, grid_size: float, mode: _PrecisionMode = "valid_output", **kwargs) -> OptGeoT: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/constructive.pyi b/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/constructive.pyi index 55ceab3c7..f022b0cd7 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/constructive.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/constructive.pyi @@ -39,14 +39,14 @@ __all__ = [ ] class BufferCapStyle(ParamEnum): - round = 1 # noqa: Y052 - flat = 2 # noqa: Y052 - square = 3 # noqa: Y052 + round = 1 + flat = 2 + square = 3 class BufferJoinStyle(ParamEnum): - round = 1 # noqa: Y052 - mitre = 2 # noqa: Y052 - bevel = 3 # noqa: Y052 + round = 1 + mitre = 2 + bevel = 3 @overload def boundary(geometry: Point | MultiPoint, **kwargs) -> GeometryCollection: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/geometry/base.pyi b/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/geometry/base.pyi index fe0da8aa5..ac8b1ca31 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/geometry/base.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/geometry/base.pyi @@ -1,7 +1,7 @@ from array import array from collections.abc import Iterator from typing import Any, Generic, Literal, NoReturn, overload -from typing_extensions import Self, TypeVar, deprecated # noqa: Y023 +from typing_extensions import Self, TypeVar, deprecated import numpy as np from numpy.typing import NDArray @@ -33,7 +33,7 @@ class JOIN_STYLE: class BaseGeometry(Geometry): @deprecated( "Directly calling 'BaseGeometry()' is deprecated. To create an empty geometry, " - "use one of the subclasses instead, for example 'GeometryCollection()'." # pyright: ignore[reportImplicitStringConcatenation] + "use one of the subclasses instead, for example 'GeometryCollection()'." ) def __new__(self) -> GeometryCollection: ... def __bool__(self) -> bool: ... @@ -280,6 +280,6 @@ class GeometrySequence(Generic[_P_co]): class EmptyGeometry(BaseGeometry): @deprecated( "The 'EmptyGeometry()' constructor is deprecated. Use one of the " - "geometry subclasses instead, for example 'GeometryCollection()'." # pyright: ignore[reportImplicitStringConcatenation] + "geometry subclasses instead, for example 'GeometryCollection()'." ) def __new__(self) -> GeometryCollection: ... # type: ignore[misc] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/io.pyi b/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/io.pyi index f7e1d2e85..27b667e53 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/io.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/io.pyi @@ -18,8 +18,8 @@ __all__ = ["from_geojson", "from_ragged_array", "from_wkb", "from_wkt", "to_geoj DecodingErrorOptions: Incomplete class WKBFlavorOptions(ParamEnum): - extended = 1 # noqa: Y052 - iso = 2 # noqa: Y052 + extended = 1 + iso = 2 @overload def to_wkt( diff --git a/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/strtree.pyi b/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/strtree.pyi index d43291c78..d85da2e73 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/strtree.pyi +++ b/packages/pyright-internal/typeshed-fallback/stubs/shapely/shapely/strtree.pyi @@ -15,15 +15,15 @@ _BinaryPredicate: TypeAlias = Literal[ ] class BinaryPredicate(ParamEnum): - intersects = 1 # noqa: Y052 - within = 2 # noqa: Y052 - contains = 3 # noqa: Y052 - overlaps = 4 # noqa: Y052 - crosses = 5 # noqa: Y052 - touches = 6 # noqa: Y052 - covers = 7 # noqa: Y052 - covered_by = 8 # noqa: Y052 - contains_properly = 9 # noqa: Y052 + intersects = 1 + within = 2 + contains = 3 + overlaps = 4 + crosses = 5 + touches = 6 + covers = 7 + covered_by = 8 + contains_properly = 9 class STRtree: def __init__(self, geoms: GeoArrayLikeSeq, node_capacity: SupportsIndex = 10) -> None: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter-languages/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter-languages/METADATA.toml index 3922f7af9..055b8d94d 100644 --- a/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter-languages/METADATA.toml +++ b/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter-languages/METADATA.toml @@ -1,3 +1,3 @@ version = "1.10.*" upstream_repository = "https://github.com/grantjenks/py-tree-sitter-languages" -requires = ["types-tree-sitter"] +requires = ["tree-sitter>=0.20.3"] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/METADATA.toml b/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/METADATA.toml deleted file mode 100644 index bfcd1317b..000000000 --- a/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/METADATA.toml +++ /dev/null @@ -1,7 +0,0 @@ -version = "0.20.1" -upstream_repository = "https://github.com/tree-sitter/py-tree-sitter" -obsolete_since = "0.20.3" # Released on 2023-11-13 - -[tool.stubtest] -# The runtime has an undeclared dependency on setuptools -stubtest_requirements = ["setuptools"] diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/tree_sitter/__init__.pyi b/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/tree_sitter/__init__.pyi deleted file mode 100644 index d26b17620..000000000 --- a/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/tree_sitter/__init__.pyi +++ /dev/null @@ -1,17 +0,0 @@ -import ctypes -from _typeshed import StrPath -from collections.abc import Sequence - -# At runtime, Query and Range are available only in tree_sitter.binding -from tree_sitter.binding import Node as Node, Parser as Parser, Query, Tree as Tree, TreeCursor as TreeCursor - -class Language: - @staticmethod - def build_library(output_path: str, repo_paths: Sequence[StrPath]) -> bool: ... - name: str - lib: ctypes.CDLL - language_id: int - # library_path is passed into ctypes LoadLibrary - def __init__(self, library_path: str, name: str) -> None: ... - def field_id_for_name(self, name: str) -> int | None: ... - def query(self, source: str) -> Query: ... diff --git a/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/tree_sitter/binding.pyi b/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/tree_sitter/binding.pyi deleted file mode 100644 index 5b07bfd55..000000000 --- a/packages/pyright-internal/typeshed-fallback/stubs/tree-sitter/tree_sitter/binding.pyi +++ /dev/null @@ -1,115 +0,0 @@ -from typing import Any, ClassVar, final - -from tree_sitter import Language - -@final -class Node: - @property - def start_byte(self) -> int: ... - @property - def start_point(self) -> tuple[int, int]: ... - @property - def end_byte(self) -> int: ... - @property - def end_point(self) -> tuple[int, int]: ... - @property - def has_changes(self) -> bool: ... - @property - def has_error(self) -> bool: ... - @property - def id(self) -> int: ... - @property - def is_missing(self) -> bool: ... - @property - def is_named(self) -> bool: ... - @property - def child_count(self) -> int: ... - @property - def named_child_count(self) -> bool: ... - @property - def children(self) -> list[Node]: ... - @property - def named_children(self) -> list[Node]: ... - @property - def next_named_sibling(self) -> Node | None: ... - @property - def next_sibling(self) -> Node | None: ... - @property - def parent(self) -> Node | None: ... - @property - def prev_named_sibling(self) -> Node | None: ... - @property - def prev_sibling(self) -> Node | None: ... - @property - def text(self) -> bytes | Any: ... # can be None, but annoying to check - @property - def type(self) -> str: ... - def children_by_field_name(self, name: str) -> list[Node]: ... - def children_by_field_id(self, id: int, /) -> list[Node]: ... - def field_name_for_child(self, child_index: int, /) -> str: ... - def child_by_field_id(self, id: int, /) -> Node | None: ... - def child_by_field_name(self, name: str, /) -> Node | None: ... - __hash__: ClassVar[None] # type: ignore[assignment] - def sexp(self) -> str: ... - def walk(self) -> TreeCursor: ... - def __eq__(self, other: object) -> bool: ... - def __ne__(self, other: object) -> bool: ... - # There are __ge__, __gt__, __le__, __lt__ methods but they always return False - # - # >>> n - # - # >>> n >= "", n <= "", n >= 0, n <= 0, n >= (0,0), n <= (0,0) - # (False, False, False, False, False, False) - -@final -class Parser: - # At runtime, Parser(1, 2, 3) ignores the arguments, but that's most likely buggy code - def __init__(self) -> None: ... - def parse(self, source: bytes, old_tree: Tree | None = None, keep_text: bool = True) -> Tree: ... - def set_language(self, language: Language, /) -> None: ... - -@final -class Query: - # start_point and end_point arguments don't seem to do anything - # TODO: sync with - # https://github.com/tree-sitter/py-tree-sitter/blob/d3016edac2c33ce647653d896fbfb435ac2a6245/tree_sitter/binding.c#L1304 - def captures(self, node: Node) -> list[tuple[Node, str]]: ... - -@final -class Range: - @property - def start_byte(self) -> int: ... - @property - def end_byte(self) -> int: ... - @property - def start_point(self) -> tuple[int, int]: ... - @property - def end_point(self) -> tuple[int, int]: ... - -@final -class Tree: - @property - def root_node(self) -> Node: ... - @property - def text(self) -> bytes | Any: ... # technically ReadableBuffer | Any - def edit( - self, - start_byte: int, - old_end_byte: int, - new_end_byte: int, - start_point: tuple[int, int], - old_end_point: tuple[int, int], - new_end_point: tuple[int, int], - ) -> None: ... - def get_changed_ranges(self, new_tree: Tree) -> list[Range]: ... - def walk(self) -> TreeCursor: ... - -@final -class TreeCursor: - @property - def node(self) -> Node: ... - def copy(self) -> TreeCursor: ... - def current_field_name(self) -> str | None: ... - def goto_first_child(self) -> bool: ... - def goto_next_sibling(self) -> bool: ... - def goto_parent(self) -> bool: ...