| -- Tests for error codes and ignoring errors using error codes | |
| -- | |
| -- These implicitly use --show-error-codes. | |
| [case testErrorCodeNoAttribute] | |
| import m | |
| m.x # E: Module has no attribute "x" [attr-defined] | |
| 'x'.foobar # E: "str" has no attribute "foobar" [attr-defined] | |
| from m import xx # E: Module "m" has no attribute "xx" [attr-defined] | |
| from m import think # E: Module "m" has no attribute "think"; maybe "thing"? [attr-defined] | |
| for x in 1: # E: "int" has no attribute "__iter__" (not iterable) [attr-defined] | |
| pass | |
| [file m.py] | |
| thing = 0 | |
| [builtins fixtures/module.pyi] | |
| [case testErrorCodeUndefinedName] | |
| x # E: Name "x" is not defined [name-defined] | |
| def f() -> None: | |
| y # E: Name "y" is not defined [name-defined] | |
| [file m.py] | |
| [builtins fixtures/module.pyi] | |
| [case testErrorCodeUndefinedNameSuggestion] | |
| my_variable = 42 | |
| my_constant = 100 | |
| x = my_variabel # E: Name "my_variabel" is not defined; did you mean "my_variable"? [name-defined] | |
| def calculate_sum(items: int) -> int: | |
| return items | |
| calculate_summ(1) # E: Name "calculate_summ" is not defined; did you mean "calculate_sum"? [name-defined] | |
| class MyClass: | |
| pass | |
| y = MyClas() # E: Name "MyClas" is not defined; did you mean "MyClass"? [name-defined] | |
| unknown_xyz # E: Name "unknown_xyz" is not defined [name-defined] | |
| [builtins fixtures/module.pyi] | |
| [case testErrorCodeUndefinedNameSuggestionLocal] | |
| def foo() -> None: | |
| local_value = 10 | |
| x = local_valeu # E: Name "local_valeu" is not defined; did you mean "local_value"? [name-defined] | |
| [builtins fixtures/module.pyi] | |
| [case testErrorCodeUndefinedNameSuggestionOuterScope] | |
| top_level_var = 42 | |
| def foo() -> None: | |
| x = top_level_vr # E: Name "top_level_vr" is not defined; did you mean "top_level_var"? [name-defined] | |
| [builtins fixtures/module.pyi] | |
| [case testErrorCodeUndefinedNameSuggestionClassBody] | |
| class Foo: | |
| class_attr = 10 | |
| x = class_atr # E: Name "class_atr" is not defined; did you mean "class_attr"? [name-defined] | |
| [builtins fixtures/module.pyi] | |
| [case testErrorCodeUndefinedNameSuggestionFromImport] | |
| from m import some_function | |
| some_functon(1) # E: Name "some_functon" is not defined; did you mean "some_function"? [name-defined] | |
| [file m.py] | |
| def some_function(x: int) -> int: | |
| return x | |
| [builtins fixtures/module.pyi] | |
| [case testErrorCodeUndefinedNameSuggestionBuiltin] | |
| x = lenn # E: Name "lenn" is not defined; did you mean "len"? [name-defined] | |
| [builtins fixtures/len.pyi] | |
| [case testErrorCodeUndefinedNameSuggestionClassMethod] | |
| class Foo: | |
| class_attr = 10 | |
| def method(self) -> None: | |
| x = class_atr # E: Name "class_atr" is not defined [name-defined] | |
| [builtins fixtures/module.pyi] | |
| [case testErrorCodeUndefinedNameSuggestionMultiple] | |
| total_count = 1 | |
| total_counts = 2 | |
| x = total_countt # E: Name "total_countt" is not defined; did you mean "total_count" or "total_counts"? [name-defined] | |
| [builtins fixtures/module.pyi] | |
| [case testErrorCodeUndefinedNameSuggestionIgnored] | |
| my_variable = 42 | |
| x = my_variabel # type: ignore[name-defined] | |
| y = my_variabel # type: ignore | |
| [builtins fixtures/module.pyi] | |
| [case testErrorCodeUnclassifiedError] | |
| class A: | |
| def __init__(self) -> int: \ | |
| # E: The return type of "__init__" must be None [misc] | |
| pass | |
| [case testErrorCodeNoteHasNoCode] | |
| reveal_type(1) # N: Revealed type is "Literal[1]?" | |
| [case testErrorCodeSyntaxError] | |
| 1 '' | |
| [out] | |
| main:1: error: Simple statements must be separated by newlines or semicolons [syntax] | |
| [case testErrorCodeSyntaxError2] | |
| def f(): # E: Type signature has too many parameters [syntax] | |
| # type: (int) -> None | |
| 1 | |
| x = 0 # type: x y # E: Syntax error in type comment "x y" [syntax] \ | |
| # E: Invalid type comment or annotation [valid-type] | |
| [case testErrorCodeSyntaxError3_old_parser] | |
| # This is a bit inconsistent -- syntax error would be more logical? | |
| x: 'a b' # E: Invalid type comment or annotation [valid-type] | |
| for v in x: # type: int, int # E: Syntax error in type annotation [syntax] \ | |
| # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn) | |
| pass | |
| [case testErrorCodeSyntaxError4] | |
| x = 1 # type: int, int # E: Syntax error in type annotation [syntax] \ | |
| # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn) | |
| [case testErrorCodeSyntaxErrorIgnoreNote] | |
| # This is a bit inconsistent -- syntax error would be more logical? | |
| x: 'a b' # type: ignore[valid-type] | |
| y = 1 # type: int, int # type: ignore[syntax] | |
| [case testErrorCodeIgnore1] | |
| 'x'.foobar # type: ignore[attr-defined] | |
| 'x'.foobar # type: ignore[xyz] # E: "str" has no attribute "foobar" [attr-defined] \ | |
| # N: Error code "attr-defined" not covered by "type: ignore[xyz]" comment | |
| 'x'.foobar # type: ignore | |
| [case testErrorCodeIgnore2] | |
| a = 'x'.foobar # type: int # type: ignore[attr-defined] | |
| b = 'x'.foobar # type: int # type: ignore[xyz] # E: "str" has no attribute "foobar" [attr-defined] \ | |
| # N: Error code "attr-defined" not covered by "type: ignore[xyz]" comment | |
| c = 'x'.foobar # type: int # type: ignore | |
| [case testErrorCodeIgnoreMultiple1] | |
| a = 'x'.foobar(b) # type: ignore[name-defined, attr-defined] | |
| a = 'x'.foobar(b) # type: ignore[name-defined, xyz] # E: "str" has no attribute "foobar" [attr-defined] \ | |
| # N: Error code "attr-defined" not covered by "type: ignore[name-defined, xyz]" comment | |
| a = 'x'.foobar(b) # type: ignore[xyz, w, attr-defined] # E: Name "b" is not defined [name-defined] \ | |
| # N: Error code "name-defined" not covered by "type: ignore[xyz, w, attr-defined]" comment | |
| a = 'x'.foobar(b) # type: ignore[ w, xyz, attr-defined] # E: Name "b" is not defined [name-defined] \ | |
| # N: Error code "name-defined" not covered by "type: ignore[w, xyz, attr-defined]" comment | |
| [case testErrorCodeIgnoreMultiple2] | |
| a = 'x'.foobar(c) # type: int # type: ignore[name-defined, attr-defined] | |
| b = 'x'.foobar(c) # type: int # type: ignore[name-defined, xyz] # E: "str" has no attribute "foobar" [attr-defined] \ | |
| # N: Error code "attr-defined" not covered by "type: ignore[name-defined, xyz]" comment | |
| [case testErrorCodeWarnUnusedIgnores1] | |
| # flags: --warn-unused-ignores | |
| x # type: ignore[name-defined, attr-defined] # E: Unused "type: ignore[attr-defined]" comment [unused-ignore] | |
| [case testErrorCodeWarnUnusedIgnores2] | |
| # flags: --warn-unused-ignores | |
| "x".foobar(y) # type: ignore[name-defined, attr-defined] | |
| [case testErrorCodeWarnUnusedIgnores3] | |
| # flags: --warn-unused-ignores | |
| "x".foobar(y) # type: ignore[name-defined, attr-defined, xyz] | |
| [case testErrorCodeWarnUnusedIgnores4] | |
| # flags: --warn-unused-ignores | |
| "x".foobar(y) # type: ignore[name-defined, attr-defined, valid-type] # E: Unused "type: ignore[valid-type]" comment [unused-ignore] | |
| [case testErrorCodeWarnUnusedIgnores5] | |
| # flags: --warn-unused-ignores | |
| "x".foobar(y) # type: ignore[name-defined, attr-defined, valid-type, xyz] # E: Unused "type: ignore[valid-type]" comment [unused-ignore] | |
| [case testErrorCodeWarnUnusedIgnores6_NoDetailWhenSingleErrorCode] | |
| # flags: --warn-unused-ignores | |
| "x" # type: ignore[name-defined] # E: Unused "type: ignore" comment [unused-ignore] | |
| [case testErrorCodeWarnUnusedIgnores7_WarnWhenErrorCodeDisabled] | |
| # flags: --warn-unused-ignores --disable-error-code name-defined | |
| x # type: ignore # E: Unused "type: ignore" comment [unused-ignore] | |
| x # type: ignore[name-defined] # E: Unused "type: ignore" comment [unused-ignore] | |
| "x".foobar(y) # type: ignore[name-defined, attr-defined] # E: Unused "type: ignore[name-defined]" comment [unused-ignore] | |
| [case testErrorCodeWarnUnusedIgnores8_IgnoreUnusedIgnore] | |
| # flags: --warn-unused-ignores --disable-error-code name-defined | |
| "x" # type: ignore[unused-ignore] | |
| "x" # type: ignore[name-defined, unused-ignore] | |
| "x" # type: ignore[xyz, unused-ignore] | |
| x # type: ignore[name-defined, unused-ignore] | |
| [case testErrorCodeWarnUnusedIgnores9_SloppyFormattingNotEmptyBrackets] | |
| # flags: --warn-unused-ignores | |
| 1 + "ok" + "ok".foo # type: ignore[ operator,attr-defined] | |
| 1 + "ok" + "ok".foo # type: ignore[ ,operator,attr-defined] | |
| 1 + "ok" + "ok".foo # type: ignore[ operator,attr-defined,] | |
| 1 + "ok" + "ok".foo # type: ignore[ operator,attr-defined,,] | |
| [case testErrorCodeWarnUnusedIgnores10_SloppyFormattingEmptyBrackets] | |
| # flags: --warn-unused-ignores | |
| 1+1 # type: ignore # E: Unused "type: ignore" comment [unused-ignore] | |
| 1+1 # type: ignore[] # E: Unused "type: ignore" comment [unused-ignore] | |
| 1+1 # type: ignore[ ] # E: Unused "type: ignore" comment [unused-ignore] | |
| 1+1 # type: ignore[,,, ] # E: Unused "type: ignore" comment [unused-ignore] | |
| [case testErrorCodeMissingWhenRequired] | |
| # flags: --enable-error-code ignore-without-code | |
| "x" # type: ignore # E: "type: ignore" comment without error code [ignore-without-code] | |
| y # type: ignore # E: "type: ignore" comment without error code (consider "type: ignore[name-defined]" instead) [ignore-without-code] | |
| z # type: ignore[name-defined] | |
| "a" # type: ignore[ignore-without-code] | |
| [case testErrorCodeMissingDoesntTrampleUnusedIgnoresWarning] | |
| # flags: --enable-error-code ignore-without-code --warn-unused-ignores | |
| "x" # type: ignore # E: Unused "type: ignore" comment [unused-ignore] | |
| "y" # type: ignore[ignore-without-code] # E: Unused "type: ignore" comment [unused-ignore] | |
| z # type: ignore[ignore-without-code] # E: Unused "type: ignore" comment [unused-ignore] \ | |
| # E: Name "z" is not defined [name-defined] \ | |
| # N: Error code "name-defined" not covered by "type: ignore[ignore-without-code]" comment | |
| [case testErrorCodeMissingWholeFileIgnores] | |
| # flags: --enable-error-code ignore-without-code | |
| # type: ignore # whole file ignore | |
| x | |
| y # type: ignore # ignore the lack of error code since we ignore the whole file | |
| [case testErrorCodeMissingMultiple] | |
| # flags: --enable-error-code ignore-without-code | |
| from __future__ import annotations | |
| class A: | |
| attr: int | |
| def func(self, var: int) -> A | None: ... | |
| a: A | None | |
| # 'union-attr' should only be listed once (instead of twice) and list should be sorted | |
| a.func("invalid string").attr # type: ignore # E: "type: ignore" comment without error code (consider "type: ignore[arg-type, union-attr]" instead) [ignore-without-code] | |
| [builtins fixtures/tuple.pyi] | |
| [case testErrorCodeIgnoreWithExtraSpace] | |
| x # type: ignore [name-defined] | |
| x2 # type: ignore [ name-defined ] | |
| x3 # type: ignore [ xyz , name-defined ] | |
| x4 # type: ignore[xyz,name-defined] | |
| y # type: ignore [xyz] # E: Name "y" is not defined [name-defined] \ | |
| # N: Error code "name-defined" not covered by "type: ignore[xyz]" comment | |
| y # type: ignore[ xyz ] # E: Name "y" is not defined [name-defined] \ | |
| # N: Error code "name-defined" not covered by "type: ignore[xyz]" comment | |
| y # type: ignore[ xyz , foo ] # E: Name "y" is not defined [name-defined] \ | |
| # N: Error code "name-defined" not covered by "type: ignore[xyz, foo]" comment | |
| a = z # type: int # type: ignore [name-defined] | |
| b = z2 # type: int # type: ignore [ name-defined ] | |
| c = z2 # type: int # type: ignore [ name-defined , xyz ] | |
| d = zz # type: int # type: ignore [xyz] # E: Name "zz" is not defined [name-defined] \ | |
| # N: Error code "name-defined" not covered by "type: ignore[xyz]" comment | |
| e = zz # type: int # type: ignore [ xyz ] # E: Name "zz" is not defined [name-defined] \ | |
| # N: Error code "name-defined" not covered by "type: ignore[xyz]" comment | |
| f = zz # type: int # type: ignore [ xyz,foo ] # E: Name "zz" is not defined [name-defined] \ | |
| # N: Error code "name-defined" not covered by "type: ignore[xyz, foo]" comment | |
| [case testErrorCodeIgnoreAfterArgComment] | |
| def f(x # type: xyz # type: ignore[name-defined] # Comment | |
| ): | |
| # type () -> None | |
| pass | |
| def g(x # type: xyz # type: ignore # Comment | |
| ): | |
| # type () -> None | |
| pass | |
| def h(x # type: xyz # type: ignore[foo] # E: Name "xyz" is not defined [name-defined] \ | |
| # N: Error code "name-defined" not covered by "type: ignore[foo]" comment | |
| ): | |
| # type () -> None | |
| pass | |
| [case testErrorCodeIgnoreWithNote] | |
| import nostub # type: ignore[import] | |
| from defusedxml import xyz # type: ignore[import] | |
| [case testErrorCodeBadIgnore] | |
| import nostub # type: ignore xyz # E: Cannot find implementation or library stub for module named "nostub" [import-not-found] \ | |
| # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports \ | |
| # E: Invalid "type: ignore" comment [syntax] | |
| import nostub # type: ignore[ # E: Invalid "type: ignore" comment [syntax] | |
| import nostub # type: ignore[foo # E: Invalid "type: ignore" comment [syntax] | |
| import nostub # type: ignore[foo, # E: Invalid "type: ignore" comment [syntax] | |
| import nostub # type: ignore[foo]] # E: Invalid "type: ignore" comment [syntax] | |
| import nostub # type: ignore[foo][bar] # E: Invalid "type: ignore" comment [syntax] | |
| import nostub # type: ignore[foo] [bar] # E: Invalid "type: ignore" comment [syntax] | |
| x = 0 # type: ignore[ # E: Invalid "type: ignore" comment [syntax] | |
| def f(x, # type: int # type: ignore[ # E: Invalid "type: ignore" comment [syntax] | |
| ): | |
| # type: (...) -> None | |
| pass | |
| [case testErrorCodeBadIgnoreNoExtraComment] | |
| # Omit the E: ... comments, as they affect parsing | |
| import nostub # type: ignore xyz | |
| import nostub # type: ignore[xyz | |
| import nostub # type: ignore[xyz][xyz] | |
| x = 0 # type: ignore[ | |
| def f(x, # type: int # type: ignore[ | |
| ): | |
| # type: (...) -> None | |
| pass | |
| [out] | |
| main:2: error: Cannot find implementation or library stub for module named "nostub" [import-not-found] | |
| main:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports | |
| main:2: error: Invalid "type: ignore" comment [syntax] | |
| main:3: error: Invalid "type: ignore" comment [syntax] | |
| main:4: error: Invalid "type: ignore" comment [syntax] | |
| main:5: error: Invalid "type: ignore" comment [syntax] | |
| main:6: error: Invalid "type: ignore" comment [syntax] | |
| [case testErrorCodeArgKindAndCount] | |
| def f(x: int) -> None: pass | |
| f() # E: Missing positional argument "x" in call to "f" [call-arg] | |
| f(1, 2) # E: Too many arguments for "f" [call-arg] | |
| f(y=1) # E: Unexpected keyword argument "y" for "f" [call-arg] | |
| def g(*, x: int) -> None: pass | |
| g() # E: Missing named argument "x" for "g" [call-arg] | |
| def h(x: int, y: int, z: int) -> None: pass | |
| h(y=1, z=1) # E: Missing positional argument "x" in call to "h" [call-arg] | |
| h(y=1) # E: Missing positional arguments "x", "z" in call to "h" [call-arg] | |
| [case testTooManyPositionalArgumentsErrorCode] | |
| def f(a: int, *, b: int) -> None: pass | |
| f(1, 2) # E: Too many positional arguments for "f" [call-arg] | |
| f(1, 2) # type: ignore[call-arg] | |
| f(1, 2) # type: ignore[misc] | |
| [case testTooManyPositionalArgumentsCoveredByMiscUnused] | |
| # flags: --warn-unused-ignores | |
| def f(a: int, *, b: int) -> None: pass | |
| f(1, 2) # type: ignore[misc] # E: Unused "type: ignore" comment, use narrower [call-arg] instead of [misc] code [unused-ignore] | |
| [case testErrorCodeArgType] | |
| def f(x: int) -> None: pass | |
| f('') # E: Argument 1 to "f" has incompatible type "str"; expected "int" [arg-type] | |
| class A: | |
| def g(self, *, x: int) -> None: pass | |
| A().g(x='') # E: Argument "x" to "g" of "A" has incompatible type "str"; expected "int" [arg-type] | |
| [case testErrorCodeInvalidType] | |
| def f(): pass | |
| x: f # E: Function "__main__.f" is not valid as a type [valid-type] \ | |
| # N: Perhaps you need "Callable[...]" or a callback protocol? | |
| import sys | |
| y: sys # E: Module "sys" is not valid as a type [valid-type] \ | |
| # N: Perhaps you meant to use a protocol matching the module structure? | |
| z: y # E: Variable "__main__.y" is not valid as a type [valid-type] \ | |
| # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases | |
| [builtins fixtures/tuple.pyi] | |
| [case testErrorCodeNeedTypeAnnotation] | |
| from typing import TypeVar | |
| T = TypeVar('T') | |
| def f() -> T: pass # E: A function returning TypeVar should receive at least one argument containing the same TypeVar [type-var] | |
| x = f() # E: Need type annotation for "x" [var-annotated] | |
| y = [] # E: Need type annotation for "y" (hint: "y: list[<type>] = ...") [var-annotated] | |
| [builtins fixtures/list.pyi] | |
| [case testErrorCodeBadOverride] | |
| from typing import overload | |
| class A: | |
| def f(self) -> int: | |
| return 0 | |
| class B(A): | |
| def f(self) -> str: # E: Return type "str" of "f" incompatible with return type "int" in supertype "A" [override] | |
| return '' | |
| class C(A): | |
| def f(self, x: int) -> int: # E: Signature of "f" incompatible with supertype "A" [override] \ | |
| # N: Superclass: \ | |
| # N: def f(self) -> int \ | |
| # N: Subclass: \ | |
| # N: def f(self, x: int) -> int | |
| return 0 | |
| class D: | |
| def f(self, x: int) -> int: | |
| return 0 | |
| class E(D): | |
| def f(self, x: str) -> int: # E: Argument 1 of "f" is incompatible with supertype "D"; supertype defines the argument type as "int" [override] \ | |
| # N: This violates the Liskov substitution principle \ | |
| # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides | |
| return 0 | |
| class O: | |
| @overload | |
| def f(self, x: int) -> None: pass | |
| @overload | |
| def f(self, x: str) -> None: pass | |
| def f(self, x): | |
| pass | |
| class OO(O): | |
| @overload # E: Signature of "f" incompatible with supertype "O" [override] \ | |
| # N: Overload variants must be defined in the same order as they are in "O" | |
| def f(self, x: str) -> None: pass | |
| @overload | |
| def f(self, x: int) -> None: pass | |
| def f(self, x): | |
| pass | |
| [case testErrorCodeReturnValue] | |
| def f() -> int: | |
| return '' # E: Incompatible return value type (got "str", expected "int") [return-value] | |
| [case testErrorCodeMissingReturnValueInReturnStatement] | |
| def f() -> int: | |
| return # E: Return value expected [return-value] | |
| [case testErrorCodeAssignment] | |
| x: str = 0 # E: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment] | |
| def f(x: str = 0) -> None: # E: Incompatible default for parameter "x" (default has type "int", parameter has type "str") [assignment] | |
| pass | |
| class A: | |
| x = 0 | |
| class B(A): | |
| x = '' # E: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "int") [assignment] | |
| a: A | |
| a.x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment] | |
| [case testErrorCodeMissingTypeArg] | |
| # flags: --disallow-any-generics | |
| from typing import List, TypeVar | |
| x: List # E: Missing type arguments for generic type "List" [type-arg] | |
| y: list # E: Missing type arguments for generic type "list" [type-arg] | |
| T = TypeVar('T') | |
| L = List[List[T]] | |
| z: L # E: Missing type arguments for generic type "L" [type-arg] | |
| [builtins fixtures/list.pyi] | |
| [case testErrorCodeUnionAttribute] | |
| from typing import Union | |
| class A: | |
| x: int | |
| class B: | |
| y: str | |
| a: Union[A, B] | |
| a.x # E: Item "B" of "A | B" has no attribute "x" [union-attr] | |
| [case testErrorCodeFunctionHasNoAnnotation] | |
| # flags: --disallow-untyped-defs | |
| def f(x): # E: Function is missing a type annotation [no-untyped-def] | |
| pass | |
| def g(x: int): # E: Function is missing a return type annotation [no-untyped-def] | |
| pass | |
| def h(x) -> None: # E: Function is missing a type annotation for one or more parameters [no-untyped-def] | |
| pass | |
| def gen(): # E: Function is missing a return type annotation [no-untyped-def] | |
| yield 1 | |
| def gen2(x: int): # E: Function is missing a return type annotation [no-untyped-def] | |
| yield 1 | |
| async def asyncf(): # E: Function is missing a return type annotation [no-untyped-def] | |
| return 0 | |
| async def asyncf2(x: int): # E: Function is missing a return type annotation [no-untyped-def] | |
| return 0 | |
| [typing fixtures/typing-async.pyi] | |
| [builtins fixtures/tuple.pyi] | |
| [case testErrorCodeCallUntypedFunction] | |
| # flags: --disallow-untyped-calls | |
| def f() -> None: | |
| g() # E: Call to untyped function "g" in typed context [no-untyped-call] | |
| def g(): | |
| pass | |
| [case testErrorCodeUntypedDecorator] | |
| # flags: --disallow-untyped-decorators --warn-unused-ignores | |
| def d(f): return f | |
| @d # E: Untyped decorator makes function "x" untyped [untyped-decorator] | |
| def x() -> int: return 1 | |
| @d # type: ignore | |
| def y() -> int: return 2 | |
| @d # type: ignore[untyped-decorator] | |
| def best() -> int: return 3 | |
| @d # type: ignore[misc] # E: Unused "type: ignore" comment [unused-ignore] \ | |
| # E: Untyped decorator makes function "z" untyped [untyped-decorator] \ | |
| # N: Error code "untyped-decorator" not covered by "type: ignore[misc]" comment | |
| def z() -> int: return 4 | |
| [case testErrorCodeIndexing] | |
| from typing import Dict | |
| x: Dict[int, int] | |
| x[''] # E: Invalid index type "str" for "dict[int, int]"; expected type "int" [index] | |
| 1[''] # E: Value of type "int" is not indexable [index] | |
| 1[''] = 1 # E: Unsupported target for indexed assignment ("int") [index] | |
| [builtins fixtures/dict.pyi] | |
| [case testErrorCodeInvalidTypeArg] | |
| from typing import TypeVar, Generic | |
| T = TypeVar('T', int, str) | |
| TT = TypeVar('TT', int, None) | |
| S = TypeVar('S', bound=str) | |
| def f(x: T) -> T: | |
| return x | |
| f(object()) # E: Value of type variable "T" of "f" cannot be "object" [type-var] | |
| def g(x: S) -> S: | |
| return x | |
| g(1) # E: Value of type variable "S" of "g" cannot be "int" [type-var] | |
| class C(Generic[T]): pass | |
| class D(Generic[S]): pass | |
| class E(Generic[S, T]): pass | |
| x: C[object] # E: Value of type variable "T" of "C" cannot be "object" [type-var] | |
| y: D[int] # E: Type argument "int" of "D" must be a subtype of "str" [type-var] | |
| z: D[int, int] # E: "D" expects 1 type argument, but 2 given [type-arg] | |
| def h(a: TT, s: S) -> None: | |
| b: C[TT] # E: Invalid type argument value for "C" [type-var] | |
| c: C[S] # E: Type variable "S" not valid as type argument value for "C" [type-var] | |
| [case testErrorCodeOperators] | |
| class A: pass | |
| A() + 1 # E: Unsupported left operand type for + ("A") [operator] | |
| 1 in A() # E: Unsupported right operand type for in ("A") [operator] | |
| A() < 1 # E: Unsupported left operand type for < ("A") [operator] | |
| -A() # E: Unsupported operand type for unary - ("A") [operator] | |
| +A() # E: Unsupported operand type for unary + ("A") [operator] | |
| ~A() # E: Unsupported operand type for ~ ("A") [operator] | |
| class B: | |
| def __add__(self, other: int) -> 'B': | |
| return self | |
| def __radd__(self, other: int) -> 'B': | |
| return self | |
| def __contains__(self, other: int) -> int: | |
| return 0 | |
| B() + '' # E: Unsupported operand types for + ("B" and "str") [operator] | |
| '' + B() # E: Unsupported operand types for + ("str" and "B") [operator] | |
| '' in B() # E: Unsupported operand types for in ("str" and "B") [operator] | |
| 1() # E: "int" not callable [operator] | |
| [builtins fixtures/tuple.pyi] | |
| [case testErrorCodeListOrDictItem] | |
| from typing import List, Dict | |
| x: List[int] = [''] # E: List item 0 has incompatible type "str"; expected "int" [list-item] | |
| y: Dict[int, int] = {1: ''} # E: Dict entry 0 has incompatible type "int": "str"; expected "int": "int" [dict-item] | |
| [builtins fixtures/dict.pyi] | |
| [case testErrorCodeTypedDict] | |
| from typing import TypedDict | |
| class D(TypedDict): | |
| x: int | |
| class E(TypedDict): | |
| x: int | |
| y: int | |
| a: D = {'x': ''} # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") [typeddict-item] | |
| b: D = {'y': ''} # E: Missing key "x" for TypedDict "D" [typeddict-item] \ | |
| # E: Extra key "y" for TypedDict "D" [typeddict-unknown-key] | |
| c = D(x=0) if int() else E(x=0, y=0) | |
| c = {} # E: Missing key "x" for TypedDict "D" [typeddict-item] | |
| d: D = {'x': '', 'y': 1} # E: Extra key "y" for TypedDict "D" [typeddict-unknown-key] \ | |
| # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") [typeddict-item] | |
| a['y'] = 1 # E: TypedDict "D" has no key "y" [typeddict-unknown-key] | |
| a['x'] = 'x' # E: Value of "x" has incompatible type "str"; expected "int" [typeddict-item] | |
| a['y'] # E: TypedDict "D" has no key "y" [typeddict-item] | |
| [builtins fixtures/dict.pyi] | |
| [typing fixtures/typing-typeddict.pyi] | |
| [case testErrorCodeTypedDictNoteIgnore] | |
| from typing import TypedDict | |
| class A(TypedDict): | |
| one_commonpart: int | |
| two_commonparts: int | |
| a: A = {'one_commonpart': 1, 'two_commonparts': 2} | |
| a['other_commonpart'] = 3 # type: ignore[typeddict-unknown-key] | |
| not_exist = a['not_exist'] # type: ignore[typeddict-item] | |
| [builtins fixtures/dict.pyi] | |
| [typing fixtures/typing-typeddict.pyi] | |
| [case testErrorCodeTypedDictSubCodeIgnore] | |
| from typing import TypedDict | |
| class D(TypedDict): | |
| x: int | |
| d: D = {'x': 1, 'y': 2} # type: ignore[typeddict-item] | |
| [builtins fixtures/dict.pyi] | |
| [typing fixtures/typing-typeddict.pyi] | |
| [case testErrorCodeCannotDetermineType] | |
| y = x # E: Cannot determine type of "x" [has-type] \ | |
| # E: Name "x" is used before definition [used-before-def] | |
| reveal_type(y) # N: Revealed type is "Any" | |
| x = None | |
| [case testErrorCodeRedundantCast] | |
| # flags: --warn-redundant-casts | |
| from typing import cast | |
| x = cast(int, int()) # E: Redundant cast to "int" [redundant-cast] | |
| [case testErrorCodeInvalidCommentSignature] | |
| def f(x): # E: Type signature has too few parameters [syntax] | |
| # type: () -> None | |
| pass | |
| def g(x): # E: Type signature has too many parameters [syntax] | |
| # type: (int, int) -> None | |
| pass | |
| [case testErrorCodeNonOverlappingEquality] | |
| # flags: --strict-equality | |
| if int() == str(): # E: Non-overlapping equality check (left operand type: "int", right operand type: "str") [comparison-overlap] | |
| pass | |
| if int() != str(): # E: Non-overlapping equality check (left operand type: "int", right operand type: "str") [comparison-overlap] | |
| pass | |
| if int() is str(): # E: Non-overlapping identity check (left operand type: "int", right operand type: "str") [comparison-overlap] | |
| pass | |
| [builtins fixtures/primitives.pyi] | |
| [case testErrorCodeMissingModule] | |
| from defusedxml import xyz # E: Library stubs not installed for "defusedxml" [import-untyped] \ | |
| # N: Hint: "python3 -m pip install types-defusedxml" \ | |
| # N: (or run "mypy --install-types" to install all missing stub packages) | |
| from nonexistent import foobar # E: Cannot find implementation or library stub for module named "nonexistent" [import-not-found] | |
| import nonexistent2 # E: Cannot find implementation or library stub for module named "nonexistent2" [import-not-found] | |
| from nonexistent3 import * # E: Cannot find implementation or library stub for module named "nonexistent3" [import-not-found] | |
| from pkg import bad # E: Module "pkg" has no attribute "bad" [attr-defined] | |
| from pkg.bad2 import bad3 # E: Cannot find implementation or library stub for module named "pkg.bad2" [import-not-found] \ | |
| # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports | |
| [file pkg/__init__.py] | |
| [case testErrorCodeAlreadyDefined] | |
| x: int | |
| x: str # E: Name "x" already defined on line 1 [no-redef] | |
| def f(): | |
| pass | |
| def f(): # E: Name "f" already defined on line 4 [no-redef] | |
| pass | |
| [case testErrorCodeMissingReturn] | |
| def f() -> int: # E: Missing return statement [return] | |
| x = 0 | |
| [case testErrorCodeReturnValueNotExpected] | |
| def f() -> None: | |
| return 1 # E: No return value expected [return-value] | |
| [case testErrorCodeFunctionDoesNotReturnValue] | |
| from typing import Callable | |
| def f() -> None: pass | |
| class A: | |
| def g(self) -> None: pass | |
| c: Callable[[], None] | |
| def main() -> None: | |
| x = f() # E: "f" does not return a value (it only ever returns None) [func-returns-value] | |
| y = A().g() # E: "g" of "A" does not return a value (it only ever returns None) [func-returns-value] | |
| z = c() # E: Function does not return a value (it only ever returns None) [func-returns-value] | |
| [case testErrorCodeInstantiateAbstract] | |
| from abc import abstractmethod | |
| class A: | |
| @abstractmethod | |
| def f(self): pass | |
| class B(A): | |
| pass | |
| B() # E: Cannot instantiate abstract class "B" with abstract attribute "f" [abstract] | |
| [case testErrorCodeNewTypeNotSubclassable] | |
| from typing import Union, NewType | |
| X = NewType('X', Union[int, str]) # E: Argument 2 to NewType(...) must be subclassable (got "int | str") [valid-newtype] | |
| [case testErrorCodeOverloadVariant] | |
| from typing import overload | |
| @overload | |
| def f(x: int) -> int: ... | |
| @overload | |
| def f(x: str) -> str: ... | |
| def f(x): | |
| return x | |
| f(object()) # E: No overload variant of "f" matches argument type "object" [call-overload] \ | |
| # N: Possible overload variants: \ | |
| # N: def f(x: int) -> int \ | |
| # N: def f(x: str) -> str | |
| f() # E: All overload variants of "f" require at least one argument [call-overload] \ | |
| # N: Possible overload variants: \ | |
| # N: def f(x: int) -> int \ | |
| # N: def f(x: str) -> str | |
| f(1, 1) # E: No overload variant of "f" matches argument types "int", "int" [call-overload] \ | |
| # N: Possible overload variants: \ | |
| # N: def f(x: int) -> int \ | |
| # N: def f(x: str) -> str | |
| [case testErrorCodeOverloadVariantIgnore] | |
| from typing import overload | |
| @overload | |
| def f(x: int) -> int: ... | |
| @overload | |
| def f(x: str) -> str: ... | |
| def f(x): | |
| return x | |
| f(object()) # type: ignore[call-overload] | |
| [case testErrorCodeAnyFromUnfollowedImport] | |
| # flags: --disallow-any-unimported | |
| from m import C # type: ignore | |
| def f(x: C) -> None: # E: Argument 1 to "f" becomes "Any" due to an unfollowed import [no-any-unimported] | |
| pass | |
| def g() -> C: ... # E: Return type becomes "Any" due to an unfollowed import [no-any-unimported] | |
| [case testErrorCodeReturnAny] | |
| # flags: --warn-return-any | |
| def f(): pass | |
| def g() -> int: | |
| return f() # E: Returning Any from function declared to return "int" [no-any-return] | |
| [case testErrorCodeFormatCall] | |
| '{:d}'.format('no') # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int") [str-format] | |
| '{!x}'.format('Hm...') # E: Invalid conversion type "x", must be one of "r", "s" or "a" [str-format] | |
| '}{'.format() # E: Invalid conversion specifier in format string: unexpected } [str-format] | |
| '%d' % 'no' # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int | float | SupportsInt") [str-format] | |
| '%d + %d' % (1, 2, 3) # E: Not all arguments converted during string formatting [str-format] | |
| '{}'.format(b'abc') # E: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). Otherwise, decode the bytes [str-bytes-safe] | |
| '%s' % b'abc' # E: If x = b'abc' then "%s" % x produces "b'abc'", not "abc". If this is desired behavior use "%r" % x. Otherwise, decode the bytes [str-bytes-safe] | |
| [builtins fixtures/primitives.pyi] | |
| [typing fixtures/typing-medium.pyi] | |
| [case testErrorCodeIgnoreNamedDefinedNote] | |
| x: List[int] # type: ignore[name-defined] | |
| [case testErrorCodeProtocolProblemsIgnore] | |
| from typing import Protocol | |
| class P(Protocol): | |
| def f(self, x: str) -> None: ... | |
| class A: | |
| def f(self, x: int) -> None: ... | |
| def g(p: P) -> None: pass | |
| p: A | |
| g(p) # type: ignore[arg-type] | |
| [builtins fixtures/tuple.pyi] | |
| [case testErrorCodeNoneReturnNoteIgnore] | |
| # flags: --disallow-untyped-defs | |
| def f(): # type: ignore[no-untyped-def] | |
| pass | |
| [case testErrorCodeVarianceNoteIgnore] | |
| from typing import List | |
| def f(x: List[object]) -> None: pass | |
| a = [1] | |
| f(a) # type: ignore[arg-type] | |
| [builtins fixtures/list.pyi] | |
| [case testErrorCodeAssignToMethod] | |
| class A: | |
| def f(self) -> None: pass | |
| def g(self: A) -> None: pass | |
| A.f = g # E: Cannot assign to a method [method-assign] | |
| [case testErrorCodeDefinedHereNoteIgnore] | |
| import m | |
| m.f(kw=1) # type: ignore[call-arg] | |
| [file m.py] | |
| def f() -> None: pass | |
| [case testErrorCodeUnionNoteIgnore] | |
| from typing import Union | |
| class Foo: | |
| def __add__(self, x: Foo) -> Foo: pass | |
| def __radd__(self, x: Foo) -> Foo: pass | |
| class Bar: | |
| def __add__(self, x: Bar) -> Bar: pass | |
| def __radd__(self, x: Bar) -> Bar: pass | |
| a: Union[Foo, Bar] | |
| a + a # type: ignore[operator] | |
| a + Foo() # type: ignore[operator] | |
| Foo() + a # type: ignore[operator] | |
| [case testErrorCodeTypeIgnoreMisspelled1] | |
| x = y # type: ignored[foo] | |
| xx = y # type: ignored [foo] | |
| [out] | |
| main:1: error: Name "ignored" is not defined [name-defined] | |
| main:1: error: Name "y" is not defined [name-defined] | |
| main:2: error: Name "ignored" is not defined [name-defined] | |
| main:2: error: Name "y" is not defined [name-defined] | |
| [case testErrorCodeTypeIgnoreMisspelled2] | |
| x = y # type: int # type: ignored[foo] | |
| x = y # type: int # type: ignored [foo] | |
| [out] | |
| main:1: error: Name "y" is not defined [name-defined] | |
| main:1: error: Multiple type comments on the same line [syntax] | |
| main:2: error: Name "x" already defined on line 1 [no-redef] | |
| main:2: error: Name "y" is not defined [name-defined] | |
| main:2: error: Multiple type comments on the same line [syntax] | |
| [case testErrorCode__exit__Return] | |
| class InvalidReturn: | |
| def __exit__(self, x, y, z) -> bool: # E: "bool" is invalid as return type for "__exit__" that always returns False [exit-return] \ | |
| # N: Use "typing.Literal[False]" as the return type or change it to "None" \ | |
| # N: If return type of "__exit__" implies that it may return True, the context manager may swallow exceptions | |
| return False | |
| [builtins fixtures/bool.pyi] | |
| [case testErrorCodeOverloadedOperatorMethod] | |
| from typing import Optional, overload | |
| class A: | |
| @overload | |
| def __add__(self, x: int) -> A: ... | |
| @overload | |
| def __add__(self, x: str) -> str: ... | |
| def __add__(self, x): pass | |
| class B: | |
| pass | |
| x: Optional[B] | |
| A() + x # type: ignore[operator] | |
| class C: | |
| @overload | |
| def __rsub__(self, x: int) -> A: ... | |
| @overload | |
| def __rsub__(self, x: str) -> str: ... | |
| def __rsub__(self, x): pass | |
| x - C() # type: ignore[operator] | |
| [case testErrorCodeMultiLineBinaryOperatorOperand] | |
| from typing import Optional | |
| class C: pass | |
| def f() -> Optional[C]: | |
| return None | |
| f( # type: ignore[operator] | |
| ) + C() | |
| [case testErrorCodeSpecialArgTypeErrors] | |
| from typing import TypedDict | |
| class C(TypedDict): | |
| x: int | |
| c: C | |
| c.setdefault('x', '1') # type: ignore[typeddict-item] | |
| class A: | |
| pass | |
| class B(A): | |
| def f(self) -> None: | |
| super(1, self).foo() # type: ignore[arg-type] | |
| def f(**x: int) -> None: | |
| pass | |
| f(**1) # type: ignore[arg-type] | |
| [builtins fixtures/dict.pyi] | |
| [typing fixtures/typing-typeddict.pyi] | |
| [case testRedundantExpressions] | |
| # flags: --enable-error-code redundant-expr | |
| def foo() -> bool: ... | |
| lst = [1, 2, 3, 4] | |
| b = False or foo() # E: Left operand of "or" is always false [redundant-expr] | |
| c = True and foo() # E: Left operand of "and" is always true [redundant-expr] | |
| g = 3 if True else 4 # E: If condition is always true [redundant-expr] | |
| h = 3 if False else 4 # E: If condition is always false [redundant-expr] | |
| i = [x for x in lst if True] # E: If condition in comprehension is always true [redundant-expr] | |
| j = [x for x in lst if False] # E: If condition in comprehension is always false [redundant-expr] | |
| k = [x for x in lst if isinstance(x, int) or foo()] # E: If condition in comprehension is always true [redundant-expr] | |
| [builtins fixtures/isinstancelist.pyi] | |
| [case testRedundantExprTruthiness] | |
| # flags: --enable-error-code redundant-expr | |
| from typing import List | |
| def maybe() -> bool: ... | |
| class Foo: | |
| def __init__(self, x: List[int]) -> None: | |
| self.x = x or [] | |
| def method(self) -> int: | |
| if not self.x or maybe(): | |
| return 1 | |
| return 2 | |
| [builtins fixtures/list.pyi] | |
| [case testRedundantExpressionsUnionWithAny] | |
| # flags: --enable-error-code redundant-expr | |
| from typing import Any, Awaitable, Union | |
| ok_list: list[Union[Any, Awaitable]] | |
| for y in ok_list: | |
| z = 1 if isinstance(y, Awaitable) else 2 | |
| bad_list: list[Awaitable] | |
| for y in bad_list: | |
| z = 1 if isinstance(y, Awaitable) else 2 # E: If condition is always true [redundant-expr] | |
| [builtins fixtures/isinstancelist.pyi] | |
| [typing fixtures/typing-full.pyi] | |
| [case testNamedTupleNameMismatch] | |
| from typing import NamedTuple | |
| Foo = NamedTuple("Bar", []) # E: First argument to namedtuple() should be "Foo", not "Bar" [name-match] | |
| [builtins fixtures/tuple.pyi] | |
| [case testTypedDictNameMismatch] | |
| from typing import TypedDict | |
| Foo = TypedDict("Bar", {}) # E: First argument "Bar" to TypedDict() does not match variable name "Foo" [name-match] | |
| [builtins fixtures/dict.pyi] | |
| [typing fixtures/typing-typeddict.pyi] | |
| [case testTruthyBool] | |
| # flags: --enable-error-code truthy-bool | |
| from typing import List, Union, Any | |
| class Foo: | |
| pass | |
| class Bar: | |
| pass | |
| foo = Foo() | |
| if foo: # E: "__main__.foo" has type "Foo" which does not implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool] | |
| pass | |
| not foo # E: "__main__.foo" has type "Foo" which does not implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool] | |
| zero = 0 | |
| if zero: | |
| pass | |
| not zero | |
| false = False | |
| if false: | |
| pass | |
| not false | |
| null = None | |
| if null: | |
| pass | |
| not null | |
| s = '' | |
| if s: | |
| pass | |
| not s | |
| good_union: Union[str, int] = 5 | |
| if good_union: | |
| pass | |
| if not good_union: | |
| pass | |
| not good_union | |
| bad_union: Union[Foo, Bar] = Foo() | |
| if bad_union: # E: "__main__.bad_union" has type "Foo | Bar" of which no members implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool] | |
| pass | |
| if not bad_union: # E: "__main__.bad_union" has type "Foo | Bar" of which no members implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool] | |
| pass | |
| not bad_union # E: "__main__.bad_union" has type "Foo | Bar" of which no members implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool] | |
| # 'object' is special and is treated as potentially falsy | |
| obj: object = Foo() | |
| if obj: | |
| pass | |
| if not obj: | |
| pass | |
| not obj | |
| lst: List[int] = [] | |
| if lst: | |
| pass | |
| not lst | |
| a: Any | |
| if a: | |
| pass | |
| not a | |
| any_or_object: Union[object, Any] | |
| if any_or_object: | |
| pass | |
| not any_or_object | |
| if (my_foo := Foo()): # E: "__main__.my_foo" has type "Foo" which does not implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool] | |
| pass | |
| if my_a := (a or Foo()): # E: "__main__.Foo" returns "Foo" which does not implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool] | |
| pass | |
| [builtins fixtures/list.pyi] | |
| [case testTruthyFunctions] | |
| def f(): | |
| pass | |
| if f: # E: Function "f" could always be true in boolean context [truthy-function] | |
| pass | |
| if not f: # E: Function "f" could always be true in boolean context [truthy-function] | |
| pass | |
| conditional_result = 'foo' if f else 'bar' # E: Function "f" could always be true in boolean context [truthy-function] | |
| not f # E: Function "f" could always be true in boolean context [truthy-function] | |
| [case testTruthyIterable] | |
| # flags: --enable-error-code truthy-iterable | |
| from typing import Iterable | |
| def func(var: Iterable[str]) -> None: | |
| if var: # E: "var" has type "Iterable[str]" which can always be true in boolean context. Consider using "Collection[str]" instead. [truthy-iterable] | |
| ... | |
| not var # E: "var" has type "Iterable[str]" which can always be true in boolean context. Consider using "Collection[str]" instead. [truthy-iterable] | |
| [case testNoOverloadImplementation] | |
| from typing import overload | |
| @overload # E: An overloaded function outside a stub file must have an implementation [no-overload-impl] | |
| def f(arg: int) -> int: | |
| ... | |
| @overload | |
| def f(arg: str) -> str: | |
| ... | |
| [case testSliceInDictBuiltin] | |
| # flags: --show-column-numbers | |
| b: dict[int, x:y] | |
| c: dict[x:y] | |
| [builtins fixtures/dict.pyi] | |
| [out] | |
| main:2:14: error: Invalid type comment or annotation [valid-type] | |
| main:3:4: error: "dict" expects 2 type arguments, but 1 given [type-arg] | |
| main:3:9: error: Invalid type comment or annotation [valid-type] | |
| [case testSliceInDictTyping] | |
| # flags: --show-column-numbers | |
| from typing import Dict | |
| b: Dict[int, x:y] | |
| c: Dict[x:y] | |
| [builtins fixtures/dict.pyi] | |
| [out] | |
| main:3:14: error: Invalid type comment or annotation [valid-type] | |
| main:4:4: error: "dict" expects 2 type arguments, but 1 given [type-arg] | |
| main:4:9: error: Invalid type comment or annotation [valid-type] | |
| [case testSliceInCustomTensorType] | |
| # syntactically mimics torchtyping.TensorType | |
| class TensorType: ... | |
| t: TensorType["batch":..., float] # type: ignore | |
| reveal_type(t) # N: Revealed type is "__main__.TensorType" | |
| [builtins fixtures/tuple.pyi] | |
| [case testNoteAboutChangedTypedDictErrorCode] | |
| from typing import TypedDict | |
| class D(TypedDict): | |
| x: int | |
| def f(d: D, s: str) -> None: | |
| d[s] # type: ignore[xyz] \ | |
| # E: TypedDict key must be a string literal; expected one of ("x") [literal-required] \ | |
| # N: Error code "literal-required" not covered by "type: ignore[xyz]" comment | |
| d[s] # E: TypedDict key must be a string literal; expected one of ("x") [literal-required] | |
| d[s] # type: ignore[misc] \ | |
| # E: TypedDict key must be a string literal; expected one of ("x") [literal-required] \ | |
| # N: Error code changed to literal-required; "type: ignore" comment may be out of date | |
| d[s] # type: ignore[literal-required] | |
| [builtins fixtures/dict.pyi] | |
| [typing fixtures/typing-typeddict.pyi] | |
| [case testRecommendErrorCode] | |
| # type: ignore[whatever] # E: Type ignore with error code is not supported for modules; use `# mypy: disable-error-code="whatever"` [syntax] | |
| 1 + "asdf" | |
| [case testRecommendErrorCode2] | |
| # type: ignore[whatever, other] # E: Type ignore with error code is not supported for modules; use `# mypy: disable-error-code="whatever, other"` [syntax] | |
| 1 + "asdf" | |
| [case testShowErrorCodesInConfig] | |
| # flags: --config-file tmp/mypy.ini | |
| # Test 'show_error_codes = True' in config doesn't raise an exception | |
| var: int = "" # E: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment] | |
| [file mypy.ini] | |
| \[mypy] | |
| show_error_codes = True | |
| [case testErrorCodeUnsafeSuper_no_empty] | |
| from abc import abstractmethod | |
| class Base: | |
| @abstractmethod | |
| def meth(self) -> int: | |
| raise NotImplementedError() | |
| class Sub(Base): | |
| def meth(self) -> int: | |
| return super().meth() # E: Call to abstract method "meth" of "Base" with trivial body via super() is unsafe [safe-super] | |
| [builtins fixtures/exception.pyi] | |
| [case testDedicatedErrorCodeForEmpty_no_empty] | |
| from typing import Optional | |
| def foo() -> int: ... # E: Missing return statement [empty-body] | |
| def bar() -> None: ... | |
| # This is inconsistent with how --warn-no-return behaves in general | |
| # but we want to minimize fallout of finally handling empty bodies. | |
| def baz() -> Optional[int]: ... # OK | |
| [case testDedicatedErrorCodeTypeAbstract] | |
| import abc | |
| from typing import TypeVar, Type | |
| class C(abc.ABC): | |
| @abc.abstractmethod | |
| def foo(self) -> None: ... | |
| T = TypeVar("T") | |
| def test(tp: Type[T]) -> T: ... | |
| test(C) # E: Only concrete class can be given where "type[C]" is expected [type-abstract] | |
| class D(C): | |
| @abc.abstractmethod | |
| def bar(self) -> None: ... | |
| cls: Type[C] = D # E: Can only assign concrete classes to a variable of type "type[C]" [type-abstract] | |
| [case testUncheckedAnnotationCodeShown] | |
| def f(): | |
| x: int = "no" # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs [annotation-unchecked] | |
| [case testUncheckedAnnotationSuppressed] | |
| # flags: --disable-error-code=annotation-unchecked | |
| def f(): | |
| x: int = "no" # No warning here | |
| [case testMethodAssignmentSuppressed] | |
| # flags: --disable-error-code=method-assign | |
| class A: | |
| def f(self) -> None: pass | |
| def g(self) -> None: pass | |
| def h(self: A) -> None: pass | |
| A.f = h | |
| # This actually works at runtime, but there is no way to express this in current type system | |
| A.f = A().g # E: Incompatible types in assignment (expression has type "Callable[[], None]", variable has type "Callable[[A], None]") [assignment] | |
| [case testMethodAssignCoveredByAssignmentIgnore] | |
| class A: | |
| def f(self) -> None: pass | |
| def h(self: A) -> None: pass | |
| A.f = h # type: ignore[assignment] | |
| [case testMethodAssignCoveredByAssignmentFlag] | |
| # flags: --disable-error-code=assignment | |
| class A: | |
| def f(self) -> None: pass | |
| def h(self: A) -> None: pass | |
| A.f = h # OK | |
| [case testMethodAssignCoveredByAssignmentUnused] | |
| # flags: --warn-unused-ignores | |
| class A: | |
| def f(self) -> None: pass | |
| def h(self: A) -> None: pass | |
| A.f = h # type: ignore[assignment] # E: Unused "type: ignore" comment, use narrower [method-assign] instead of [assignment] code [unused-ignore] | |
| [case testUnusedIgnoreEnableCode] | |
| # flags: --enable-error-code=unused-ignore | |
| x = 1 # type: ignore # E: Unused "type: ignore" comment [unused-ignore] | |
| [case testErrorCodeUnsafeOverloadError] | |
| from typing import overload, Union | |
| @overload | |
| def unsafe_func(x: int) -> int: ... # E: Overloaded function signatures 1 and 2 overlap with incompatible return types [overload-overlap] | |
| @overload | |
| def unsafe_func(x: object) -> str: ... | |
| def unsafe_func(x: object) -> Union[int, str]: | |
| if isinstance(x, int): | |
| return 42 | |
| else: | |
| return "some string" | |
| [builtins fixtures/isinstancelist.pyi] | |
| ### | |
| # unimported-reveal | |
| ### | |
| [case testUnimportedRevealType] | |
| # flags: --enable-error-code=unimported-reveal | |
| x = 1 | |
| reveal_type(x) | |
| [out] | |
| main:3: error: Name "reveal_type" is not defined [unimported-reveal] | |
| main:3: note: Did you forget to import it from "typing_extensions"? (Suggestion: "from typing_extensions import reveal_type") | |
| main:3: note: Revealed type is "builtins.int" | |
| [builtins fixtures/isinstancelist.pyi] | |
| [case testUnimportedRevealTypePy311] | |
| # flags: --enable-error-code=unimported-reveal --python-version=3.11 | |
| x = 1 | |
| reveal_type(x) | |
| [out] | |
| main:3: error: Name "reveal_type" is not defined [unimported-reveal] | |
| main:3: note: Did you forget to import it from "typing"? (Suggestion: "from typing import reveal_type") | |
| main:3: note: Revealed type is "builtins.int" | |
| [builtins fixtures/isinstancelist.pyi] | |
| [case testUnimportedRevealTypeInUncheckedFunc] | |
| # flags: --enable-error-code=unimported-reveal | |
| def unchecked(): | |
| x = 1 | |
| reveal_type(x) | |
| [out] | |
| main:4: error: Name "reveal_type" is not defined [unimported-reveal] | |
| main:4: note: Did you forget to import it from "typing_extensions"? (Suggestion: "from typing_extensions import reveal_type") | |
| main:4: note: Revealed type is "Any" | |
| main:4: note: 'reveal_type' always outputs 'Any' in unchecked functions | |
| [builtins fixtures/isinstancelist.pyi] | |
| [case testUnimportedRevealTypeImportedTypingExtensions] | |
| # flags: --enable-error-code=unimported-reveal | |
| from typing_extensions import reveal_type | |
| x = 1 | |
| reveal_type(x) # N: Revealed type is "builtins.int" | |
| [builtins fixtures/isinstancelist.pyi] | |
| [case testUnimportedRevealTypeImportedTyping311] | |
| # flags: --enable-error-code=unimported-reveal --python-version=3.11 | |
| from typing import reveal_type | |
| x = 1 | |
| reveal_type(x) # N: Revealed type is "builtins.int" | |
| [builtins fixtures/isinstancelist.pyi] | |
| [typing fixtures/typing-full.pyi] | |
| [case testUnimportedRevealLocals] | |
| # flags: --enable-error-code=unimported-reveal | |
| x = 1 | |
| reveal_locals() | |
| [out] | |
| main:3: note: Revealed local types are: | |
| main:3: note: x: builtins.int | |
| main:3: error: Name "reveal_locals" is not defined [unimported-reveal] | |
| [builtins fixtures/isinstancelist.pyi] | |
| [case testCovariantMutableOverride] | |
| # flags: --enable-error-code=mutable-override | |
| from typing import Any | |
| class C: | |
| x: float | |
| y: float | |
| z: float | |
| w: Any | |
| @property | |
| def foo(self) -> float: ... | |
| @property | |
| def bar(self) -> float: ... | |
| @bar.setter | |
| def bar(self, val: float) -> None: ... | |
| baz: float | |
| bad1: float | |
| bad2: float | |
| class D(C): | |
| x: int # E: Covariant override of a mutable attribute (base class "C" defined the type as "float", expression has type "int") [mutable-override] | |
| y: float | |
| z: Any | |
| w: float | |
| foo: int | |
| bar: int # E: Covariant override of a mutable attribute (base class "C" defined the type as "float", expression has type "int") [mutable-override] | |
| def one(self) -> None: | |
| self.baz = 5 | |
| bad1 = 5 # E: Covariant override of a mutable attribute (base class "C" defined the type as "float", expression has type "int") [mutable-override] | |
| def other(self) -> None: | |
| self.bad2: int = 5 # E: Covariant override of a mutable attribute (base class "C" defined the type as "float", expression has type "int") [mutable-override] | |
| [builtins fixtures/property.pyi] | |
| [case testNarrowedTypeNotSubtype] | |
| from typing_extensions import TypeIs | |
| def f(x: str) -> TypeIs[int]: # E: Narrowed type "int" is not a subtype of input type "str" [narrowed-type-not-subtype] | |
| pass | |
| [builtins fixtures/tuple.pyi] | |
| [case testDynamicMetaclass] | |
| class A(metaclass=type(tuple)): pass # E: Dynamic metaclass not supported for "A" [metaclass] | |
| [builtins fixtures/tuple.pyi] | |
| [case testMetaclassOfTypeAny] | |
| # mypy: disallow-subclassing-any=True | |
| from typing import Any | |
| foo: Any = ... | |
| class A(metaclass=foo): pass # E: Class cannot use "foo" as a metaclass (has type "Any") [metaclass] | |
| [case testMetaclassOfWrongType] | |
| class Foo: | |
| bar = 1 | |
| class A2(metaclass=Foo.bar): pass # E: Invalid metaclass "Foo.bar" [metaclass] | |
| [case testMetaclassNotTypeSubclass] | |
| class M: pass | |
| class A(metaclass=M): pass # E: Metaclasses not inheriting from "type" are not supported [metaclass] | |
| [case testMultipleMetaclasses] | |
| import six | |
| class M1(type): pass | |
| @six.add_metaclass(M1) | |
| class A1(metaclass=M1): pass # E: Multiple metaclass definitions [metaclass] | |
| class A2(six.with_metaclass(M1), metaclass=M1): pass # E: Multiple metaclass definitions [metaclass] | |
| @six.add_metaclass(M1) | |
| class A3(six.with_metaclass(M1)): pass # E: Multiple metaclass definitions [metaclass] | |
| [builtins fixtures/tuple.pyi] | |
| [case testInvalidMetaclassStructure] | |
| class X(type): pass | |
| class Y(type): pass | |
| class A(metaclass=X): pass | |
| class B(A, metaclass=Y): pass # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases [metaclass] \ | |
| # N: "__main__.Y" (metaclass of "__main__.B") conflicts with "__main__.X" (metaclass of "__main__.A") | |
| [case testOverloadedFunctionSignature] | |
| from typing import overload, Union | |
| @overload | |
| def process(response1: float,response2: float) -> float: | |
| ... | |
| @overload | |
| def process(response1: int,response2: int) -> int: # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader [overload-cannot-match] | |
| ... | |
| def process(response1,response2)-> Union[float,int]: | |
| return response1 + response2 |