| -- 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 testReversed] | |
| from typing import Reversible | |
| class A(Reversible): | |
| def __iter__(self): return iter('oof') | |
| def __reversed__(self): return iter('foo') | |
| print(list(reversed(range(5)))) | |
| print(list(reversed([1,2,3]))) | |
| print(list(reversed('abc'))) | |
| print(list(reversed(A()))) | |
| [out] | |
| -- Escape bracket at line beginning | |
| \[4, 3, 2, 1, 0] | |
| \[3, 2, 1] | |
| \['c', 'b', 'a'] | |
| \['f', 'o', 'o'] | |
| [case testIntAndFloatConversion] | |
| from typing import SupportsInt, SupportsFloat | |
| class A(SupportsInt): | |
| def __int__(self): return 5 | |
| class B(SupportsFloat): | |
| def __float__(self): return 1.2 | |
| print(int(1)) | |
| print(int(6.2)) | |
| print(int('3')) | |
| print(int(b'4')) | |
| print(int(A())) | |
| print(float(-9)) | |
| print(float(B())) | |
| [out] | |
| 1 | |
| 6 | |
| 3 | |
| 4 | |
| 5 | |
| -9.0 | |
| 1.2 | |
| [case testAbs] | |
| from typing import SupportsAbs | |
| class A(SupportsAbs[float]): | |
| def __abs__(self) -> float: return 5.5 | |
| print(abs(-1)) | |
| print(abs(-1.2)) | |
| print(abs(A())) | |
| [out] | |
| 1 | |
| 1.2 | |
| 5.5 | |
| [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 testRound] | |
| from typing import SupportsRound | |
| class A(SupportsRound): | |
| def __round__(self, ndigits=0): return 'x%d' % ndigits | |
| print(round(1.6)) | |
| print(round(A())) | |
| print(round(A(), 2)) | |
| [out] | |
| 2 | |
| x0 | |
| x2 | |
| [case testCallMethodViaTypeObject] | |
| import typing | |
| print(list.__add__([1, 2], [3, 4])) | |
| [out] | |
| \[1, 2, 3, 4] | |
| [case testInheritedClassAttribute] | |
| import typing | |
| class A: | |
| x = 1 | |
| def f(self: typing.Optional["A"]) -> None: print('f') | |
| class B(A): | |
| pass | |
| B.f(None) | |
| print(B.x) | |
| [out] | |
| f | |
| 1 | |
| [case testModuleAttributes] | |
| import math | |
| import typing | |
| print(math.__name__) | |
| print(type(math.__dict__)) | |
| print(type(math.__doc__ or '')) | |
| print(math.__class__) | |
| [out] | |
| math | |
| <class 'dict'> | |
| <class 'str'> | |
| <class 'module'> | |
| [case testSpecialAttributes] | |
| import typing | |
| class A: | |
| """A docstring!""" | |
| print(A().__doc__) | |
| print(A().__class__) | |
| [out] | |
| A docstring! | |
| <class '__main__.A'> | |
| [case testFunctionAttributes] | |
| import typing | |
| ord.__class__ | |
| print(type(ord.__doc__ or '' + '')) | |
| print(ord.__name__) | |
| print(ord.__module__) | |
| [out] | |
| <class 'str'> | |
| ord | |
| builtins | |
| [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: No overload variant of "write" of "IO" matches argument type "bytes" | |
| _program.py:5: note: Possible overload variants: | |
| _program.py:5: note: def write(self, str, /) -> int | |
| _program.py:10: error: Argument 1 to "bin" has incompatible type "TextIO"; 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" 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" | |
| _program.py:2: note: Revealed type is "io.TextIOWrapper" | |
| _program.py:3: note: Revealed type is "io.BufferedReader" | |
| _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" | |
| _testOpenReturnTypeInferenceSpecialCases.py:2: note: Revealed type is "io.BufferedReader" | |
| _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" | |
| _program.py:4: note: Revealed type is "io.TextIOWrapper" | |
| _program.py:5: note: Revealed type is "io.BufferedReader" | |
| _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" | |
| _program.py:4: note: Revealed type is "io.TextIOWrapper" | |
| _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) -> 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 | |
| [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 "Callable[[VarArg(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[Union[_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 "Union[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[Union[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[Union[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] | |
| # flags: --new-type-inference | |
| 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:7: error: Argument 1 to "defaultdict" has incompatible type "Type[List[Any]]"; expected "Optional[Callable[[], str]]" | |
| _program.py:10: error: Invalid index type "str" for "defaultdict[int, str]"; expected type "int" | |
| _program.py:10: error: Incompatible types in assignment (expression has type "int", target has type "str") | |
| _program.py:20: error: Argument 1 to "tst" has incompatible type "defaultdict[str, List[<nothing>]]"; expected "defaultdict[int, List[<nothing>]]" | |
| _program.py:24: error: Invalid index type "str" for "MyDDict[Dict[<nothing>, <nothing>]]"; expected type "int" | |
| [case testNoSubcriptionOfStdlibCollections] | |
| # flags: --python-version 3.6 | |
| import collections | |
| from collections import Counter | |
| from typing import TypeVar | |
| collections.defaultdict[int, str]() | |
| Counter[int]() | |
| T = TypeVar('T') | |
| DDint = collections.defaultdict[T, int] | |
| d = DDint[str]() | |
| d[0] = 1 | |
| def f(d: collections.defaultdict[int, str]) -> None: | |
| ... | |
| [out] | |
| _program.py:6: error: "defaultdict" is not subscriptable | |
| _program.py:7: error: "Counter" is not subscriptable | |
| _program.py:10: error: "defaultdict" is not subscriptable | |
| _program.py:13: error: Invalid index type "int" for "defaultdict[str, int]"; expected type "str" | |
| _program.py:15: error: "defaultdict" is not subscriptable, use "typing.DefaultDict" instead | |
| [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[builtins.int]" | |
| _testCollectionsAliases.py:6: error: Invalid index type "str" for "Counter[int]"; expected type "int" | |
| _testCollectionsAliases.py:9: note: Revealed type is "collections.ChainMap[builtins.int, builtins.str]" | |
| _testCollectionsAliases.py:12: note: Revealed type is "collections.deque[builtins.int]" | |
| _testCollectionsAliases.py:15: note: Revealed type is "collections.Counter[builtins.int]" | |
| _testCollectionsAliases.py:18: note: Revealed type is "collections.ChainMap[builtins.int, builtins.str]" | |
| _testCollectionsAliases.py:21: note: Revealed type is "collections.deque[builtins.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 | |
| 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: Union[str, Pattern[str]], string: str, flags: Union[int, RegexFlag] = ...) -> Optional[Match[str]] | |
| _testReModuleBytes.py:9: note: def search(pattern: Union[bytes, Pattern[bytes]], string: Buffer, flags: Union[int, RegexFlag] = ...) -> Optional[Match[bytes]] | |
| _testReModuleBytes.py:13: error: Argument 1 to "search" has incompatible type "Pattern[bytes]"; expected "Union[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: Union[str, Pattern[str]], string: str, flags: Union[int, RegexFlag] = ...) -> Optional[Match[str]] | |
| _testReModuleString.py:9: note: def search(pattern: Union[bytes, Pattern[bytes]], string: Buffer, flags: Union[int, RegexFlag] = ...) -> Optional[Match[bytes]] | |
| _testReModuleString.py:13: error: Argument 1 to "search" has incompatible type "Pattern[str]"; expected "Union[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: builtins.int) -> contextlib._GeneratorContextManager[builtins.str]" | |
| _program.py:14: note: Revealed type is "def (*x: builtins.str) -> contextlib._GeneratorContextManager[builtins.int]" | |
| _program.py:16: error: Argument 1 to "f" has incompatible type "str"; expected "int" | |
| _program.py:17: note: Revealed type is "builtins.str" | |
| [case testTypedDictGet] | |
| # Test that TypedDict get plugin works with typeshed stubs | |
| from mypy_extensions import TypedDict | |
| class A: pass | |
| D = TypedDict('D', {'x': int, 'y': str}) | |
| d: D | |
| 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:6: note: Revealed type is "Union[builtins.int, None]" | |
| _testTypedDictGet.py:7: note: Revealed type is "Union[builtins.str, None]" | |
| _testTypedDictGet.py:8: note: Revealed type is "builtins.object" | |
| _testTypedDictGet.py:9: error: All overload variants of "get" of "Mapping" require at least one argument | |
| _testTypedDictGet.py:9: note: Possible overload variants: | |
| _testTypedDictGet.py:9: note: def get(self, str, /) -> object | |
| _testTypedDictGet.py:9: note: def [_T] get(self, str, /, default: object) -> object | |
| _testTypedDictGet.py:11: note: Revealed type is "builtins.object" | |
| [case testTypedDictMappingMethods] | |
| from mypy_extensions 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 "builtins.str" | |
| _testTypedDictMappingMethods.py:6: note: Revealed type is "typing.Iterator[builtins.str]" | |
| _testTypedDictMappingMethods.py:7: note: Revealed type is "builtins.int" | |
| _testTypedDictMappingMethods.py:8: note: Revealed type is "builtins.bool" | |
| _testTypedDictMappingMethods.py:9: note: Revealed type is "_collections_abc.dict_keys[builtins.str, builtins.object]" | |
| _testTypedDictMappingMethods.py:10: note: Revealed type is "_collections_abc.dict_items[builtins.str, builtins.object]" | |
| _testTypedDictMappingMethods.py:11: note: Revealed type is "_collections_abc.dict_values[builtins.str, builtins.object]" | |
| _testTypedDictMappingMethods.py:12: note: Revealed type is "TypedDict('_testTypedDictMappingMethods.Cell', {'value': builtins.int})" | |
| _testTypedDictMappingMethods.py:13: note: Revealed type is "builtins.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 "builtins.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 mypy_extensions import TypedDict | |
| from typing import Sized, 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:11: error: Incompatible types in assignment (expression has type "Point", variable has type "Iterable[int]") | |
| _testCanConvertTypedDictToAnySuperclassOfMapping.py:11: note: Following member(s) of "Point" have conflicts: | |
| _testCanConvertTypedDictToAnySuperclassOfMapping.py:11: note: Expected: | |
| _testCanConvertTypedDictToAnySuperclassOfMapping.py:11: note: def __iter__(self) -> Iterator[int] | |
| _testCanConvertTypedDictToAnySuperclassOfMapping.py:11: note: Got: | |
| _testCanConvertTypedDictToAnySuperclassOfMapping.py:11: 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 "builtins.str" | |
| _testAsyncioGatherPreciseType.py:10: note: Revealed type is "builtins.str" | |
| _testAsyncioGatherPreciseType.py:11: note: Revealed type is "asyncio.futures.Future[builtins.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 "builtins.str" | |
| _testNoCrashOnGenericUnionUnpacking.py:7: note: Revealed type is "builtins.str" | |
| _testNoCrashOnGenericUnionUnpacking.py:10: note: Revealed type is "Union[builtins.str, builtins.int]" | |
| _testNoCrashOnGenericUnionUnpacking.py:11: note: Revealed type is "Union[builtins.str, builtins.int]" | |
| _testNoCrashOnGenericUnionUnpacking.py:15: note: Revealed type is "Union[builtins.int, builtins.str]" | |
| _testNoCrashOnGenericUnionUnpacking.py:16: note: Revealed type is "Union[builtins.int, builtins.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 "Union[builtins.str, builtins.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 "builtins.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 "Union[str, Iterable[str]]") | |
| _testInvalidSlots.py:5: error: Invalid type for "__slots__" (actual type "Tuple[int, int]", expected type "Union[str, Iterable[str]]") | |
| _testInvalidSlots.py:7: error: Invalid type for "__slots__" (actual type "List[int]", expected type "Union[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 "builtins.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[builtins.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 "collections.OrderedDict[builtins.str, Any]" | |
| _testNamedTupleTypeInheritanceSpecialCase.py:9: note: Revealed type is "builtins.tuple[builtins.str, ...]" | |
| _testNamedTupleTypeInheritanceSpecialCase.py:10: note: Revealed type is "builtins.dict[builtins.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 "builtins.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': builtins.str, 'bar': builtins.int})) -> builtins.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'} # Error | |
| {1: 2}.values() == {2} # Error | |
| {1: 2}.keys() == [1] # Error | |
| [out] | |
| _testStrictEqualityAllowlist.py:5: error: Non-overlapping equality check (left operand type: "FrozenSet[int]", right operand type: "List[int]") | |
| _testStrictEqualityAllowlist.py:11: error: Non-overlapping equality check (left operand type: "dict_keys[int, int]", right operand type: "Set[str]") | |
| _testStrictEqualityAllowlist.py:12: error: Non-overlapping equality check (left operand type: "dict_values[int, int]", right operand type: "Set[int]") | |
| _testStrictEqualityAllowlist.py:13: error: Non-overlapping equality check (left operand type: "dict_keys[int, int]", right operand type: "List[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: would have incompatible method signatures | |
| _testIsInstanceAdHocIntersectionWithStrAndBytes.py:4: error: Statement is unreachable | |
| _testIsInstanceAdHocIntersectionWithStrAndBytes.py:6: error: Subclass of "str" and "int" cannot exist: would have incompatible method signatures | |
| _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] | |
| mypy: "tmp/typing.py" shadows library module "typing" | |
| note: A user-defined top-level module with name "typing" is not supported | |
| [case testIgnoreImportIfNoPython3StubAvailable] | |
| # flags: --ignore-missing-imports | |
| import scribe # No Python 3 stubs available for scribe | |
| from scribe import x | |
| import maxminddb # Python 3 stubs available for maxminddb | |
| import foobar_asdf | |
| import jack # This has a stubs package but was never bundled with mypy, so ignoring works | |
| [out] | |
| _testIgnoreImportIfNoPython3StubAvailable.py:4: error: Library stubs not installed for "maxminddb" | |
| _testIgnoreImportIfNoPython3StubAvailable.py:4: note: Hint: "python3 -m pip install types-maxminddb" | |
| _testIgnoreImportIfNoPython3StubAvailable.py:4: note: (or run "mypy --install-types" to install all missing stub packages) | |
| _testIgnoreImportIfNoPython3StubAvailable.py:4: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports | |
| [case testNoPython3StubAvailable] | |
| import scribe | |
| from scribe import x | |
| import maxminddb | |
| [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 "maxminddb" | |
| _testNoPython3StubAvailable.py:3: note: Hint: "python3 -m pip install types-maxminddb" | |
| _testNoPython3StubAvailable.py:3: note: (or run "mypy --install-types" to install all missing stub packages) | |
| [case testTypingOrderedDictAlias] | |
| # flags: --python-version 3.7 | |
| from typing import OrderedDict | |
| x: OrderedDict[str, int] = OrderedDict({}) | |
| reveal_type(x) | |
| [out] | |
| _testTypingOrderedDictAlias.py:4: note: Revealed type is "collections.OrderedDict[builtins.str, builtins.int]" | |
| [case testTypingExtensionsOrderedDictAlias] | |
| from typing_extensions import OrderedDict | |
| x: OrderedDict[str, str] = OrderedDict({}) | |
| reveal_type(x) # Revealed type is "collections.OrderedDict[builtins.str, builtins.int]" | |
| [out] | |
| _testTypingExtensionsOrderedDictAlias.py:3: note: Revealed type is "collections.OrderedDict[builtins.str, builtins.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[builtins.int]" | |
| _testSpecialTypingProtocols.py:8: error: Statement is unreachable | |
| [case testEnumValueWithPlaceholderNodeType] | |
| # https://github.com/python/mypy/issues/11971 | |
| from enum import Enum | |
| from typing import Callable, Dict | |
| class Foo(Enum): | |
| Bar: Foo = Callable[[str], None] | |
| Baz: Foo = Callable[[Dict[str, "Missing"]], None] | |
| [out] | |
| _testEnumValueWithPlaceholderNodeType.py:5: error: Incompatible types in assignment (expression has type "object", variable has type "Foo") | |
| _testEnumValueWithPlaceholderNodeType.py:6: error: Incompatible types in assignment (expression has type "object", variable has type "Foo") | |
| _testEnumValueWithPlaceholderNodeType.py:6: error: Name "Missing" is not defined | |
| [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] | |
| # flags: --strict-optional | |
| 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:7: note: Revealed type is "builtins.str" | |
| _testNarrowTypeForDictKeys.py:9: note: Revealed type is "Union[builtins.str, None]" | |
| _testNarrowTypeForDictKeys.py:14: note: Revealed type is "builtins.str" | |
| _testNarrowTypeForDictKeys.py:16: note: Revealed type is "Union[builtins.str, None]" | |
| [case testTypeAliasWithNewStyleUnion] | |
| # flags: --python-version 3.10 | |
| 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:5: note: Revealed type is "typing._SpecialForm" | |
| _testTypeAliasWithNewStyleUnion.py:25: note: Revealed type is "Union[Type[builtins.int], builtins.str]" | |
| _testTypeAliasWithNewStyleUnion.py:28: note: Revealed type is "Union[Type[builtins.int], builtins.str]" | |
| [case testTypeAliasWithNewStyleUnionInStub] | |
| # flags: --python-version 3.7 | |
| 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 | |
| from typing_extensions import Literal, 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 "typing._SpecialForm" | |
| _testTypeAliasWithNewStyleUnionInStub.py:4: note: Revealed type is "Union[Type[builtins.int], builtins.str]" | |
| _testTypeAliasWithNewStyleUnionInStub.py:6: note: Revealed type is "Union[Type[builtins.int], builtins.str]" | |
| _testTypeAliasWithNewStyleUnionInStub.py:8: note: Revealed type is "Union[Type[builtins.int], builtins.str]" | |
| _testTypeAliasWithNewStyleUnionInStub.py:10: note: Revealed type is "Union[Type[builtins.int], builtins.str]" | |
| _testTypeAliasWithNewStyleUnionInStub.py:12: note: Revealed type is "Union[builtins.str, Type[builtins.int]]" | |
| _testTypeAliasWithNewStyleUnionInStub.py:14: note: Revealed type is "Union[builtins.str, Type[builtins.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 "builtins.str" | |
| _testEnumNameWorkCorrectlyOn311.py:12: note: Revealed type is "Union[Literal[1]?, Literal[2]?]" | |
| _testEnumNameWorkCorrectlyOn311.py:13: note: Revealed type is "Literal['X']?" | |
| _testEnumNameWorkCorrectlyOn311.py:14: note: Revealed type is "builtins.int" | |
| _testEnumNameWorkCorrectlyOn311.py:15: note: Revealed type is "builtins.int" | |
| [case testTypeAliasNotSupportedWithNewStyleUnion] | |
| # flags: --python-version 3.9 | |
| from typing_extensions import TypeAlias | |
| A = type[int] | str | |
| B = str | type[int] | |
| C = str | int | |
| D: TypeAlias = str | int | |
| [out] | |
| _testTypeAliasNotSupportedWithNewStyleUnion.py:3: error: Invalid type alias: expression is not a valid type | |
| _testTypeAliasNotSupportedWithNewStyleUnion.py:3: error: Value of type "Type[type]" is not indexable | |
| _testTypeAliasNotSupportedWithNewStyleUnion.py:4: error: Invalid type alias: expression is not a valid type | |
| _testTypeAliasNotSupportedWithNewStyleUnion.py:4: error: Value of type "Type[type]" is not indexable | |
| _testTypeAliasNotSupportedWithNewStyleUnion.py:5: error: Invalid type alias: expression is not a valid type | |
| _testTypeAliasNotSupportedWithNewStyleUnion.py:5: error: Unsupported left operand type for | ("Type[str]") | |
| _testTypeAliasNotSupportedWithNewStyleUnion.py:6: error: Invalid type alias: expression is not a valid type | |
| _testTypeAliasNotSupportedWithNewStyleUnion.py:6: error: Unsupported left operand type for | ("Type[str]") | |
| [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'?: builtins.int, 'y'?: builtins.int})" | |
| [case testTupleWithDifferentArgsPy310] | |
| # https://github.com/python/mypy/issues/11098 | |
| # flags: --python-version 3.10 | |
| 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 | |
| # TODO: This should produce a fixed-length tuple | |
| reveal_type(tuple[int, str]((1, "x"))) | |
| [out] | |
| _testTupleWithDifferentArgsPy310.py:15: note: Revealed type is "Union[builtins.str, Tuple[builtins.float, builtins.float, builtins.str]]" | |
| _testTupleWithDifferentArgsPy310.py:16: note: Revealed type is "Union[Tuple[builtins.float], builtins.str]" | |
| _testTupleWithDifferentArgsPy310.py:17: note: Revealed type is "Union[builtins.tuple[builtins.float, ...], builtins.str]" | |
| _testTupleWithDifferentArgsPy310.py:18: note: Revealed type is "Tuple[builtins.float, builtins.str]" | |
| _testTupleWithDifferentArgsPy310.py:19: note: Revealed type is "builtins.tuple[builtins.float, ...]" | |
| _testTupleWithDifferentArgsPy310.py:20: note: Revealed type is "builtins.list[Tuple[builtins.int, builtins.str]]" | |
| _testTupleWithDifferentArgsPy310.py:26: error: Invalid type: try using Literal[1] instead? | |
| _testTupleWithDifferentArgsPy310.py:27: error: Unexpected "..." | |
| _testTupleWithDifferentArgsPy310.py:30: note: Revealed type is "builtins.tuple[builtins.object, ...]" | |
| [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`-1]" | |
| _testEnumIterMetaInference.py:9: note: Revealed type is "_E`-1" | |
| _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 "builtins.list[builtins.str]" | |
| _testStarUnpackNestedUnderscore.py:16: note: Revealed type is "builtins.list[builtins.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 good1(foo1: Foo[[int]], foo2: Foo[[str]]) -> bool: | |
| return foo1 == foo2 | |
| def good2(foo1: Foo[[int, str]], foo2: Foo[[int, bytes]]) -> bool: | |
| return foo1 == foo2 | |
| def good3(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]]") | |
| [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[builtins.str, Any]" | |
| _testInferenceOfDunderDictOnClassObjects.py:3: note: Revealed type is "builtins.dict[builtins.str, Any]" | |
| _testInferenceOfDunderDictOnClassObjects.py:4: error: Property "__dict__" defined in "type" is read-only | |
| _testInferenceOfDunderDictOnClassObjects.py:4: error: Incompatible types in assignment (expression has type "Dict[<nothing>, <nothing>]", variable has type "MappingProxyType[str, Any]") | |
| [case testTypeVarTuple] | |
| # flags: --enable-incomplete-feature=TypeVarTuple --enable-incomplete-feature=Unpack --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] | |
| # flags: --enable-incomplete-feature=TypeVarTuple --enable-incomplete-feature=Unpack | |
| 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] | |
| # flags: --new-type-inference | |
| 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] | |
| # flags: --new-type-inference | |
| 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] | |
| # flags: --new-type-inference | |
| 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] | |
| # flags: --strict-optional | |
| 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:10: note: Revealed type is "_testDataclassReplaceOptional.A" | |
| _testDataclassReplaceOptional.py:12: note: Revealed type is "_testDataclassReplaceOptional.A" |