blob: 7945fe552114cfb033d9ab787ae836a3eb3cf55f [file]
-- 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
-- Skipped because different typing package versions have different repr()s.
[case testAbstractBaseClasses-skip]
import re
from typing import Sized, Sequence, Iterator, Iterable, Mapping, AbstractSet
def check(o, t):
rep = re.sub('0x[0-9a-fA-F]+', '0x...', repr(o))
rep = rep.replace('sequenceiterator', 'str_iterator')
trep = str(t).replace('_abcoll.Sized', 'collections.abc.Sized')
print(rep, trep, isinstance(o, t))
def f():
check('x', Sized)
check([1], Sequence)
check({1:3}, Sequence)
check(iter('x'), Iterator)
check('x', Iterable)
check({}, Mapping)
check(set([1]), AbstractSet)
f()
[out]
'x' <class 'collections.abc.Sized'> True
[1] typing.Sequence True
{1: 3} typing.Sequence False
<str_iterator object at 0x...> typing.Iterator True
'x' typing.Iterable True
{} typing.Mapping True
{1} typing.AbstractSet True
[case testSized]
from typing import Sized
class A(Sized):
def __len__(self): return 5
print(len(A()))
[out]
5
[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]
-- Duplicate [ 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:5: error: Unsupported operand types for + ("int" and "str")
_program.py:7: 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 testClassDataAttribute]
import typing
class A:
x = 0
print(A.x)
A.x += 1
print(A.x)
[out]
0
1
[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 testFunctionDecorator]
from typing import TypeVar, cast
ftype = TypeVar('ftype')
def logged(f: ftype) -> ftype:
def g(*args, **kwargs):
print('enter', f.__name__)
r = f(*args, **kwargs)
print('exit', f.__name__)
return r
return cast(ftype, g)
@logged
def foo(s: str) -> str:
print('foo', s)
return s + '!'
print(foo('y'))
print(foo('x'))
[out]
enter foo
foo y
exit foo
y!
enter foo
foo x
exit foo
x!
[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: pass
print(object().__doc__)
print(A().__class__)
[out]
The most base type
<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 testStaticmethod]
import typing
class A:
@staticmethod
def f(x: str) -> int: return int(x)
print(A.f('12'))
print(A().f('34'))
[out]
12
34
[case testClassmethod]
import typing
class A:
@classmethod
def f(cls, x: str) -> int: return int(x)
print(A.f('12'))
print(A().f('34'))
[out]
12
34
[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 testArray]
import typing
import array
array.array('b', [1, 2])
[out]
[case testDictFromkeys]
import typing
d = dict.fromkeys('foo')
d['x'] = 2
d2 = dict.fromkeys([1, 2], b'')
d2[2] = b'foo'
[out]
[case testReadOnlyProperty]
class A:
x = 2
@property
def f(self) -> int:
return self.x + 1
print(A().f)
[out]
3
[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 testTypevarValues]
from typing import TypeVar
T = TypeVar('T', str, bytes)
def f(x: T) -> T:
if isinstance(x, str):
return 'foo'
else:
return b'bar'
print(f(''))
print(f(b''))
[out]
foo
b'bar'
[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
[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:4: error: IO[Any] has no attribute "foobar"
[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 testMultipleTypevarsWithValues]
from typing import TypeVar
T = TypeVar('T', int, str)
S = TypeVar('S', int, str)
def f(t: T, s: S) -> None:
t + s
[out]
_program.py:7: error: Unsupported operand types for + ("int" and "str")
_program.py:7: error: Unsupported operand types for + ("str" and "int")
[case testSystemExitCode]
import typing
print(SystemExit(5).code)
[out]
5
[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
s = b'foo' * 5 # Error
b = 5 * b'foo'
b = b'foo' * 5
s = 5 * 'foo'
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 > ("bytes" and "str")
_program.py:3: error: Unsupported operand types for > ("str" and "bytes")
_program.py:4: error: Unsupported operand types for > ("bytearray" and "str")
_program.py:5: error: Unsupported operand types for > ("str" and "bytearray")
[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 testListConcatenateWithIterable]
import typing
[1] + iter([2, 3])
[out]
_program.py:2: error: Unsupported operand types for + ("list" and Iterator[int])
[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 testSetUnion]
import typing
s = {'x', 'y'}
print('>', sorted(s.union('foo')))
[out]
> ['f', 'o', 'x', 'y']
[case testFromFuturePrintFunction]
from __future__ import print_function
print('a', 'b')
[out]
a b
[case testLenOfTuple]
import typing
print(len((1, 'x')))
[out]
2
[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
[out]
_program.py:2: error: Name '_T' 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[[StarArg(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 testNamedTuple]
import typing
from collections import namedtuple
X = namedtuple('X', ['a', 'b'])
x = X(a=1, b='s')
print(x.a, x.b)
[out]
1 s
[case testNamedTupleShortSyntax]
import typing
from collections import namedtuple
X = namedtuple('X', ' a b ')
x = X(a=1, b='s')
print(x.a, x.b)
[out]
1 s
[case testNamedTupleError]
import typing
from collections import namedtuple
X = namedtuple('X', ['a', 'b'])
x = X(a=1, b='s')
x.c
[out]
_program.py:5: error: "X" has no attribute "c"
[case testNamedTupleTupleOperations]
from typing import Iterable
from collections import namedtuple
X = namedtuple('X', ['a', 'b'])
def f(x: Iterable[int]) -> None: pass
x = X(a=1, b='s')
f(x)
print(len(x))
print(x.index(1))
print(x.count(1))
print(x + x)
[out]
2
0
1
(1, 's', 1, 's')
[case testNamedTupleWithTypes]
from typing import NamedTuple
N = NamedTuple('N', [('a', int), ('b', str)])
n = N(1, 'x')
print(n)
a, b = n
print(a, b)
print(n[0])
[out]
N(a=1, b='x')
1 x
1
[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 testAssignToComplexReal]
import typing
x = 4j
y = x.real
y = x # Error
x.real = 2.0 # Error
[out]
_program.py:4: error: Incompatible types in assignment (expression has type "complex", variable has type "float")
_program.py:5: error: Property "real" defined in "complex" is read-only
[case testComplexArithmetic]
import typing
print(5 + 8j)
print(3j * 2.0)
print(4J / 2.0)
[out]
(5+8j)
6j
2j
[case testComplexArithmetic2]
import typing
x = 5 + 8j
x = ''
y = 3j * 2.0
y = ''
[out]
_program.py:3: error: Incompatible types in assignment (expression has type "str", variable has type "complex")
_program.py:5: error: Incompatible types in assignment (expression has type "str", variable has type "complex")
[case testUnionTypeAlias]
from typing import Union
U = Union[int, str]
u = 1 # type: U
u = 1.1
[out]
_program.py:4: error: Incompatible types in assignment (expression has type "float", variable has type "Union[int, str]")
[case testTupleTypeAlias]
from typing import Tuple
A = Tuple[int, str]
u = 1, 'x' # type: A
u = 1
[out]
_program.py:4: error: Incompatible types in assignment (expression has type "int", variable has type "Tuple[int, str]")
[case testCallableTypeAlias]
from typing import Callable
A = Callable[[int], None]
def f(x: A) -> None:
x(1)
x('')
[out]
_program.py:5: error: Argument 1 has incompatible type "str"; expected "int"
[case testSuperNew]
from typing import Dict, Any
class MyType(type):
def __new__(cls, name: str, bases: tuple, namespace: Dict[str, Any]) -> type:
return super().__new__(cls, name + 'x', bases, namespace)
class A(metaclass=MyType): pass
print(type(A()).__name__)
[out]
Ax
[case testSequenceIndexAndCount]
from typing import Sequence
def f(x: Sequence[int]) -> None:
print(x.index(1))
print(x.count(1))
f([0, 0, 1, 1, 1])
[out]
2
3
[case testEscapeInTripleQuotedStrLiteral]
print('''\'''')
print(r"""\"""$""")
[out]
'
\"""$
[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 testOptional]
from typing import Optional
def f() -> Optional[int]: pass
x = f()
y = 1
y = x
[case testAppendToStarArg]
import typing
def f(*x: int) -> None:
x.append(1)
f(1)
[out]
_program.py:3: error: Tuple[int, ...] has no attribute "append"
[case testExit]
print('a')
exit(2)
print('b')
[out]
a
[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 testVariableLengthTuple]
from typing import Tuple
def p(t: Tuple[int, ...]) -> None:
for n in t:
print(n)
p((1, 3, 2))
[out]
1
3
2
[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: Unsupported operand types for + (Tuple[str, ...] and "int")
[case testMultiplyTupleByIntegerReverse]
n = 4
t = n * ('',)
t + 1
[out]
_program.py:3: error: Unsupported operand types for + (Tuple[str, ...] and "int")
[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: List item 1 has incompatible type "Tuple[str, str]"
_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 List[_T]; expected Callable[[], str]
_program.py:9: error: Invalid index type "str" for "dict"; expected type "int"
_program.py:9: error: Incompatible types in assignment (expression has type "int", target has type "str")
_program.py:19: error: List item 0 has incompatible type "Tuple[str, List[None]]"
_program.py:23: error: Invalid index type "str" for "dict"; expected type "int"
[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]
class A(type):
def __new__(cls, name, bases, namespace) -> 'type':
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
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: Type argument 1 of "search" has incompatible value "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: Type argument 1 of "search" has incompatible value "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]")