| -- Test cases for type checking mypy programs using full stubs and running | |
| -- using CPython. | |
| -- | |
| -- These are mostly regression tests -- no attempt is made to make these | |
| -- complete. | |
| [case testHello] | |
| import typing | |
| print('hello, world') | |
| [out] | |
| hello, world | |
| [case testMiscStdlibFeatures] | |
| # Various legacy tests merged together to speed up test runtimes. | |
| def f(x: object) -> None: pass | |
| # testReversed | |
| from typing import Reversible | |
| class R(Reversible): | |
| def __iter__(self): return iter('oof') | |
| def __reversed__(self): return iter('foo') | |
| f(list(reversed(range(5)))) | |
| f(list(reversed([1,2,3]))) | |
| f(list(reversed('abc'))) | |
| f(list(reversed(R()))) | |
| # testIntAndFloatConversion | |
| from typing import SupportsInt, SupportsFloat | |
| class A(SupportsInt): | |
| def __int__(self): return 5 | |
| class B(SupportsFloat): | |
| def __float__(self): return 1.2 | |
| f(int(1)) | |
| f(int(6.2)) | |
| f(int('3')) | |
| f(int(b'4')) | |
| f(int(A())) | |
| f(float(-9)) | |
| f(float(B())) | |
| # testAbs | |
| from typing import SupportsAbs | |
| class Ab(SupportsAbs[float]): | |
| def __abs__(self) -> float: return 5.5 | |
| f(abs(-1)) | |
| f(abs(-1.2)) | |
| f(abs(Ab())) | |
| # testRound | |
| from typing import SupportsRound | |
| class Ro(SupportsRound): | |
| def __round__(self, ndigits=0): return 'x%d' % ndigits | |
| f(round(1.6)) | |
| f(round(Ro())) | |
| f(round(Ro(), 2)) | |
| # testCallMethodViaTypeObject | |
| list.__add__([1, 2], [3, 4]) | |
| # testInheritedClassAttribute | |
| import typing | |
| class AA: | |
| x = 1 | |
| def f(self: typing.Optional["AA"]) -> None: pass | |
| class BB(AA): | |
| pass | |
| BB.f(None) | |
| f(BB.x) | |
| # testSpecialAttributes | |
| class Doc: | |
| """A docstring!""" | |
| f(Doc().__doc__) | |
| f(Doc().__class__) | |
| # testFunctionAttributes | |
| f(ord.__class__) | |
| f(type(ord.__doc__ or '' + '')) | |
| f(ord.__name__) | |
| f(ord.__module__) | |
| # testModuleAttributes | |
| import math | |
| f(type(__spec__)) | |
| f(math.__name__) | |
| f(math.__spec__.name) | |
| f(type(math.__dict__)) | |
| f(type(math.__doc__ or '')) | |
| f(type(math.__spec__).__name__) | |
| f(math.__class__) | |
| [case testAbs2] | |
| n: int | |
| f: float | |
| n = abs(1) | |
| abs(1) + 'x' # Error | |
| f = abs(1.1) | |
| abs(1.1) + 'x' # Error | |
| [out] | |
| _program.py:4: error: Unsupported operand types for + ("int" and "str") | |
| _program.py:6: error: Unsupported operand types for + ("float" and "str") | |
| [case testTypeAttributes] | |
| import typing | |
| print(str.__class__) | |
| print(type(str.__doc__)) | |
| print(str.__name__) | |
| print(str.__module__) | |
| print(str.__dict__ is not None) | |
| [out] | |
| <class 'type'> | |
| <class 'str'> | |
| str | |
| builtins | |
| True | |
| [case testBoolCompatibilityWithInt] | |
| import typing | |
| x = 0 | |
| x = True | |
| print(bool('x')) | |
| print(bool('')) | |
| [out] | |
| True | |
| False | |
| [case testCannotExtendBoolUnlessIgnored] | |
| class A(bool): pass | |
| class B(bool): pass # type: ignore | |
| [out] | |
| _program.py:1: error: Cannot inherit from final class "bool" | |
| [case testCallBuiltinTypeObjectsWithoutArguments] | |
| import typing | |
| print(int()) | |
| print(repr(str())) | |
| print(repr(bytes())) | |
| print(float()) | |
| print(bool()) | |
| [out] | |
| 0 | |
| '' | |
| b'' | |
| 0.0 | |
| False | |
| [case testIntegerDivision] | |
| import typing | |
| x = 1 / 2 | |
| x = 1.5 | |
| [out] | |
| [case testIntMethods] | |
| import typing | |
| print(int.from_bytes(b'ab', 'big')) | |
| n = 0 | |
| print(n.from_bytes(b'ac', 'big')) | |
| print(n.from_bytes([2, 3], 'big')) | |
| print(n.to_bytes(2, 'big')) | |
| [out] | |
| 24930 | |
| 24931 | |
| 515 | |
| b'\x00\x00' | |
| [case testFloatMethods] | |
| import typing | |
| print(1.5.as_integer_ratio()) | |
| print(1.5.hex()) | |
| print(2.0.is_integer()) | |
| print(float.fromhex('0x1.8')) | |
| [out] | |
| (3, 2) | |
| 0x1.8000000000000p+0 | |
| True | |
| 1.5 | |
| [case testDictFromkeys] | |
| import typing | |
| d = dict.fromkeys('foo') | |
| d['x'] = 2 | |
| d2 = dict.fromkeys([1, 2], b'') | |
| d2[2] = b'foo' | |
| [out] | |
| [case testIsinstanceWithTuple] | |
| from typing import cast, Any | |
| x = cast(Any, (1, 'x')) | |
| if isinstance(x, tuple): | |
| print(x[0], x[1]) | |
| [out] | |
| 1 x | |
| [case testAnyStr] | |
| from typing import AnyStr | |
| def f(x: AnyStr) -> AnyStr: | |
| if isinstance(x, str): | |
| return 'foo' | |
| else: | |
| return b'zar' | |
| print(f('')) | |
| print(f(b'')) | |
| [out] | |
| foo | |
| b'zar' | |
| [case testNameNotImportedFromTyping] | |
| import typing | |
| cast(int, 2) | |
| [out] | |
| _program.py:2: error: Name "cast" is not defined | |
| _program.py:2: note: Did you forget to import it from "typing"? (Suggestion: "from typing import cast") | |
| [case testBinaryIOType] | |
| from typing import BinaryIO | |
| def f(f: BinaryIO) -> None: | |
| f.write(b'foo') | |
| f.write(bytearray(b'foo')) | |
| [out] | |
| [case testIOTypes] | |
| from typing import IO | |
| import sys | |
| def txt(f: IO[str]) -> None: | |
| f.write('foo') | |
| f.write(b'foo') | |
| def bin(f: IO[bytes]) -> None: | |
| f.write(b'foo') | |
| f.write(bytearray(b'foo')) | |
| txt(sys.stdout) | |
| bin(sys.stdout) | |
| [out] | |
| _program.py:5: error: Argument 1 to "write" of "IO" has incompatible type "bytes"; expected "str" | |
| _program.py:10: error: Argument 1 to "bin" has incompatible type "TextIO | Any"; expected "IO[bytes]" | |
| [case testBuiltinOpen] | |
| f = open('x') | |
| f.write('x') | |
| f.write(b'x') | |
| f.foobar() | |
| [out] | |
| _program.py:3: error: Argument 1 to "write" of "_TextIOBase" has incompatible type "bytes"; expected "str" | |
| _program.py:4: error: "TextIOWrapper[_WrappedBuffer]" has no attribute "foobar" | |
| [case testOpenReturnTypeInference] | |
| reveal_type(open('x')) | |
| reveal_type(open('x', 'r')) | |
| reveal_type(open('x', 'rb')) | |
| mode = 'rb' | |
| reveal_type(open('x', mode)) | |
| [out] | |
| _program.py:1: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" | |
| _program.py:2: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" | |
| _program.py:3: note: Revealed type is "_io.BufferedReader[_io._BufferedReaderStream]" | |
| _program.py:5: note: Revealed type is "typing.IO[Any]" | |
| [case testOpenReturnTypeInferenceSpecialCases] | |
| reveal_type(open(mode='rb', file='x')) | |
| reveal_type(open(file='x', mode='rb')) | |
| mode = 'rb' | |
| reveal_type(open(mode=mode, file='r')) | |
| [out] | |
| _testOpenReturnTypeInferenceSpecialCases.py:1: note: Revealed type is "_io.BufferedReader[_io._BufferedReaderStream]" | |
| _testOpenReturnTypeInferenceSpecialCases.py:2: note: Revealed type is "_io.BufferedReader[_io._BufferedReaderStream]" | |
| _testOpenReturnTypeInferenceSpecialCases.py:4: note: Revealed type is "typing.IO[Any]" | |
| [case testPathOpenReturnTypeInference] | |
| from pathlib import Path | |
| p = Path("x") | |
| reveal_type(p.open()) | |
| reveal_type(p.open('r')) | |
| reveal_type(p.open('rb')) | |
| mode = 'rb' | |
| reveal_type(p.open(mode)) | |
| [out] | |
| _program.py:3: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" | |
| _program.py:4: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" | |
| _program.py:5: note: Revealed type is "_io.BufferedReader[_io._BufferedReaderStream]" | |
| _program.py:7: note: Revealed type is "typing.IO[Any]" | |
| [case testPathOpenReturnTypeInferenceSpecialCases] | |
| from pathlib import Path | |
| p = Path("x") | |
| reveal_type(p.open(mode='r', errors='replace')) | |
| reveal_type(p.open(errors='replace', mode='r')) | |
| mode = 'r' | |
| reveal_type(p.open(mode=mode, errors='replace')) | |
| [out] | |
| _program.py:3: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" | |
| _program.py:4: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" | |
| _program.py:6: note: Revealed type is "typing.IO[Any]" | |
| [case testGenericPatterns] | |
| from typing import Pattern | |
| import re | |
| p: Pattern[str] | |
| p = re.compile('foo*') | |
| b: Pattern[bytes] | |
| b = re.compile(b'foo*') | |
| m = p.match('fooo') | |
| assert m | |
| print(m.group(0)) | |
| [out] | |
| fooo | |
| [case testGenericMatch] | |
| from typing import Match, Optional | |
| import re | |
| def f(m: Optional[Match[bytes]]) -> None: | |
| assert m | |
| print(m.group(0)) | |
| f(re.match(b'x*', b'xxy')) | |
| [out] | |
| b'xx' | |
| [case testIntFloatDucktyping] | |
| x: float | |
| x = 2.2 | |
| x = 2 | |
| def f(x: float) -> None: pass | |
| f(1.1) | |
| f(1) | |
| [out] | |
| [case testsFloatOperations] | |
| import typing | |
| print(1.5 + 1.5) | |
| print(1.5 + 1) | |
| [out] | |
| 3.0 | |
| 2.5 | |
| [case testMathFunctionWithIntArgument] | |
| import typing | |
| import math | |
| math.sin(2) | |
| math.sin(2.2) | |
| [case testAbsReturnType] | |
| f: float | |
| n: int | |
| n = abs(2) | |
| f = abs(2.2) | |
| abs(2.2) + 'x' | |
| [out] | |
| _program.py:5: error: Unsupported operand types for + ("float" and "str") | |
| [case testROperatorMethods] | |
| b: bytes | |
| s: str | |
| if int(): | |
| s = b'foo' * 5 # Error | |
| if int(): | |
| b = 5 * b'foo' | |
| if int(): | |
| b = b'foo' * 5 | |
| if int(): | |
| s = 5 * 'foo' | |
| if int(): | |
| s = 'foo' * 5 | |
| [out] | |
| _program.py:4: error: Incompatible types in assignment (expression has type "bytes", variable has type "str") | |
| [case testROperatorMethods2] | |
| import typing | |
| print(2 / 0.5) | |
| print(' ', 2 * [3, 4]) | |
| [out] | |
| 4.0 | |
| [3, 4, 3, 4] | |
| [case testNotImplemented] | |
| import typing | |
| class A: | |
| def __add__(self, x: int) -> int: | |
| if isinstance(x, int): | |
| return x + 1 | |
| return NotImplemented | |
| class B: | |
| def __radd__(self, x: A) -> str: | |
| return 'x' | |
| print(A() + 1) | |
| print(A() + B()) | |
| [out] | |
| 2 | |
| x | |
| [case testMappingMethods] | |
| # Regression test | |
| from typing import Mapping | |
| x = {'x': 'y'} # type: Mapping[str, str] | |
| print('x' in x) | |
| print('y' in x) | |
| [out] | |
| True | |
| False | |
| [case testOverlappingOperatorMethods] | |
| class X: pass | |
| class A: | |
| def __add__(self, x: object) -> int: | |
| if isinstance(x, X): | |
| return 1 | |
| return NotImplemented | |
| class B: | |
| def __radd__(self, x: A) -> str: return 'x' | |
| class C(X, B): pass | |
| b: B | |
| b = C() | |
| print(A() + b) | |
| [out] | |
| _program.py:8: error: Signatures of "__radd__" of "B" and "__add__" of "A" are unsafely overlapping | |
| [case testBytesAndBytearrayComparisons] | |
| import typing | |
| print(b'ab' < bytearray(b'b')) | |
| print(bytearray(b'ab') < b'a') | |
| [out] | |
| True | |
| False | |
| [case testBytesAndBytearrayComparisons2] | |
| import typing | |
| '' < b'' | |
| b'' < '' | |
| '' < bytearray() | |
| bytearray() < '' | |
| [out] | |
| _program.py:2: error: Unsupported operand types for < ("str" and "bytes") | |
| _program.py:3: error: Unsupported operand types for < ("bytes" and "str") | |
| _program.py:4: error: Unsupported operand types for < ("str" and "bytearray") | |
| _program.py:5: error: Unsupported operand types for < ("bytearray" and "str") | |
| [case testInplaceOperatorMethod] | |
| import typing | |
| a = [1] | |
| print('', a.__iadd__([2])) | |
| print('', a) | |
| [out] | |
| [1, 2] | |
| [1, 2] | |
| [case testListInplaceAdd] | |
| import typing | |
| a = [1] | |
| a += iter([2, 3]) | |
| print(tuple(a)) | |
| [out] | |
| (1, 2, 3) | |
| [case testInferHeterogeneousListOfIterables] | |
| from typing import Sequence | |
| s = ['x', 'y'] # type: Sequence[str] | |
| a = [['x', 'x'], 'fo', s, iter('foo'), {'aa'}] | |
| for i, x in enumerate(a): | |
| print(i, next(iter(x))) | |
| [out] | |
| 0 x | |
| 1 f | |
| 2 x | |
| 3 f | |
| 4 aa | |
| [case testTextIOProperties] | |
| import typing | |
| import sys | |
| print(type(sys.stdin.encoding)) | |
| print(type(sys.stdin.errors)) | |
| sys.stdin.line_buffering | |
| sys.stdin.buffer | |
| sys.stdin.newlines | |
| [out] | |
| <class 'str'> | |
| <class 'str'> | |
| [case testIOProperties] | |
| import typing | |
| import sys | |
| print(sys.stdin.name) | |
| print(sys.stdin.buffer.mode) | |
| [out] | |
| <stdin> | |
| rb | |
| [case testFromFuturePrintFunction] | |
| from __future__ import print_function | |
| print('a', 'b') | |
| [out] | |
| a b | |
| [case testListMethods] | |
| import typing | |
| import sys | |
| l = [0, 1, 2, 3, 4] | |
| if sys.version >= '3.3': | |
| l.clear() | |
| else: | |
| l = [] | |
| l.append(0) | |
| print('>', l) | |
| if sys.version >= '3.3': | |
| m = l.copy() | |
| else: | |
| m = l[:] | |
| m.extend([1, 2, 3, 4]) | |
| print('>', m) | |
| print(l.index(0)) | |
| print(l.index(0, 0)) | |
| print(l.index(0, 0, 1)) | |
| try: | |
| print(l.index(1)) | |
| print('expected ValueError') | |
| except ValueError: | |
| pass | |
| l.insert(0, 1) | |
| print('>', l) | |
| print(l.pop(0)) | |
| print(l.pop()) | |
| m.remove(0) | |
| try: | |
| m.remove(0) | |
| print('expected ValueError') | |
| except ValueError: | |
| pass | |
| m.reverse() | |
| m.sort() | |
| m.sort(key=lambda x: -x) | |
| m.sort(reverse=False) | |
| m.sort(key=lambda x: -x, reverse=True) | |
| print('>', m) | |
| [out] | |
| > [0] | |
| > [0, 1, 2, 3, 4] | |
| 0 | |
| 0 | |
| 0 | |
| > [1, 0] | |
| 1 | |
| 0 | |
| > [1, 2, 3, 4] | |
| [case testListOperators] | |
| import typing | |
| l = [0, 1] | |
| print('+', l + [2]) | |
| print('*', l * 2) | |
| print('*', 2 * l) | |
| print('in', 1 in l) | |
| print('==', l == [1, 2]) | |
| print('!=', l != [1, 2]) | |
| print('>', l > [1, 2, 3]) | |
| print('>=', l >= [1, 2, 3]) | |
| print('<', l < [1, 2, 3]) | |
| print('<=', l <= [1, 2, 3]) | |
| print('>[0]', l[0]) | |
| l += [2] | |
| print('+=', l) | |
| l *= 2 | |
| print('*=', l) | |
| print('iter', list(iter(l))) | |
| print('len', len(l)) | |
| print('repr', repr(l)) | |
| l[:3] = [] | |
| print('setslice', l) | |
| print('reversed', list(reversed(l))) | |
| [out] | |
| + [0, 1, 2] | |
| * [0, 1, 0, 1] | |
| * [0, 1, 0, 1] | |
| in True | |
| == False | |
| != True | |
| > False | |
| >= False | |
| < True | |
| <= True | |
| >[0] 0 | |
| += [0, 1, 2] | |
| *= [0, 1, 2, 0, 1, 2] | |
| iter [0, 1, 2, 0, 1, 2] | |
| len 6 | |
| repr [0, 1, 2, 0, 1, 2] | |
| setslice [0, 1, 2] | |
| reversed [2, 1, 0] | |
| [case testTupleAsSubtypeOfSequence] | |
| from typing import TypeVar, Sequence | |
| T = TypeVar('T') | |
| def f(a: Sequence[T]) -> None: print(a) | |
| f(tuple()) | |
| [out] | |
| () | |
| [case testMapWithLambdaSpecialCase] | |
| from typing import List, Iterator | |
| a = [[1], [3]] | |
| b = map(lambda y: y[0], a) | |
| print('>', list(b)) | |
| [out] | |
| > [1, 3] | |
| [case testInternalBuiltinDefinition] | |
| import typing | |
| def f(x: _T) -> None: pass | |
| s: FrozenSet | |
| [out] | |
| _program.py:2: error: Name "_T" is not defined | |
| _program.py:3: error: Name "FrozenSet" is not defined; did you mean "frozenset"? | |
| [case testVarArgsFunctionSubtyping] | |
| import typing | |
| def f(*args: str) -> str: return args[0] | |
| map(f, ['x']) | |
| map(f, [1]) | |
| [out] | |
| _program.py:4: error: Argument 1 to "map" has incompatible type "def f(*args: str) -> str"; expected "Callable[[int], str]" | |
| [case testMapStr] | |
| import typing | |
| x = range(3) | |
| a = list(map(str, x)) | |
| a + 1 | |
| [out] | |
| _testMapStr.py:4: error: No overload variant of "__add__" of "list" matches argument type "int" | |
| _testMapStr.py:4: note: Possible overload variants: | |
| _testMapStr.py:4: note: def __add__(self, list[str], /) -> list[str] | |
| _testMapStr.py:4: note: def [_S] __add__(self, list[_S], /) -> list[_S | str] | |
| [case testRelativeImport] | |
| import typing | |
| from m import x | |
| print(x) | |
| [file m/__init__.py] | |
| from .n import x | |
| [file m/n.py] | |
| x = 1 | |
| [out] | |
| 1 | |
| [case testRelativeImport2] | |
| import typing | |
| from m.n import x | |
| print(x) | |
| [file m/__init__.py] | |
| [file m/n.py] | |
| from .nn import x | |
| [file m/nn.py] | |
| x = 2 | |
| [out] | |
| 2 | |
| [case testPyiTakesPrecedenceOverPy] | |
| import m | |
| m.f(1) | |
| [file m.py] | |
| def f(x): | |
| print(x) | |
| [file m.pyi] | |
| import typing | |
| def f(x: str) -> None: pass | |
| [out] | |
| _program.py:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" | |
| [case testComplexArithmetic] | |
| import typing | |
| print(5 + 8j) | |
| print(3j * 2.0) | |
| print(4J / 2.0) | |
| [out] | |
| (5+8j) | |
| 6j | |
| 2j | |
| [case testComplexArithmetic2] | |
| x = 5 + 8j | |
| if int(): | |
| x = '' # E | |
| y = 3j * 2.0 | |
| if int(): | |
| y = '' # E | |
| [out] | |
| _program.py:3: error: Incompatible types in assignment (expression has type "str", variable has type "complex") | |
| _program.py:6: error: Incompatible types in assignment (expression has type "str", variable has type "complex") | |
| [case testSuperNew] | |
| from typing import Dict, Any | |
| class MyType(type): | |
| def __new__(cls, name: str, bases: tuple, namespace: Dict[str, Any]) -> Any: | |
| return super().__new__(cls, name + 'x', bases, namespace) | |
| class A(metaclass=MyType): pass | |
| print(type(A()).__name__) | |
| [out] | |
| Ax | |
| [case testSubclassBothGenericAndNonGenericABC] | |
| from typing import Generic, TypeVar | |
| from abc import ABCMeta | |
| T = TypeVar('T') | |
| class A(metaclass=ABCMeta): pass | |
| class B(Generic[T]): pass | |
| class C(A, B): pass | |
| class D(B, A): pass | |
| class E(A, B[T], Generic[T]): pass | |
| class F(B[T], A, Generic[T]): pass | |
| def f(e: E[int], f: F[int]) -> None: pass | |
| [out] | |
| [case testTypeVariableTypeComparability] | |
| from typing import TypeVar | |
| T = TypeVar('T') | |
| def eq(x: T, y: T, z: T) -> T: | |
| if x == y: | |
| return y | |
| else: | |
| return z | |
| print(eq(1, 2, 3)) | |
| print(eq('x', 'x', 'z')) | |
| [out] | |
| 3 | |
| x | |
| [case testIntDecimalCompatibility] | |
| import typing | |
| from decimal import Decimal | |
| print(Decimal(1) + 2) | |
| print(Decimal(1) - 2) | |
| print(1 + Decimal('2.34')) | |
| print(1 - Decimal('2.34')) | |
| print(2 * Decimal('2.34')) | |
| [out] | |
| 3 | |
| -1 | |
| 3.34 | |
| -1.34 | |
| 4.68 | |
| [case testInstantiateBuiltinTypes] | |
| from typing import Dict, Set, List | |
| d = dict() # type: Dict[int, str] | |
| s = set() # type: Set[int] | |
| l = list() # type: List[int] | |
| str() | |
| bytes() | |
| bytearray() | |
| int() | |
| float() | |
| complex() | |
| slice(1) | |
| bool() | |
| [case testVariableLengthTupleError] | |
| from typing import Tuple | |
| def p(t: Tuple[str, ...]) -> None: | |
| n = 5 | |
| print(t[n]) | |
| for s in t: | |
| s() | |
| ''.startswith(('x', 'y')) | |
| ''.startswith(('x', b'y')) | |
| [out] | |
| _program.py:6: error: "str" not callable | |
| _program.py:8: error: Argument 1 to "startswith" of "str" has incompatible type "tuple[str, bytes]"; expected "str | tuple[str, ...]" | |
| [case testMultiplyTupleByInteger] | |
| n = 4 | |
| t = ('',) * n | |
| t + 1 | |
| [out] | |
| _program.py:3: error: No overload variant of "__add__" of "tuple" matches argument type "int" | |
| _program.py:3: note: Possible overload variants: | |
| _program.py:3: note: def __add__(self, tuple[str, ...], /) -> tuple[str, ...] | |
| _program.py:3: note: def [_T] __add__(self, tuple[_T, ...], /) -> tuple[str | _T, ...] | |
| [case testMultiplyTupleByIntegerReverse] | |
| n = 4 | |
| t = n * ('',) | |
| t + 1 | |
| [out] | |
| _program.py:3: error: No overload variant of "__add__" of "tuple" matches argument type "int" | |
| _program.py:3: note: Possible overload variants: | |
| _program.py:3: note: def __add__(self, tuple[str, ...], /) -> tuple[str, ...] | |
| _program.py:3: note: def [_T] __add__(self, tuple[_T, ...], /) -> tuple[str | _T, ...] | |
| [case testDictWithKeywordArgs] | |
| from typing import Dict, Any, List | |
| d1 = dict(a=1, b=2) # type: Dict[str, int] | |
| d2 = dict(a=1, b='') # type: Dict[str, int] # E | |
| d3 = dict(a=1, b=1) | |
| d3.xyz # E | |
| d4 = dict(a=1, b='') # type: Dict[str, Any] | |
| result = dict(x=[], y=[]) # type: Dict[str, List[str]] | |
| [out] | |
| _program.py:3: error: Dict entry 1 has incompatible type "str": "str"; expected "str": "int" | |
| _program.py:5: error: "dict[str, int]" has no attribute "xyz" | |
| [case testDefaultDict] | |
| import typing as t | |
| from collections import defaultdict | |
| T = t.TypeVar('T') | |
| d1 = defaultdict(list) # type: t.DefaultDict[int, str] | |
| d2 = defaultdict() # type: t.DefaultDict[int, str] | |
| d2[0] = '0' | |
| d2['0'] = 0 | |
| def tst(dct: t.DefaultDict[int, T]) -> T: | |
| return dct[0] | |
| collections = ['coins', 'stamps', 'comics'] # type: t.List[str] | |
| d3 = defaultdict(str) # type: t.DefaultDict[int, str] | |
| collections[2] | |
| tst(defaultdict(list, {0: []})) | |
| tst(defaultdict(list, {'0': []})) | |
| class MyDDict(t.DefaultDict[int,T], t.Generic[T]): | |
| pass | |
| MyDDict(dict)['0'] | |
| MyDDict(dict)[0] | |
| [out] | |
| _program.py:6: error: Argument 1 to "defaultdict" has incompatible type "type[list[_T]]"; expected "Callable[[], str] | None" | |
| _program.py:9: error: Invalid index type "str" for "defaultdict[int, str]"; expected type "int" | |
| _program.py:9: error: Incompatible types in assignment (expression has type "int", target has type "str") | |
| _program.py:19: error: Argument 1 to "tst" has incompatible type "defaultdict[str, list[Never]]"; expected "defaultdict[int, list[Never]]" | |
| _program.py:23: error: Invalid index type "str" for "MyDDict[dict[Never, Never]]"; expected type "int" | |
| [case testCollectionsAliases] | |
| import typing as t | |
| import collections as c | |
| o1 = c.Counter() # type: t.Counter[int] | |
| reveal_type(o1) | |
| o1['string'] | |
| o2 = c.ChainMap() # type: t.ChainMap[int, str] | |
| reveal_type(o2) | |
| o3 = c.deque() # type: t.Deque[int] | |
| reveal_type(o3) | |
| o4 = t.Counter[int]() | |
| reveal_type(o4) | |
| o5 = t.ChainMap[int, str]() | |
| reveal_type(o5) | |
| o6 = t.Deque[int]() | |
| reveal_type(o6) | |
| [out] | |
| _testCollectionsAliases.py:5: note: Revealed type is "collections.Counter[int]" | |
| _testCollectionsAliases.py:6: error: Invalid index type "str" for "Counter[int]"; expected type "int" | |
| _testCollectionsAliases.py:9: note: Revealed type is "collections.ChainMap[int, str]" | |
| _testCollectionsAliases.py:12: note: Revealed type is "collections.deque[int]" | |
| _testCollectionsAliases.py:15: note: Revealed type is "collections.Counter[int]" | |
| _testCollectionsAliases.py:18: note: Revealed type is "collections.ChainMap[int, str]" | |
| _testCollectionsAliases.py:21: note: Revealed type is "collections.deque[int]" | |
| [case testChainMapUnimported] | |
| ChainMap[int, str]() | |
| [out] | |
| _testChainMapUnimported.py:1: error: Name "ChainMap" is not defined | |
| [case testDequeWrongCase] | |
| import collections | |
| import typing | |
| collections.Deque() | |
| typing.deque() | |
| [out] | |
| _testDequeWrongCase.py:4: error: Module has no attribute "Deque"; maybe "deque"? | |
| _testDequeWrongCase.py:5: error: Module has no attribute "deque"; maybe "Deque"? | |
| [case testDictUpdateInference] | |
| from typing import Dict, Optional | |
| d = {} # type: Dict[str, Optional[int]] | |
| d.update({str(i): None for i in range(4)}) | |
| [case testSuperAndSetattr] | |
| class A: | |
| def __init__(self) -> None: | |
| super().__setattr__('a', 1) | |
| super().__setattr__(1, 'a') | |
| [out] | |
| _program.py:4: error: Argument 1 to "__setattr__" of "object" has incompatible type "int"; expected "str" | |
| [case testMetaclassAndSuper] | |
| from typing import Any | |
| class A(type): | |
| def __new__(cls, name, bases, namespace) -> Any: | |
| return super().__new__(cls, '', (object,), {'x': 7}) | |
| class B(metaclass=A): | |
| pass | |
| print(getattr(B(), 'x')) | |
| [out] | |
| 7 | |
| [case testSortedNoError] | |
| from typing import Iterable, Callable, TypeVar, List, Dict, Optional | |
| T = TypeVar('T') | |
| def sorted(x: Iterable[T], *, key: Optional[Callable[[T], object]] = None) -> None: ... | |
| a = [] # type: List[Dict[str, str]] | |
| sorted(a, key=lambda y: y['']) | |
| [case testAbstractProperty] | |
| from abc import abstractproperty, ABCMeta # type: ignore[deprecated] | |
| class A(metaclass=ABCMeta): | |
| @abstractproperty | |
| def x(self) -> int: pass | |
| class B(A): | |
| @property | |
| def x(self) -> int: | |
| return 3 | |
| b = B() | |
| print(b.x + 1) | |
| [out] | |
| 4 | |
| [case testInferenceWithLambda] | |
| from typing import TypeVar, Iterable, Iterator, List | |
| import itertools | |
| _T = TypeVar('_T') | |
| def f(iterable): # type: (Iterable[_T]) -> Iterator[List[_T]] | |
| grouped = itertools.groupby(enumerate(iterable), lambda pair: pair[0] // 2) | |
| return ([elem for _, elem in group] for _, group in grouped) | |
| [case testReModuleBytes] | |
| # Regression tests for various overloads in the re module -- bytes version | |
| import re | |
| bre = b'a+' | |
| bpat = re.compile(bre) | |
| bpat = re.compile(bpat) | |
| s1 = re.search(bre, b'') | |
| assert s1 | |
| s1.groups() | |
| re.search(bre, u'') # Error | |
| s2 = re.search(bpat, b'') | |
| assert s2 | |
| s2.groups() | |
| re.search(bpat, u'') # Error | |
| # match(), split(), findall(), finditer() are much the same, so skip those. | |
| # sub(), subn() have more overloads and we are checking these: | |
| re.sub(bre, b'', b'') + b'' | |
| re.sub(bpat, b'', b'') + b'' | |
| re.sub(bre, lambda m: b'', b'') + b'' | |
| re.sub(bpat, lambda m: b'', b'') + b'' | |
| re.subn(bre, b'', b'')[0] + b'' | |
| re.subn(bpat, b'', b'')[0] + b'' | |
| re.subn(bre, lambda m: b'', b'')[0] + b'' | |
| re.subn(bpat, lambda m: b'', b'')[0] + b'' | |
| [out] | |
| _testReModuleBytes.py:9: error: No overload variant of "search" matches argument types "bytes", "str" | |
| _testReModuleBytes.py:9: note: Possible overload variants: | |
| _testReModuleBytes.py:9: note: def search(pattern: str | Pattern[str], string: str, flags: int | RegexFlag = ...) -> Match[str] | None | |
| _testReModuleBytes.py:9: note: def search(pattern: bytes | Pattern[bytes], string: Buffer, flags: int | RegexFlag = ...) -> Match[bytes] | None | |
| _testReModuleBytes.py:13: error: Argument 1 to "search" has incompatible type "Pattern[bytes]"; expected "str | Pattern[str]" | |
| [case testReModuleString] | |
| # Regression tests for various overloads in the re module -- string version | |
| import re | |
| sre = 'a+' | |
| spat = re.compile(sre) | |
| spat = re.compile(spat) | |
| s1 = re.search(sre, '') | |
| assert s1 | |
| s1.groups() | |
| re.search(sre, b'') # Error | |
| s2 = re.search(spat, '') | |
| assert s2 | |
| s2.groups() | |
| re.search(spat, b'') # Error | |
| # match(), split(), findall(), finditer() are much the same, so skip those. | |
| # sus(), susn() have more overloads and we are checking these: | |
| re.sub(sre, '', '') + '' | |
| re.sub(spat, '', '') + '' | |
| re.sub(sre, lambda m: '', '') + '' | |
| re.sub(spat, lambda m: '', '') + '' | |
| re.subn(sre, '', '')[0] + '' | |
| re.subn(spat, '', '')[0] + '' | |
| re.subn(sre, lambda m: '', '')[0] + '' | |
| re.subn(spat, lambda m: '', '')[0] + '' | |
| [out] | |
| _testReModuleString.py:9: error: No overload variant of "search" matches argument types "str", "bytes" | |
| _testReModuleString.py:9: note: Possible overload variants: | |
| _testReModuleString.py:9: note: def search(pattern: str | Pattern[str], string: str, flags: int | RegexFlag = ...) -> Match[str] | None | |
| _testReModuleString.py:9: note: def search(pattern: bytes | Pattern[bytes], string: Buffer, flags: int | RegexFlag = ...) -> Match[bytes] | None | |
| _testReModuleString.py:13: error: Argument 1 to "search" has incompatible type "Pattern[str]"; expected "bytes | Pattern[bytes]" | |
| [case testListSetitemTuple] | |
| from typing import List, Tuple | |
| a = [] # type: List[Tuple[str, int]] | |
| a[0] = 'x', 1 | |
| a[1] = 2, 'y' | |
| a[:] = [('z', 3)] | |
| [out] | |
| _program.py:4: error: Incompatible types in assignment (expression has type "tuple[int, str]", target has type "tuple[str, int]") | |
| [case testContextManager] | |
| import contextlib | |
| from contextlib import contextmanager | |
| from typing import Iterator | |
| @contextmanager | |
| def f(x: int) -> Iterator[str]: | |
| yield 'foo' | |
| @contextlib.contextmanager | |
| def g(*x: str) -> Iterator[int]: | |
| yield 1 | |
| reveal_type(f) | |
| reveal_type(g) | |
| with f('') as s: | |
| reveal_type(s) | |
| [out] | |
| _program.py:13: note: Revealed type is "def (x: int) -> contextlib._GeneratorContextManager[str, None, None]" | |
| _program.py:14: note: Revealed type is "def (*x: str) -> contextlib._GeneratorContextManager[int, None, None]" | |
| _program.py:16: error: Argument 1 to "f" has incompatible type "str"; expected "int" | |
| _program.py:17: note: Revealed type is "str" | |
| [case testTypedDictGet] | |
| # Test that TypedDict get plugin works with typeshed stubs | |
| from typing import TypedDict | |
| class A: pass | |
| D_total = TypedDict('D_total', {'x': int, 'y': str}, total=True) | |
| D_not_total = TypedDict('D_not_total', {'x': int, 'y': str}, total=False) | |
| def test_total(d: D_total) -> None: | |
| reveal_type(d.get('x')) | |
| reveal_type(d.get('y')) | |
| reveal_type(d.get('z')) | |
| d.get() | |
| s = '' | |
| reveal_type(d.get(s)) | |
| def test_not_total(d: D_not_total) -> None: | |
| reveal_type(d.get('x')) | |
| reveal_type(d.get('y')) | |
| reveal_type(d.get('z')) | |
| d.get() | |
| s = '' | |
| reveal_type(d.get(s)) | |
| [out] | |
| _testTypedDictGet.py:8: note: Revealed type is "int" | |
| _testTypedDictGet.py:9: note: Revealed type is "str" | |
| _testTypedDictGet.py:10: note: Revealed type is "object" | |
| _testTypedDictGet.py:11: error: All overload variants of "get" of "Mapping" require at least one argument | |
| _testTypedDictGet.py:11: note: Possible overload variants: | |
| _testTypedDictGet.py:11: note: def get(self, str, /) -> object | |
| _testTypedDictGet.py:11: note: def get(self, str, object, /) -> object | |
| _testTypedDictGet.py:11: note: def [_T] get(self, str, _T, /) -> object | |
| _testTypedDictGet.py:13: note: Revealed type is "object" | |
| _testTypedDictGet.py:16: note: Revealed type is "int | None" | |
| _testTypedDictGet.py:17: note: Revealed type is "str | None" | |
| _testTypedDictGet.py:18: note: Revealed type is "object" | |
| _testTypedDictGet.py:19: error: All overload variants of "get" of "Mapping" require at least one argument | |
| _testTypedDictGet.py:19: note: Possible overload variants: | |
| _testTypedDictGet.py:19: note: def get(self, str, /) -> object | |
| _testTypedDictGet.py:19: note: def get(self, str, object, /) -> object | |
| _testTypedDictGet.py:19: note: def [_T] get(self, str, _T, /) -> object | |
| _testTypedDictGet.py:21: note: Revealed type is "object" | |
| [case testTypedDictMappingMethods] | |
| from typing import TypedDict | |
| Cell = TypedDict('Cell', {'value': int}) | |
| c = Cell(value=42) | |
| for x in c: | |
| reveal_type(x) | |
| reveal_type(iter(c)) | |
| reveal_type(len(c)) | |
| reveal_type('value' in c) | |
| reveal_type(c.keys()) | |
| reveal_type(c.items()) | |
| reveal_type(c.values()) | |
| reveal_type(c.copy()) | |
| reveal_type(c.setdefault('value', False)) | |
| c.update({'value': 2}) | |
| c.update({'invalid': 2}) | |
| c.pop('value') | |
| c == c | |
| c != c | |
| Cell2 = TypedDict('Cell2', {'value': int}, total=False) | |
| c2 = Cell2() | |
| reveal_type(c2.pop('value')) | |
| [out] | |
| _testTypedDictMappingMethods.py:5: note: Revealed type is "str" | |
| _testTypedDictMappingMethods.py:6: note: Revealed type is "typing.Iterator[str]" | |
| _testTypedDictMappingMethods.py:7: note: Revealed type is "int" | |
| _testTypedDictMappingMethods.py:8: note: Revealed type is "bool" | |
| _testTypedDictMappingMethods.py:9: note: Revealed type is "_collections_abc.dict_keys[str, object]" | |
| _testTypedDictMappingMethods.py:10: note: Revealed type is "_collections_abc.dict_items[str, object]" | |
| _testTypedDictMappingMethods.py:11: note: Revealed type is "_collections_abc.dict_values[str, object]" | |
| _testTypedDictMappingMethods.py:12: note: Revealed type is "TypedDict(_testTypedDictMappingMethods.Cell, {'value': int})" | |
| _testTypedDictMappingMethods.py:13: note: Revealed type is "int" | |
| _testTypedDictMappingMethods.py:15: error: Unexpected TypedDict key "invalid" | |
| _testTypedDictMappingMethods.py:16: error: Key "value" of TypedDict "Cell" cannot be deleted | |
| _testTypedDictMappingMethods.py:21: note: Revealed type is "int" | |
| [case testCrashOnComplexCheckWithNamedTupleNext] | |
| from typing import NamedTuple, Optional | |
| MyNamedTuple = NamedTuple('MyNamedTuple', [('parent', 'MyNamedTuple')]) # type: ignore | |
| def foo(mymap) -> Optional[MyNamedTuple]: | |
| return next((mymap[key] for key in mymap), None) | |
| [out] | |
| [case testCanConvertTypedDictToAnySuperclassOfMapping] | |
| from typing import Sized, TypedDict, Iterable, Container | |
| Point = TypedDict('Point', {'x': int, 'y': int}) | |
| p: Point | |
| s: Sized = p | |
| it: Iterable[str] = p | |
| c: Container[str] = p | |
| o: object = p | |
| it2: Iterable[int] = p | |
| [out] | |
| _testCanConvertTypedDictToAnySuperclassOfMapping.py:10: error: Incompatible types in assignment (expression has type "Point", variable has type "Iterable[int]") | |
| _testCanConvertTypedDictToAnySuperclassOfMapping.py:10: note: Following member(s) of "Point" have conflicts: | |
| _testCanConvertTypedDictToAnySuperclassOfMapping.py:10: note: Expected: | |
| _testCanConvertTypedDictToAnySuperclassOfMapping.py:10: note: def __iter__(self) -> Iterator[int] | |
| _testCanConvertTypedDictToAnySuperclassOfMapping.py:10: note: Got: | |
| _testCanConvertTypedDictToAnySuperclassOfMapping.py:10: note: def __iter__(self) -> Iterator[str] | |
| [case testAsyncioGatherPreciseType-xfail] | |
| # Mysteriously regressed in #11905 | |
| import asyncio | |
| from typing import Tuple | |
| async def get_location(arg: str) -> Tuple[str, str]: | |
| return arg, arg | |
| async def main() -> None: | |
| ((a_x, a_y),) = await asyncio.gather(get_location('start')) | |
| reveal_type(a_x) | |
| reveal_type(a_y) | |
| reveal_type(asyncio.gather(*[asyncio.sleep(1), asyncio.sleep(1)])) | |
| [out] | |
| _testAsyncioGatherPreciseType.py:9: note: Revealed type is "str" | |
| _testAsyncioGatherPreciseType.py:10: note: Revealed type is "str" | |
| _testAsyncioGatherPreciseType.py:11: note: Revealed type is "asyncio.futures.Future[list[Any]]" | |
| [case testMultipleInheritanceWorksWithTupleTypeGeneric] | |
| from typing import SupportsAbs, NamedTuple | |
| class Point(NamedTuple('Point', [('x', int), ('y', int)]), SupportsAbs[int]): | |
| def __abs__(p) -> int: | |
| return abs(p.x) + abs(p.y) | |
| def test(a: Point) -> bool: | |
| return abs(a) == 2 | |
| [out] | |
| [case testNoCrashOnGenericUnionUnpacking] | |
| from typing import Union, Dict | |
| TEST = {'key': ('a', 'b')} | |
| def test() -> None: | |
| a, b = TEST.get('foo', ('x', 'y')) | |
| reveal_type(a) | |
| reveal_type(b) | |
| def test2() -> None: | |
| a, b = TEST.get('foo', (1, 2)) | |
| reveal_type(a) | |
| reveal_type(b) | |
| x: Union[Dict[int, int], Dict[str, str]] = dict(a='b') | |
| for a, b in x.items(): | |
| reveal_type(a) | |
| reveal_type(b) | |
| [out] | |
| _testNoCrashOnGenericUnionUnpacking.py:6: note: Revealed type is "str" | |
| _testNoCrashOnGenericUnionUnpacking.py:7: note: Revealed type is "str" | |
| _testNoCrashOnGenericUnionUnpacking.py:10: note: Revealed type is "str | int" | |
| _testNoCrashOnGenericUnionUnpacking.py:11: note: Revealed type is "str | int" | |
| _testNoCrashOnGenericUnionUnpacking.py:15: note: Revealed type is "int | str" | |
| _testNoCrashOnGenericUnionUnpacking.py:16: note: Revealed type is "int | str" | |
| [case testMetaclassOpAccess] | |
| from typing import Type | |
| class A: | |
| pass | |
| class Meta(type): | |
| def __mul__(self, other: int) -> Type[A]: | |
| pass | |
| def __add__(self, other: int) -> Type[C]: | |
| pass | |
| def __radd__(self, other: int) -> Type[C]: | |
| pass | |
| class C(metaclass=Meta): | |
| pass | |
| bar: Type[C] | |
| def get_c_type() -> Type[C]: | |
| pass | |
| res = bar * 4 | |
| other = 4 + get_c_type() + 5 | |
| reveal_type(res) | |
| reveal_type(other) | |
| [out] | |
| _testMetaclassOpAccess.py:21: note: Revealed type is "type[_testMetaclassOpAccess.A]" | |
| _testMetaclassOpAccess.py:22: note: Revealed type is "type[_testMetaclassOpAccess.C]" | |
| [case testMetaclassOpAccessUnion] | |
| from typing import Type, Union | |
| class MetaA(type): | |
| def __mul__(self, other: int) -> str: | |
| pass | |
| class A(metaclass=MetaA): | |
| pass | |
| class MetaB(type): | |
| def __mul__(self, other: int) -> int: | |
| pass | |
| class B(metaclass=MetaB): | |
| pass | |
| bar: Type[Union[A, B]] | |
| res = bar * 4 | |
| reveal_type(res) | |
| [out] | |
| _testMetaclassOpAccessUnion.py:16: note: Revealed type is "str | int" | |
| [case testMetaclassOpAccessAny] | |
| from typing import Type | |
| from nonexistent import C | |
| bar: Type[C] | |
| bar * 4 + bar + 3 # should not produce more errors | |
| [out] | |
| _testMetaclassOpAccessAny.py:2: error: Cannot find implementation or library stub for module named "nonexistent" | |
| _testMetaclassOpAccessAny.py:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports | |
| [case testEnumIterationAndPreciseElementType] | |
| # Regression test for #2305 | |
| from enum import Enum | |
| class E(Enum): | |
| A = 'a' | |
| (reveal_type(e) for e in E) | |
| for e in E: | |
| reveal_type(e) | |
| [out] | |
| _testEnumIterationAndPreciseElementType.py:5: note: Revealed type is "_testEnumIterationAndPreciseElementType.E" | |
| _testEnumIterationAndPreciseElementType.py:7: note: Revealed type is "_testEnumIterationAndPreciseElementType.E" | |
| [case testEnumIterable] | |
| from enum import Enum | |
| from typing import Iterable | |
| class E(Enum): | |
| A = 'a' | |
| def f(ie: Iterable[E]): | |
| pass | |
| f(E) | |
| [case testIntEnumIterable] | |
| from enum import IntEnum | |
| from typing import Iterable | |
| class N(IntEnum): | |
| X = 1 | |
| def f(ni: Iterable[N]): | |
| pass | |
| def g(ii: Iterable[int]): | |
| pass | |
| f(N) | |
| g(N) | |
| reveal_type(list(N)) | |
| [out] | |
| _testIntEnumIterable.py:11: note: Revealed type is "list[_testIntEnumIterable.N]" | |
| [case testDerivedEnumIterable] | |
| from enum import Enum | |
| from typing import Iterable | |
| class E(str, Enum): | |
| A = 'foo' | |
| def f(ei: Iterable[E]): | |
| pass | |
| def g(si: Iterable[str]): | |
| pass | |
| f(E) | |
| g(E) | |
| [case testInvalidSlots] | |
| from typing import List | |
| class A: | |
| __slots__ = 1 | |
| class B: | |
| __slots__ = (1, 2) | |
| class C: | |
| __slots__: List[int] = [] | |
| [out] | |
| _testInvalidSlots.py:3: error: Invalid type for "__slots__" (actual type "int", expected type "str | Iterable[str]") | |
| _testInvalidSlots.py:5: error: Invalid type for "__slots__" (actual type "tuple[int, int]", expected type "str | Iterable[str]") | |
| _testInvalidSlots.py:7: error: Invalid type for "__slots__" (actual type "list[int]", expected type "str | Iterable[str]") | |
| [case testDictWithStarStarSpecialCase] | |
| from typing import Dict | |
| def f() -> Dict[int, str]: | |
| return {1: '', **d()} | |
| def d() -> Dict[int, int]: | |
| return {} | |
| [out] | |
| _testDictWithStarStarSpecialCase.py:4: error: Unpacked dict entry 1 has incompatible type "dict[int, int]"; expected "SupportsKeysAndGetItem[int, str]" | |
| [case testLoadsOfOverloads] | |
| from typing import overload, Any, TypeVar, Iterable, List, Dict, Callable, Union | |
| S = TypeVar('S') | |
| T = TypeVar('T') | |
| @overload | |
| def simple_map() -> None: ... | |
| @overload | |
| def simple_map(func: Callable[[T], S], one: Iterable[T]) -> S: ... | |
| @overload | |
| def simple_map(func: Callable[..., S], *iterables: Iterable[Any]) -> S: ... | |
| def simple_map(*args): pass | |
| def format_row(*entries: object) -> str: pass | |
| class DateTime: pass | |
| JsonBlob = Dict[str, Any] | |
| Column = Union[List[str], List[int], List[bool], List[float], List[DateTime], List[JsonBlob]] | |
| def print_custom_table() -> None: | |
| a: Column | |
| for row in simple_map(format_row, a, a, a, a, a, a, a, a): # 8 columns | |
| reveal_type(row) | |
| [out] | |
| _testLoadsOfOverloads.py:24: note: Revealed type is "str" | |
| [case testReduceWithAnyInstance] | |
| from typing import Iterable | |
| from functools import reduce | |
| M = Iterable | |
| def f(m1: M, m2): | |
| ... | |
| def g(ms: 'T[M]') -> None: | |
| reduce(f, ms) | |
| T = Iterable | |
| [out] | |
| [case testNamedTupleNew] | |
| # This is an eval test because there was a snag found only with full stubs | |
| from typing import NamedTuple | |
| Base = NamedTuple('Base', [('param', int)]) | |
| class Child(Base): | |
| def __new__(cls, param: int = 1) -> 'Child': | |
| return Base.__new__(cls, param) | |
| Base(param=10) | |
| Child(param=10) | |
| reveal_type(Child()) | |
| from collections import namedtuple | |
| X = namedtuple('X', ['a', 'b']) | |
| x = X(a=1, b='s') | |
| [out] | |
| _testNamedTupleNew.py:12: note: Revealed type is "tuple[int, fallback=_testNamedTupleNew.Child]" | |
| [case testNamedTupleTypeInheritanceSpecialCase] | |
| from typing import NamedTuple, Tuple | |
| from collections import namedtuple | |
| A = NamedTuple('A', [('param', int)]) | |
| B = namedtuple('B', ['param']) | |
| def accepts_named_tuple(arg: NamedTuple): | |
| reveal_type(arg._asdict()) | |
| reveal_type(arg._fields) | |
| reveal_type(arg._field_defaults) | |
| a = A(1) | |
| b = B(1) | |
| accepts_named_tuple(a) | |
| accepts_named_tuple(b) | |
| accepts_named_tuple(1) | |
| accepts_named_tuple((1, 2)) | |
| [out] | |
| _testNamedTupleTypeInheritanceSpecialCase.py:8: note: Revealed type is "dict[str, Any]" | |
| _testNamedTupleTypeInheritanceSpecialCase.py:9: note: Revealed type is "tuple[str, ...]" | |
| _testNamedTupleTypeInheritanceSpecialCase.py:10: note: Revealed type is "dict[str, Any]" | |
| _testNamedTupleTypeInheritanceSpecialCase.py:17: error: Argument 1 to "accepts_named_tuple" has incompatible type "int"; expected "NamedTuple" | |
| _testNamedTupleTypeInheritanceSpecialCase.py:18: error: Argument 1 to "accepts_named_tuple" has incompatible type "tuple[int, int]"; expected "NamedTuple" | |
| [case testNewAnalyzerBasicTypeshed_newsemanal] | |
| from typing import Dict, List, Tuple | |
| x: Dict[str, List[int]] | |
| reveal_type(x['test'][0]) | |
| [out] | |
| _testNewAnalyzerBasicTypeshed_newsemanal.py:4: note: Revealed type is "int" | |
| [case testNewAnalyzerTypedDictInStub_newsemanal] | |
| import stub | |
| reveal_type(stub.thing) | |
| [file stub.pyi] | |
| from typing_extensions import TypedDict | |
| class StuffDict(TypedDict): | |
| foo: str | |
| bar: int | |
| def thing(stuff: StuffDict) -> int: ... | |
| [out] | |
| _testNewAnalyzerTypedDictInStub_newsemanal.py:2: note: Revealed type is "def (stuff: TypedDict(stub.StuffDict, {'foo': str, 'bar': int})) -> int" | |
| [case testStrictEqualityAllowlist] | |
| # mypy: strict-equality | |
| {1} == frozenset({1}) | |
| frozenset({1}) == {1} | |
| frozenset({1}) == [1] # Error | |
| {1: 2}.keys() == {1} | |
| {1: 2}.keys() == frozenset({1}) | |
| {1: 2}.items() == {(1, 2)} | |
| {1: 2}.keys() == {'no'} # OK | |
| {1: 2}.values() == {2} # Error | |
| {1: 2}.keys() == [1] # OK | |
| [out] | |
| _testStrictEqualityAllowlist.py:5: error: Non-overlapping equality check (left operand type: "frozenset[int]", right operand type: "list[int]") | |
| _testStrictEqualityAllowlist.py:12: error: Non-overlapping equality check (left operand type: "dict_values[int, int]", right operand type: "set[int]") | |
| [case testUnreachableWithStdlibContextManagers] | |
| # mypy: warn-unreachable, strict-optional | |
| from contextlib import suppress | |
| # This test overlaps with some of the warn-unreachable tests in check-unreachable-code, | |
| # but 'open(...)' is a very common function so we want to make sure we don't regress | |
| # against it specifically | |
| def f_open() -> str: | |
| with open("foo.txt", "r") as f: | |
| return f.read() | |
| print("noop") | |
| # contextlib.suppress is less common, but it's a fairly prominent example of an | |
| # exception-suppressing context manager, so it'd be good to double-check. | |
| def f_suppresses() -> int: | |
| with suppress(Exception): | |
| return 3 | |
| print("noop") | |
| [out] | |
| _testUnreachableWithStdlibContextManagers.py:11: error: Statement is unreachable | |
| _testUnreachableWithStdlibContextManagers.py:15: error: Missing return statement | |
| [case testUnreachableWithStdlibContextManagersNoStrictOptional] | |
| # mypy: warn-unreachable, no-strict-optional | |
| from contextlib import suppress | |
| # When strict-optional is disabled, 'open' should still behave in the same way as before | |
| def f_open() -> str: | |
| with open("foo.txt", "r") as f: | |
| return f.read() | |
| print("noop") | |
| # ...but unfortunately, we can't | |
| def f_suppresses() -> int: | |
| with suppress(Exception): | |
| return 3 | |
| print("noop") | |
| [out] | |
| _testUnreachableWithStdlibContextManagersNoStrictOptional.py:9: error: Statement is unreachable | |
| _testUnreachableWithStdlibContextManagersNoStrictOptional.py:15: error: Statement is unreachable | |
| [case testIsInstanceAdHocIntersectionWithStrAndBytes] | |
| # mypy: warn-unreachable | |
| x: str | |
| if isinstance(x, bytes): | |
| reveal_type(x) | |
| y: str | |
| if isinstance(x, int): | |
| reveal_type(x) | |
| [out] | |
| _testIsInstanceAdHocIntersectionWithStrAndBytes.py:3: error: Subclass of "str" and "bytes" cannot exist: have distinct disjoint bases | |
| _testIsInstanceAdHocIntersectionWithStrAndBytes.py:4: error: Statement is unreachable | |
| _testIsInstanceAdHocIntersectionWithStrAndBytes.py:6: error: Subclass of "str" and "int" cannot exist: have distinct disjoint bases | |
| _testIsInstanceAdHocIntersectionWithStrAndBytes.py:7: error: Statement is unreachable | |
| [case testAsyncioFutureWait] | |
| # mypy: strict-optional | |
| from asyncio import Future, wait | |
| from typing import List | |
| async def foo() -> None: | |
| f = [] # type: List[Future[None]] | |
| await wait(f) | |
| [case testShadowTypingModule] | |
| 1 + '' | |
| [file typing.py] | |
| x = 0 | |
| 1 + '' | |
| [out] | |
| typing.py: error: This file shadows library module "typing" | |
| typing.py: note: A user-defined top-level module with name "typing" is not supported | |
| [case testNoPython3StubAvailable] | |
| import scribe | |
| from scribe import x | |
| import pytz | |
| [out] | |
| _testNoPython3StubAvailable.py:1: error: Cannot find implementation or library stub for module named "scribe" | |
| _testNoPython3StubAvailable.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports | |
| _testNoPython3StubAvailable.py:3: error: Library stubs not installed for "pytz" | |
| _testNoPython3StubAvailable.py:3: note: Hint: "python3 -m pip install types-pytz" | |
| _testNoPython3StubAvailable.py:3: note: (or run "mypy --install-types" to install all missing stub packages) | |
| [case testTypingOrderedDictAlias] | |
| from typing import OrderedDict | |
| x: OrderedDict[str, int] = OrderedDict({}) | |
| reveal_type(x) | |
| [out] | |
| _testTypingOrderedDictAlias.py:3: note: Revealed type is "collections.OrderedDict[str, int]" | |
| [case testTypingExtensionsOrderedDictAlias] | |
| from typing_extensions import OrderedDict | |
| x: OrderedDict[str, str] = OrderedDict({}) | |
| reveal_type(x) | |
| [out] | |
| _testTypingExtensionsOrderedDictAlias.py:3: note: Revealed type is "collections.OrderedDict[str, str]" | |
| [case testSpecialTypingProtocols] | |
| # flags: --warn-unreachable | |
| from typing import Awaitable, Hashable, Union, Tuple, List | |
| obj: Union[Tuple[int], List[int]] | |
| if isinstance(obj, Hashable): | |
| reveal_type(obj) | |
| if isinstance(obj, Awaitable): | |
| reveal_type(obj) | |
| [out] | |
| _testSpecialTypingProtocols.py:6: note: Revealed type is "tuple[int]" | |
| _testSpecialTypingProtocols.py:8: error: Statement is unreachable | |
| [case testTypeshedRecursiveTypesExample] | |
| from typing import List, Union | |
| Recursive = Union[str, List["Recursive"]] | |
| def foo(r: Recursive) -> None: | |
| if not isinstance(r, str): | |
| if r: | |
| foo(r[0]) | |
| if not isinstance(r, list): | |
| r.casefold() | |
| foo("") | |
| foo(list("")) | |
| foo(list((list(""), ""))) | |
| [out] | |
| [case testNarrowTypeForDictKeys] | |
| from typing import Dict, KeysView, Optional | |
| d: Dict[str, int] | |
| key: Optional[str] | |
| if key in d.keys(): | |
| reveal_type(key) | |
| else: | |
| reveal_type(key) | |
| kv: KeysView[str] | |
| k: Optional[str] | |
| if k in kv: | |
| reveal_type(k) | |
| else: | |
| reveal_type(k) | |
| [out] | |
| _testNarrowTypeForDictKeys.py:6: note: Revealed type is "str" | |
| _testNarrowTypeForDictKeys.py:8: note: Revealed type is "str | None" | |
| _testNarrowTypeForDictKeys.py:13: note: Revealed type is "str" | |
| _testNarrowTypeForDictKeys.py:15: note: Revealed type is "str | None" | |
| [case testTypeAliasWithNewStyleUnion] | |
| from typing import Literal, Type, TypeAlias, TypeVar | |
| Foo = Literal[1, 2] | |
| reveal_type(Foo) | |
| Bar1 = Foo | Literal[3] | |
| Bar2 = Literal[3] | Foo | |
| Bar3 = Foo | Foo | Literal[3] | Foo | |
| U1 = int | str | |
| U2 = U1 | bytes | |
| U3 = bytes | U1 | |
| Opt1 = None | int | |
| Opt2 = None | float | |
| Opt3 = int | None | |
| Opt4 = float | None | |
| A = Type[int] | str | |
| B: TypeAlias = Type[int] | str | |
| C = type[int] | str | |
| D = type[int] | str | |
| x: D | |
| reveal_type(x) | |
| E: TypeAlias = type[int] | str | |
| y: E | |
| reveal_type(y) | |
| F = list[type[int] | str] | |
| T = TypeVar("T", int, str) | |
| def foo(x: T) -> T: | |
| A = type[int] | str | |
| a: A | |
| return x | |
| [out] | |
| _testTypeAliasWithNewStyleUnion.py:4: note: Revealed type is "typing._SpecialForm" | |
| _testTypeAliasWithNewStyleUnion.py:24: note: Revealed type is "type[int] | str" | |
| _testTypeAliasWithNewStyleUnion.py:27: note: Revealed type is "type[int] | str" | |
| [case testTypeAliasWithNewStyleUnionInStub] | |
| import m | |
| a: m.A | |
| reveal_type(a) | |
| b: m.B | |
| reveal_type(b) | |
| c: m.C | |
| reveal_type(c) | |
| d: m.D | |
| reveal_type(d) | |
| e: m.E | |
| reveal_type(e) | |
| f: m.F | |
| reveal_type(f) | |
| [file m.pyi] | |
| from typing import Type, Callable, Literal | |
| from typing_extensions import TypeAlias | |
| Foo = Literal[1, 2] | |
| reveal_type(Foo) | |
| Bar1 = Foo | Literal[3] | |
| Bar2 = Literal[3] | Foo | |
| Bar3 = Foo | Foo | Literal[3] | Foo | |
| U1 = int | str | |
| U2 = U1 | bytes | |
| U3 = bytes | U1 | |
| Opt1 = None | int | |
| Opt2 = None | float | |
| Opt3 = int | None | |
| Opt4 = float | None | |
| A = Type[int] | str | |
| B: TypeAlias = Type[int] | str | |
| C = type[int] | str | |
| reveal_type(C) | |
| D: TypeAlias = type[int] | str | |
| E = str | type[int] | |
| F: TypeAlias = str | type[int] | |
| G = list[type[int] | str] | |
| H = list[str | type[int]] | |
| CU1 = int | Callable[[], str | bool] | |
| CU2: TypeAlias = int | Callable[[], str | bool] | |
| CU3 = int | Callable[[str | bool], str] | |
| CU4: TypeAlias = int | Callable[[str | bool], str] | |
| [out] | |
| m.pyi:5: note: Revealed type is "typing._SpecialForm" | |
| m.pyi:22: note: Revealed type is "types.UnionType[type[int], str]" | |
| _testTypeAliasWithNewStyleUnionInStub.py:3: note: Revealed type is "type[int] | str" | |
| _testTypeAliasWithNewStyleUnionInStub.py:5: note: Revealed type is "type[int] | str" | |
| _testTypeAliasWithNewStyleUnionInStub.py:7: note: Revealed type is "type[int] | str" | |
| _testTypeAliasWithNewStyleUnionInStub.py:9: note: Revealed type is "type[int] | str" | |
| _testTypeAliasWithNewStyleUnionInStub.py:11: note: Revealed type is "str | type[int]" | |
| _testTypeAliasWithNewStyleUnionInStub.py:13: note: Revealed type is "str | type[int]" | |
| [case testEnumNameWorkCorrectlyOn311] | |
| # flags: --python-version 3.11 | |
| import enum | |
| class E(enum.Enum): | |
| X = 1 | |
| Y = 2 | |
| @enum.property | |
| def foo(self) -> int: ... | |
| e: E | |
| reveal_type(e.name) | |
| reveal_type(e.value) | |
| reveal_type(E.X.name) | |
| reveal_type(e.foo) | |
| reveal_type(E.Y.foo) | |
| [out] | |
| _testEnumNameWorkCorrectlyOn311.py:11: note: Revealed type is "str" | |
| _testEnumNameWorkCorrectlyOn311.py:12: note: Revealed type is "Literal[1]? | Literal[2]?" | |
| _testEnumNameWorkCorrectlyOn311.py:13: note: Revealed type is "Literal['X']?" | |
| _testEnumNameWorkCorrectlyOn311.py:14: note: Revealed type is "int" | |
| _testEnumNameWorkCorrectlyOn311.py:15: note: Revealed type is "int" | |
| [case testTypedDictUnionGetFull] | |
| from typing import Dict | |
| from typing_extensions import TypedDict | |
| class TD(TypedDict, total=False): | |
| x: int | |
| y: int | |
| A = Dict[str, TD] | |
| x: A | |
| def foo(k: str) -> TD: | |
| reveal_type(x.get(k, {})) | |
| return x.get(k, {}) | |
| [out] | |
| _testTypedDictUnionGetFull.py:11: note: Revealed type is "TypedDict(_testTypedDictUnionGetFull.TD, {'x'?: int, 'y'?: int})" | |
| [case testTupleWithDifferentArgsPy310] | |
| # https://github.com/python/mypy/issues/11098 | |
| Correct1 = str | tuple[float, float, str] | |
| Correct2 = tuple[float] | str | |
| Correct3 = tuple[float, ...] | str | |
| Correct4 = tuple[float, str] | |
| Correct5 = tuple[float, ...] | |
| Correct6 = list[tuple[int, str]] | |
| c1: Correct1 | |
| c2: Correct2 | |
| c3: Correct3 | |
| c4: Correct4 | |
| c5: Correct5 | |
| c6: Correct6 | |
| reveal_type(c1) | |
| reveal_type(c2) | |
| reveal_type(c3) | |
| reveal_type(c4) | |
| reveal_type(c5) | |
| reveal_type(c6) | |
| RHSAlias1: type = tuple[int, int] | |
| RHSAlias2: type = tuple[int] | |
| RHSAlias3: type = tuple[int, ...] | |
| WrongTypeElement = str | tuple[float, 1] # Error | |
| WrongEllipsis = tuple[float, float, ...] | str # Error | |
| reveal_type(tuple[int, str]((1, "x"))) | |
| [out] | |
| _testTupleWithDifferentArgsPy310.py:14: note: Revealed type is "str | tuple[float, float, str]" | |
| _testTupleWithDifferentArgsPy310.py:15: note: Revealed type is "tuple[float] | str" | |
| _testTupleWithDifferentArgsPy310.py:16: note: Revealed type is "tuple[float, ...] | str" | |
| _testTupleWithDifferentArgsPy310.py:17: note: Revealed type is "tuple[float, str]" | |
| _testTupleWithDifferentArgsPy310.py:18: note: Revealed type is "tuple[float, ...]" | |
| _testTupleWithDifferentArgsPy310.py:19: note: Revealed type is "list[tuple[int, str]]" | |
| _testTupleWithDifferentArgsPy310.py:25: error: Invalid type: try using Literal[1] instead? | |
| _testTupleWithDifferentArgsPy310.py:26: error: Unexpected "..." | |
| _testTupleWithDifferentArgsPy310.py:28: note: Revealed type is "tuple[int, str]" | |
| [case testEnumIterMetaInference] | |
| import socket | |
| from enum import Enum | |
| from typing import Iterable, Iterator, Type, TypeVar | |
| _E = TypeVar("_E", bound=Enum) | |
| def enum_iter(cls: Type[_E]) -> Iterable[_E]: | |
| reveal_type(iter(cls)) | |
| reveal_type(next(iter(cls))) | |
| return iter(cls) | |
| for value in enum_iter(socket.SocketKind): | |
| reveal_type(value) | |
| [out] | |
| _testEnumIterMetaInference.py:8: note: Revealed type is "typing.Iterator[_E]" | |
| _testEnumIterMetaInference.py:9: note: Revealed type is "_E" | |
| _testEnumIterMetaInference.py:13: note: Revealed type is "socket.SocketKind" | |
| [case testEnumUnpackedViaMetaclass] | |
| from enum import Enum | |
| class FooEnum(Enum): | |
| A = 1 | |
| B = 2 | |
| C = 3 | |
| a, b, c = FooEnum | |
| reveal_type(a) | |
| reveal_type(b) | |
| reveal_type(c) | |
| [out] | |
| _testEnumUnpackedViaMetaclass.py:9: note: Revealed type is "_testEnumUnpackedViaMetaclass.FooEnum" | |
| _testEnumUnpackedViaMetaclass.py:10: note: Revealed type is "_testEnumUnpackedViaMetaclass.FooEnum" | |
| _testEnumUnpackedViaMetaclass.py:11: note: Revealed type is "_testEnumUnpackedViaMetaclass.FooEnum" | |
| [case testNativeIntTypes] | |
| # Spot check various native int operations with full stubs. | |
| from mypy_extensions import i64, i32 | |
| x: i64 = 0 | |
| y: int = x | |
| x = i64(0) | |
| y = int(x) | |
| i64() | |
| i64("12") | |
| i64("ab", 16) | |
| i64(1.2) | |
| float(i64(1)) | |
| i64(1) + i32(2) # Error | |
| reveal_type(x + y) | |
| reveal_type(y + x) | |
| a = [0] | |
| a[x] | |
| [out] | |
| _testNativeIntTypes.py:14: error: Unsupported operand types for + ("i64" and "i32") | |
| _testNativeIntTypes.py:15: note: Revealed type is "mypy_extensions.i64" | |
| _testNativeIntTypes.py:16: note: Revealed type is "mypy_extensions.i64" | |
| [case testStarUnpackNestedUnderscore] | |
| from typing import Tuple, Dict, List | |
| def crash() -> None: | |
| d: Dict[int, Tuple[str, int, str]] = {} | |
| k, (v1, *_) = next(iter(d.items())) | |
| def test1() -> None: | |
| vs: List[str] | |
| d: Dict[int, Tuple[str, int, int]] = {} | |
| k, (v1, *vs) = next(iter(d.items())) | |
| reveal_type(vs) | |
| def test2() -> None: | |
| d: Dict[int, Tuple[str, int, str]] = {} | |
| k, (v1, *vs) = next(iter(d.items())) | |
| reveal_type(vs) | |
| [out] | |
| _testStarUnpackNestedUnderscore.py:10: error: List item 0 has incompatible type "int"; expected "str" | |
| _testStarUnpackNestedUnderscore.py:10: error: List item 1 has incompatible type "int"; expected "str" | |
| _testStarUnpackNestedUnderscore.py:11: note: Revealed type is "list[str]" | |
| _testStarUnpackNestedUnderscore.py:16: note: Revealed type is "list[object]" | |
| [case testStrictEqualitywithParamSpec] | |
| # flags: --strict-equality | |
| from typing import Generic | |
| from typing_extensions import Concatenate, ParamSpec | |
| P = ParamSpec("P") | |
| class Foo(Generic[P]): ... | |
| class Bar(Generic[P]): ... | |
| def bad(foo: Foo[[int]], bar: Bar[[int]]) -> bool: | |
| return foo == bar | |
| def bad1(foo1: Foo[[int]], foo2: Foo[[str]]) -> bool: | |
| return foo1 == foo2 | |
| def bad2(foo1: Foo[[int, str]], foo2: Foo[[int, bytes]]) -> bool: | |
| return foo1 == foo2 | |
| def bad3(foo1: Foo[[int]], foo2: Foo[[int, int]]) -> bool: | |
| return foo1 == foo2 | |
| def good4(foo1: Foo[[int]], foo2: Foo[[int]]) -> bool: | |
| return foo1 == foo2 | |
| def good5(foo1: Foo[[int]], foo2: Foo[[bool]]) -> bool: | |
| return foo1 == foo2 | |
| def good6(foo1: Foo[[int, int]], foo2: Foo[[bool, bool]]) -> bool: | |
| return foo1 == foo2 | |
| def good7(foo1: Foo[[int]], foo2: Foo[P], *args: P.args, **kwargs: P.kwargs) -> bool: | |
| return foo1 == foo2 | |
| def good8(foo1: Foo[P], foo2: Foo[[int, str, bytes]], *args: P.args, **kwargs: P.kwargs) -> bool: | |
| return foo1 == foo2 | |
| def good9(foo1: Foo[Concatenate[int, P]], foo2: Foo[[int, str, bytes]], *args: P.args, **kwargs: P.kwargs) -> bool: | |
| return foo1 == foo2 | |
| [out] | |
| _testStrictEqualitywithParamSpec.py:11: error: Non-overlapping equality check (left operand type: "Foo[[int]]", right operand type: "Bar[[int]]") | |
| _testStrictEqualitywithParamSpec.py:14: error: Non-overlapping equality check (left operand type: "Foo[[int]]", right operand type: "Foo[[str]]") | |
| _testStrictEqualitywithParamSpec.py:17: error: Non-overlapping equality check (left operand type: "Foo[[int, str]]", right operand type: "Foo[[int, bytes]]") | |
| _testStrictEqualitywithParamSpec.py:20: error: Non-overlapping equality check (left operand type: "Foo[[int]]", right operand type: "Foo[[int, int]]") | |
| [case testInferenceOfDunderDictOnClassObjects] | |
| class Foo: ... | |
| reveal_type(Foo.__dict__) | |
| reveal_type(Foo().__dict__) | |
| Foo.__dict__ = {} | |
| Foo().__dict__ = {} | |
| [out] | |
| _testInferenceOfDunderDictOnClassObjects.py:2: note: Revealed type is "types.MappingProxyType[str, Any]" | |
| _testInferenceOfDunderDictOnClassObjects.py:3: note: Revealed type is "dict[str, Any]" | |
| _testInferenceOfDunderDictOnClassObjects.py:4: error: Cannot assign to final attribute "__dict__" | |
| _testInferenceOfDunderDictOnClassObjects.py:4: error: Incompatible types in assignment (expression has type "dict[Never, Never]", variable has type "MappingProxyType[str, Any]") | |
| [case testTypeVarTuple] | |
| # flags: --python-version=3.11 | |
| from typing import Any, Callable, Unpack, TypeVarTuple | |
| Ts = TypeVarTuple("Ts") | |
| def foo(callback: Callable[[], Any]) -> None: | |
| call(callback) | |
| def call(callback: Callable[[Unpack[Ts]], Any], *args: Unpack[Ts]) -> Any: | |
| ... | |
| [case testTypeVarTupleTypingExtensions] | |
| from typing_extensions import Unpack, TypeVarTuple | |
| from typing import Any, Callable | |
| Ts = TypeVarTuple("Ts") | |
| def foo(callback: Callable[[], Any]) -> None: | |
| call(callback) | |
| def call(callback: Callable[[Unpack[Ts]], Any], *args: Unpack[Ts]) -> Any: | |
| ... | |
| [case testDataclassReplace] | |
| from dataclasses import dataclass, replace | |
| @dataclass | |
| class A: | |
| x: int | |
| a = A(x=42) | |
| a2 = replace(a, x=42) | |
| reveal_type(a2) | |
| a2 = replace() | |
| a2 = replace(a, x='spam') | |
| a2 = replace(a, x=42, q=42) | |
| [out] | |
| _testDataclassReplace.py:9: note: Revealed type is "_testDataclassReplace.A" | |
| _testDataclassReplace.py:10: error: Too few arguments for "replace" | |
| _testDataclassReplace.py:11: error: Argument "x" to "replace" of "A" has incompatible type "str"; expected "int" | |
| _testDataclassReplace.py:12: error: Unexpected keyword argument "q" for "replace" of "A" | |
| [case testGenericInferenceWithTuple] | |
| from typing import TypeVar, Callable, Tuple | |
| T = TypeVar("T") | |
| def f(x: Callable[..., T]) -> T: | |
| return x() | |
| x: Tuple[str, ...] = f(tuple) | |
| [out] | |
| [case testGenericInferenceWithDataclass] | |
| from typing import Any, Collection, List | |
| from dataclasses import dataclass, field | |
| class Foo: | |
| pass | |
| @dataclass | |
| class A: | |
| items: Collection[Foo] = field(default_factory=list) | |
| [out] | |
| [case testGenericInferenceWithItertools] | |
| from typing import TypeVar, Tuple | |
| from itertools import groupby | |
| K = TypeVar("K") | |
| V = TypeVar("V") | |
| def fst(kv: Tuple[K, V]) -> K: | |
| k, v = kv | |
| return k | |
| pairs = [(len(s), s) for s in ["one", "two", "three"]] | |
| grouped = groupby(pairs, key=fst) | |
| [out] | |
| [case testDataclassReplaceOptional] | |
| from dataclasses import dataclass, replace | |
| from typing import Optional | |
| @dataclass | |
| class A: | |
| x: Optional[int] | |
| a = A(x=42) | |
| reveal_type(a) | |
| a2 = replace(a, x=None) # OK | |
| reveal_type(a2) | |
| [out] | |
| _testDataclassReplaceOptional.py:9: note: Revealed type is "_testDataclassReplaceOptional.A" | |
| _testDataclassReplaceOptional.py:11: note: Revealed type is "_testDataclassReplaceOptional.A" | |
| [case testDataclassStrictOptionalAlwaysSet] | |
| from dataclasses import dataclass | |
| from typing import Callable, Optional | |
| @dataclass | |
| class Description: | |
| name_fn: Callable[[Optional[int]], Optional[str]] | |
| def f(d: Description) -> None: | |
| reveal_type(d.name_fn) | |
| [out] | |
| _testDataclassStrictOptionalAlwaysSet.py:9: note: Revealed type is "def (int | None) -> str | None" | |
| [case testPEP695VarianceInference] | |
| # flags: --python-version=3.12 | |
| from typing import Callable, Final | |
| class Job[_R_co]: | |
| def __init__(self, target: Callable[[], _R_co]) -> None: | |
| self.target: Final = target | |
| def func( | |
| action: Job[int | None], | |
| a1: Job[int | None], | |
| a2: Job[int], | |
| a3: Job[None], | |
| ) -> None: | |
| action = a1 | |
| action = a2 | |
| action = a3 | |
| a2 = action # Error | |
| [out] | |
| _testPEP695VarianceInference.py:17: error: Incompatible types in assignment (expression has type "Job[None]", variable has type "Job[int]") | |
| [case testPEP695TypeAliasWithDifferentTargetTypes] | |
| # flags: --python-version=3.12 | |
| from typing import Any, Callable, List, Literal, TypedDict, overload, TypeAlias, TypeVar, Never | |
| class C[T]: pass | |
| class O[T]: | |
| @overload | |
| def __init__(self) -> None: ... | |
| @overload | |
| def __init__(self, x: int) -> None: ... | |
| def __init__(self, x: int = 0) -> None: | |
| pass | |
| class TD(TypedDict): | |
| x: int | |
| S = TypeVar("S") | |
| A = list[S] | |
| B: TypeAlias = list[S] | |
| type A1 = type[int] | |
| type A2 = type[int] | None | |
| type A3 = None | type[int] | |
| type A4 = type[Any] | |
| type A5 = type[C] | None | |
| type A6 = None | type[C] | |
| type A7 = type[O] | None | |
| type A8 = None | type[O] | |
| type B1[**P, R] = Callable[P, R] | None | |
| type B2[**P, R] = None | Callable[P, R] | |
| type B3 = Callable[[str], int] | |
| type B4 = Callable[..., int] | |
| type C1 = A1 | None | |
| type C2 = None | A1 | |
| type D1 = Any | None | |
| type D2 = None | Any | |
| type E1 = List[int] | |
| type E2 = List[int] | None | |
| type E3 = None | List[int] | |
| type F1 = Literal[1] | |
| type F2 = Literal['x'] | None | |
| type F3 = None | Literal[True] | |
| type G1 = tuple[int, Any] | |
| type G2 = tuple[int, Any] | None | |
| type G3 = None | tuple[int, Any] | |
| type H1 = TD | |
| type H2 = TD | None | |
| type H3 = None | TD | |
| type I1 = C[int] | |
| type I2 = C[Any] | None | |
| type I3 = None | C[TD] | |
| type I4 = O[int] | None | |
| type I5 = None | O[int] | |
| type J1[T] = T | None | |
| type J2[T] = None | T | |
| type J3[*Ts] = tuple[*Ts] | |
| type J4[T] = J1[T] | None | |
| type J5[T] = None | J1[T] | |
| type J6[*Ts] = J3[*Ts] | None | |
| type K1 = A[int] | None | |
| type K2 = None | A[int] | |
| type K3 = B[int] | None | |
| type K4 = None | B[int] | |
| type L1 = Never | |
| type L2 = list[Never] | |
| [case testPEP695VarianceInferenceSpecialCaseWithTypeshed] | |
| # flags: --python-version=3.12 | |
| class C1[T1, T2](list[T1]): | |
| def m(self, a: T2) -> None: ... | |
| def func1(p: C1[int, object]): | |
| x: C1[int, int] = p | |
| class C2[T1, T2, T3](dict[T2, T3]): | |
| def m(self, a: T1) -> None: ... | |
| def func2(p: C2[object, int, int]): | |
| x: C2[int, int, int] = p | |
| class C3[T1, T2](tuple[T1, ...]): | |
| def m(self, a: T2) -> None: ... | |
| def func3(p: C3[int, object]): | |
| x: C3[int, int] = p | |
| [case testDynamicClassAttribute] | |
| # Some things that can break if DynamicClassAttribute isn't handled properly | |
| from types import DynamicClassAttribute | |
| from enum import Enum | |
| class TestClass: | |
| @DynamicClassAttribute | |
| def name(self) -> str: ... | |
| class TestClass2(TestClass, Enum): ... | |
| class Status(Enum): | |
| ABORTED = -1 | |
| def imperfect(status: Status) -> str: | |
| return status.name.lower() | |
| [case testUnpackIteratorBuiltins] | |
| # Regression test for https://github.com/python/mypy/issues/18320 | |
| # Caused by https://github.com/python/typeshed/pull/12851 | |
| x = [1, 2] | |
| reveal_type([*reversed(x)]) | |
| reveal_type([*map(str, x)]) | |
| [out] | |
| _testUnpackIteratorBuiltins.py:4: note: Revealed type is "list[int]" | |
| _testUnpackIteratorBuiltins.py:5: note: Revealed type is "list[str]" | |
| [case testReturnFallbackInferenceDict] | |
| # Requires full dict stubs. | |
| from typing import Dict, Mapping, TypeVar, Union | |
| K = TypeVar("K") | |
| V = TypeVar("V") | |
| K2 = TypeVar("K2") | |
| V2 = TypeVar("V2") | |
| def func(one: Dict[K, V], two: Mapping[K2, V2]) -> Dict[Union[K, K2], Union[V, V2]]: | |
| ... | |
| def caller(arg1: Mapping[K, V], arg2: Mapping[K2, V2]) -> Dict[Union[K, K2], Union[V, V2]]: | |
| _arg1 = arg1 if isinstance(arg1, dict) else dict(arg1) | |
| return func(_arg1, arg2) | |
| [case testStrictEqualityWithList] | |
| # flags: --strict-equality | |
| def f(x: int, y: list[str]): | |
| x in y | |
| [out] | |
| _testStrictEqualityWithList.py:3: error: Non-overlapping container check (element type: "int", container item type: "str") | |
| [case testDictOrUnionEdgeCases] | |
| from typing import Mapping, Sequence, Union | |
| d: dict[str, list[str]] | |
| m: Mapping[str, Sequence[str]] = d | d | |
| A = dict[str, Union[A, int]] | |
| d1: A | |
| d2: A | |
| d3: A = d1 | d2 | |
| reveal_type(d1 | d2) | |
| [out] | |
| _testDictOrUnionEdgeCases.py:10: note: Revealed type is "dict[str, dict[str, ... | int] | int]" | |
| [case testNarrowingMappingAndAbstractSet] | |
| # flags: --strict-equality --warn-unreachable | |
| from typing import Mapping, AbstractSet | |
| def f1(x: Mapping[str, int], y: dict[str, int]) -> None: | |
| if isinstance(x, dict): | |
| reveal_type(x) | |
| if x == y: | |
| reveal_type(x) | |
| reveal_type(y) | |
| if x == {}: | |
| reveal_type(x) | |
| def f2(x: AbstractSet[int], y: set[int]) -> None: | |
| if isinstance(x, set): | |
| reveal_type(x) | |
| if x == y: | |
| reveal_type(x) | |
| reveal_type(y) | |
| if x == set(): | |
| reveal_type(x) | |
| def f3(x: frozenset[int], y: set[int]): | |
| if x == y: | |
| reveal_type(x) | |
| reveal_type(y) | |
| def f4(x: dict[str, int], y: set[str]): | |
| if x.keys() == y: | |
| reveal_type(x) | |
| reveal_type(y) | |
| z = x.keys() | |
| if z == y: | |
| reveal_type(z) | |
| reveal_type(y) | |
| [out] | |
| _testNarrowingMappingAndAbstractSet.py:6: note: Revealed type is "dict[Any, Any]" | |
| _testNarrowingMappingAndAbstractSet.py:9: note: Revealed type is "typing.Mapping[str, int]" | |
| _testNarrowingMappingAndAbstractSet.py:10: note: Revealed type is "dict[str, int]" | |
| _testNarrowingMappingAndAbstractSet.py:13: note: Revealed type is "typing.Mapping[str, int]" | |
| _testNarrowingMappingAndAbstractSet.py:17: note: Revealed type is "set[Any]" | |
| _testNarrowingMappingAndAbstractSet.py:20: note: Revealed type is "typing.AbstractSet[int]" | |
| _testNarrowingMappingAndAbstractSet.py:21: note: Revealed type is "set[int]" | |
| _testNarrowingMappingAndAbstractSet.py:24: note: Revealed type is "typing.AbstractSet[int]" | |
| _testNarrowingMappingAndAbstractSet.py:28: note: Revealed type is "frozenset[int]" | |
| _testNarrowingMappingAndAbstractSet.py:29: note: Revealed type is "set[int]" | |
| _testNarrowingMappingAndAbstractSet.py:33: note: Revealed type is "dict[str, int]" | |
| _testNarrowingMappingAndAbstractSet.py:34: note: Revealed type is "set[str]" | |
| _testNarrowingMappingAndAbstractSet.py:38: note: Revealed type is "_collections_abc.dict_keys[str, int]" | |
| _testNarrowingMappingAndAbstractSet.py:39: note: Revealed type is "set[str]" | |
| [case testNativeParserTStringRequiresPython314] | |
| # flags: --python-version=3.13 --native-parser --ignore-missing-imports | |
| x = t"hello {1}" | |
| reveal_type(x) | |
| [out] | |
| _testNativeParserTStringRequiresPython314.py:2: error: T-strings: requires Python 3.14 or newer (current target: Python 3.13) | |
| _testNativeParserTStringRequiresPython314.py:3: note: Revealed type is "Any" | |
| [case testNativeParserTStringRequiresPython314InStub] | |
| # flags: --python-version=3.13 --native-parser --ignore-missing-imports | |
| import m | |
| [file m.pyi] | |
| x: object | |
| def f() -> object: ... | |
| y = t"hello {1}" | |
| [out] | |
| m.pyi:3: error: T-strings: requires Python 3.14 or newer (current target: Python 3.13) | |
| [case testNativeParserStarUnpackRequiresPython311] | |
| # flags: --python-version=3.10 --native-parser | |
| from typing_extensions import TypeVarTuple, Unpack | |
| Ts = TypeVarTuple("Ts") | |
| def f(x: tuple[Unpack[Ts]]) -> None: ... | |
| def g(x: tuple[*Ts]) -> None: ... | |
| reveal_type(g) | |
| g((1, 2)) | |
| [out] | |
| _testNativeParserStarUnpackRequiresPython311.py:5: error: Star unpack syntax: requires Python 3.11 or newer (current target: Python 3.10) | |
| _testNativeParserStarUnpackRequiresPython311.py:6: note: Revealed type is "def [Ts] (x: tuple[*Ts])" | |
| [case testNativeParserPEP695InStubNoVersionError] | |
| # flags: --python-version=3.11 --native-parser --ignore-missing-imports | |
| import m | |
| reveal_type(m.f) | |
| [file m.pyi] | |
| class C[T]: ... | |
| def f[T](x: T) -> T: ... | |
| type Alias[T] = list[T] | |
| def g[T = int](x: T) -> T: ... | |
| [out] | |
| _testNativeParserPEP695InStubNoVersionError.py:3: note: Revealed type is "def [T] (x: T) -> T" |