| -- 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 = None # type: int | |
| f = None # type: 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) -> 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__ + '')) | |
| 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 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"; 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 "IO" has incompatible type "bytes"; expected "str" | |
| _program.py:4: error: "TextIO" 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 'typing.TextIO' | |
| _program.py:2: note: Revealed type is 'typing.TextIO' | |
| _program.py:3: note: Revealed type is 'typing.BinaryIO' | |
| _program.py:5: note: Revealed type is 'typing.IO[Any]' | |
| [case testOpenReturnTypeInferenceSpecialCases] | |
| reveal_type(open()) | |
| 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: error: Too few arguments for "open" | |
| _testOpenReturnTypeInferenceSpecialCases.py:1: note: Revealed type is 'typing.TextIO' | |
| _testOpenReturnTypeInferenceSpecialCases.py:2: note: Revealed type is 'typing.BinaryIO' | |
| _testOpenReturnTypeInferenceSpecialCases.py:3: note: Revealed type is 'typing.BinaryIO' | |
| _testOpenReturnTypeInferenceSpecialCases.py:5: note: Revealed type is 'typing.IO[Any]' | |
| [case testGenericPatterns] | |
| from typing import Pattern | |
| import re | |
| p = None # type: Pattern[str] | |
| p = re.compile('foo*') | |
| b = None # type: Pattern[bytes] | |
| b = re.compile(b'foo*') | |
| print(p.match('fooo').group(0)) | |
| [out] | |
| fooo | |
| [case testGenericMatch] | |
| from typing import Match | |
| import re | |
| def f(m: Match[bytes]) -> None: | |
| print(m.group(0)) | |
| f(re.match(b'x*', b'xxy')) | |
| [out] | |
| b'xx' | |
| [case testIntFloatDucktyping] | |
| x = None # type: 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 = None # type: float | |
| n = None # type: int | |
| n = abs(2) | |
| f = abs(2.2) | |
| abs(2.2) + 'x' | |
| [out] | |
| _program.py:6: error: Unsupported operand types for + ("float" and "str") | |
| [case testROperatorMethods] | |
| b = None # type: bytes | |
| s = None # type: 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 = None # type: B | |
| b = C() | |
| print(A() + b) | |
| [out] | |
| _program.py:9: 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-skip] | |
| # TODO: Fix this; this was broken at some point but not sure why. | |
| 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] | |
| _program.py:4: error: Unsupported operand types for + ("List[str]" and "int") | |
| [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 __add__(self, Tuple[Any, ...]) -> Tuple[Any, ...] | |
| [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 __add__(self, Tuple[Any, ...]) -> Tuple[Any, ...] | |
| [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[Any]]"; expected "Callable[[], str]" | |
| _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: Dict entry 0 has incompatible type "str": "List[<nothing>]"; expected "int": "List[<nothing>]" | |
| _program.py:23: error: Invalid index type "str" for "MyDDict[Dict[_KT, _VT]]"; expected type "int" | |
| [case testNoSubcriptionOfStdlibCollections] | |
| 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:5: error: "defaultdict" is not subscriptable | |
| _program.py:6: error: "Counter" is not subscriptable | |
| _program.py:9: error: "defaultdict" is not subscriptable | |
| _program.py:12: error: Invalid index type "int" for "defaultdict[str, int]"; expected type "str" | |
| _program.py:14: 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" | |
| _testDequeWrongCase.py:5: error: Module has no attribute "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 | |
| T = TypeVar('T') | |
| def sorted(x: Iterable[T], *, key: Callable[[T], object] = None) -> None: ... | |
| a = None # 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) | |
| re.search(bre, b'').groups() | |
| re.search(bre, u'') # Error | |
| re.search(bpat, b'').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] | |
| _program.py:7: error: Value of type variable "AnyStr" of "search" cannot be "object" | |
| _program.py:9: error: Cannot infer type argument 1 of "search" | |
| [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) | |
| re.search(sre, '').groups() | |
| re.search(sre, b'') # Error | |
| re.search(spat, '').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] | |
| _program.py:7: error: Value of type variable "AnyStr" of "search" cannot be "object" | |
| _program.py:9: error: Cannot infer type argument 1 of "search" | |
| [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 | |
| # TODO: Make it possible to use strict optional here | |
| 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')) | |
| d.get('z') | |
| d.get() | |
| s = '' | |
| reveal_type(d.get(s)) | |
| [out] | |
| _testTypedDictGet.py:7: note: Revealed type is 'builtins.int' | |
| _testTypedDictGet.py:8: note: Revealed type is 'builtins.str' | |
| _testTypedDictGet.py:9: error: TypedDict "D" has no key 'z' | |
| _testTypedDictGet.py:10: error: All overload variants of "get" of "Mapping" require at least one argument | |
| _testTypedDictGet.py:10: note: Possible overload variants: | |
| _testTypedDictGet.py:10: note: def get(self, k: str) -> object | |
| _testTypedDictGet.py:10: note: def [_T] get(self, k: str, default: object) -> object | |
| _testTypedDictGet.py:12: 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 'typing.AbstractSet[builtins.str*]' | |
| _testTypedDictMappingMethods.py:10: note: Revealed type is 'typing.AbstractSet[Tuple[builtins.str*, builtins.object*]]' | |
| _testTypedDictMappingMethods.py:11: note: Revealed type is 'typing.ValuesView[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 | |
| MyNamedTuple = NamedTuple('MyNamedTuple', [('parent', 'MyNamedTuple')]) # type: ignore | |
| def foo(mymap) -> 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] | |
| 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 module named 'nonexistent' | |
| _testMetaclassOpAccessAny.py:2: note: See https://mypy.readthedocs.io/en/latest/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] | |
| class A: | |
| __slots__ = 1 | |
| class B: | |
| __slots__ = (1, 2) | |
| [out] | |
| _testInvalidSlots.py:2: error: Incompatible types in assignment (expression has type "int", base class "object" defined the type as "Union[str, Iterable[str]]") | |
| _testInvalidSlots.py:4: error: Incompatible types in assignment (expression has type "Tuple[int, int]", base class "object" defined the type as "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: Argument 1 to "update" of "dict" has incompatible type "Dict[int, int]"; expected "Mapping[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 = None # type: 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 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 testStrictEqualityWhitelist] | |
| # 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] | |
| _testStrictEqualityWhitelist.py:5: error: Non-overlapping equality check (left operand type: "FrozenSet[int]", right operand type: "List[int]") | |
| _testStrictEqualityWhitelist.py:11: error: Non-overlapping equality check (left operand type: "KeysView[int]", right operand type: "Set[str]") | |
| _testStrictEqualityWhitelist.py:12: error: Non-overlapping equality check (left operand type: "ValuesView[int]", right operand type: "Set[int]") | |
| _testStrictEqualityWhitelist.py:13: error: Non-overlapping equality check (left operand type: "KeysView[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 |