| 1 |
-- Test cases for type checking mypy programs using full stubs and running |
| 2 |
-- using CPython. |
| 3 |
-- |
| 4 |
-- These are mostly regression tests -- no attempt is made to make these |
| 5 |
-- complete. |
| 6 |
|
| 7 |
|
| 8 |
[case testHello] |
| 9 |
import typing |
| 10 |
print('hello, world') |
| 11 |
[out] |
| 12 |
hello, world |
| 13 |
|
| 14 |
[case testMiscStdlibFeatures] |
| 15 |
# Various legacy tests merged together to speed up test runtimes. |
| 16 |
|
| 17 |
def f(x: object) -> None: pass |
| 18 |
|
| 19 |
# testReversed |
| 20 |
from typing import Reversible |
| 21 |
class R(Reversible): |
| 22 |
def __iter__(self): return iter('oof') |
| 23 |
def __reversed__(self): return iter('foo') |
| 24 |
f(list(reversed(range(5)))) |
| 25 |
f(list(reversed([1,2,3]))) |
| 26 |
f(list(reversed('abc'))) |
| 27 |
f(list(reversed(R()))) |
| 28 |
|
| 29 |
# testIntAndFloatConversion |
| 30 |
from typing import SupportsInt, SupportsFloat |
| 31 |
class A(SupportsInt): |
| 32 |
def __int__(self): return 5 |
| 33 |
class B(SupportsFloat): |
| 34 |
def __float__(self): return 1.2 |
| 35 |
f(int(1)) |
| 36 |
f(int(6.2)) |
| 37 |
f(int('3')) |
| 38 |
f(int(b'4')) |
| 39 |
f(int(A())) |
| 40 |
f(float(-9)) |
| 41 |
f(float(B())) |
| 42 |
|
| 43 |
# testAbs |
| 44 |
from typing import SupportsAbs |
| 45 |
class Ab(SupportsAbs[float]): |
| 46 |
def __abs__(self) -> float: return 5.5 |
| 47 |
|
| 48 |
f(abs(-1)) |
| 49 |
f(abs(-1.2)) |
| 50 |
f(abs(Ab())) |
| 51 |
|
| 52 |
# testRound |
| 53 |
from typing import SupportsRound |
| 54 |
class Ro(SupportsRound): |
| 55 |
def __round__(self, ndigits=0): return 'x%d' % ndigits |
| 56 |
f(round(1.6)) |
| 57 |
f(round(Ro())) |
| 58 |
f(round(Ro(), 2)) |
| 59 |
|
| 60 |
# testCallMethodViaTypeObject |
| 61 |
list.__add__([1, 2], [3, 4]) |
| 62 |
|
| 63 |
# testInheritedClassAttribute |
| 64 |
import typing |
| 65 |
class AA: |
| 66 |
x = 1 |
| 67 |
def f(self: typing.Optional["AA"]) -> None: pass |
| 68 |
class BB(AA): |
| 69 |
pass |
| 70 |
BB.f(None) |
| 71 |
f(BB.x) |
| 72 |
|
| 73 |
# testSpecialAttributes |
| 74 |
class Doc: |
| 75 |
"""A docstring!""" |
| 76 |
f(Doc().__doc__) |
| 77 |
f(Doc().__class__) |
| 78 |
|
| 79 |
# testFunctionAttributes |
| 80 |
f(ord.__class__) |
| 81 |
f(type(ord.__doc__ or '' + '')) |
| 82 |
f(ord.__name__) |
| 83 |
f(ord.__module__) |
| 84 |
|
| 85 |
# testModuleAttributes |
| 86 |
import math |
| 87 |
f(type(__spec__)) |
| 88 |
f(math.__name__) |
| 89 |
f(math.__spec__.name) |
| 90 |
f(type(math.__dict__)) |
| 91 |
f(type(math.__doc__ or '')) |
| 92 |
f(type(math.__spec__).__name__) |
| 93 |
f(math.__class__) |
| 94 |
|
| 95 |
[case testAbs2] |
| 96 |
n: int |
| 97 |
f: float |
| 98 |
n = abs(1) |
| 99 |
abs(1) + 'x' # Error |
| 100 |
f = abs(1.1) |
| 101 |
abs(1.1) + 'x' # Error |
| 102 |
[out] |
| 103 |
_program.py:4: error: Unsupported operand types for + ("int" and "str") |
| 104 |
_program.py:6: error: Unsupported operand types for + ("float" and "str") |
| 105 |
|
| 106 |
[case testTypeAttributes] |
| 107 |
import typing |
| 108 |
print(str.__class__) |
| 109 |
print(type(str.__doc__)) |
| 110 |
print(str.__name__) |
| 111 |
print(str.__module__) |
| 112 |
print(str.__dict__ is not None) |
| 113 |
[out] |
| 114 |
<class 'type'> |
| 115 |
<class 'str'> |
| 116 |
str |
| 117 |
builtins |
| 118 |
True |
| 119 |
|
| 120 |
[case testBoolCompatibilityWithInt] |
| 121 |
import typing |
| 122 |
x = 0 |
| 123 |
x = True |
| 124 |
print(bool('x')) |
| 125 |
print(bool('')) |
| 126 |
[out] |
| 127 |
True |
| 128 |
False |
| 129 |
|
| 130 |
[case testCannotExtendBoolUnlessIgnored] |
| 131 |
class A(bool): pass |
| 132 |
class B(bool): pass # type: ignore |
| 133 |
[out] |
| 134 |
_program.py:1: error: Cannot inherit from final class "bool" |
| 135 |
|
| 136 |
[case testCallBuiltinTypeObjectsWithoutArguments] |
| 137 |
import typing |
| 138 |
print(int()) |
| 139 |
print(repr(str())) |
| 140 |
print(repr(bytes())) |
| 141 |
print(float()) |
| 142 |
print(bool()) |
| 143 |
[out] |
| 144 |
0 |
| 145 |
'' |
| 146 |
b'' |
| 147 |
0.0 |
| 148 |
False |
| 149 |
|
| 150 |
[case testIntegerDivision] |
| 151 |
import typing |
| 152 |
x = 1 / 2 |
| 153 |
x = 1.5 |
| 154 |
[out] |
| 155 |
|
| 156 |
[case testIntMethods] |
| 157 |
import typing |
| 158 |
print(int.from_bytes(b'ab', 'big')) |
| 159 |
n = 0 |
| 160 |
print(n.from_bytes(b'ac', 'big')) |
| 161 |
print(n.from_bytes([2, 3], 'big')) |
| 162 |
print(n.to_bytes(2, 'big')) |
| 163 |
[out] |
| 164 |
24930 |
| 165 |
24931 |
| 166 |
515 |
| 167 |
b'\x00\x00' |
| 168 |
|
| 169 |
[case testFloatMethods] |
| 170 |
import typing |
| 171 |
print(1.5.as_integer_ratio()) |
| 172 |
print(1.5.hex()) |
| 173 |
print(2.0.is_integer()) |
| 174 |
print(float.fromhex('0x1.8')) |
| 175 |
[out] |
| 176 |
(3, 2) |
| 177 |
0x1.8000000000000p+0 |
| 178 |
True |
| 179 |
1.5 |
| 180 |
|
| 181 |
[case testDictFromkeys] |
| 182 |
import typing |
| 183 |
d = dict.fromkeys('foo') |
| 184 |
d['x'] = 2 |
| 185 |
d2 = dict.fromkeys([1, 2], b'') |
| 186 |
d2[2] = b'foo' |
| 187 |
[out] |
| 188 |
|
| 189 |
[case testIsinstanceWithTuple] |
| 190 |
from typing import cast, Any |
| 191 |
x = cast(Any, (1, 'x')) |
| 192 |
if isinstance(x, tuple): |
| 193 |
print(x[0], x[1]) |
| 194 |
[out] |
| 195 |
1 x |
| 196 |
|
| 197 |
[case testAnyStr] |
| 198 |
from typing import AnyStr |
| 199 |
def f(x: AnyStr) -> AnyStr: |
| 200 |
if isinstance(x, str): |
| 201 |
return 'foo' |
| 202 |
else: |
| 203 |
return b'zar' |
| 204 |
print(f('')) |
| 205 |
print(f(b'')) |
| 206 |
[out] |
| 207 |
foo |
| 208 |
b'zar' |
| 209 |
|
| 210 |
[case testNameNotImportedFromTyping] |
| 211 |
import typing |
| 212 |
cast(int, 2) |
| 213 |
[out] |
| 214 |
_program.py:2: error: Name "cast" is not defined |
| 215 |
_program.py:2: note: Did you forget to import it from "typing"? (Suggestion: "from typing import cast") |
| 216 |
|
| 217 |
[case testBinaryIOType] |
| 218 |
from typing import BinaryIO |
| 219 |
def f(f: BinaryIO) -> None: |
| 220 |
f.write(b'foo') |
| 221 |
f.write(bytearray(b'foo')) |
| 222 |
[out] |
| 223 |
|
| 224 |
[case testIOTypes] |
| 225 |
from typing import IO |
| 226 |
import sys |
| 227 |
def txt(f: IO[str]) -> None: |
| 228 |
f.write('foo') |
| 229 |
f.write(b'foo') |
| 230 |
def bin(f: IO[bytes]) -> None: |
| 231 |
f.write(b'foo') |
| 232 |
f.write(bytearray(b'foo')) |
| 233 |
txt(sys.stdout) |
| 234 |
bin(sys.stdout) |
| 235 |
[out] |
| 236 |
_program.py:5: error: Argument 1 to "write" of "IO" has incompatible type "bytes"; expected "str" |
| 237 |
_program.py:10: error: Argument 1 to "bin" has incompatible type "TextIO | Any"; expected "IO[bytes]" |
| 238 |
|
| 239 |
[case testBuiltinOpen] |
| 240 |
f = open('x') |
| 241 |
f.write('x') |
| 242 |
f.write(b'x') |
| 243 |
f.foobar() |
| 244 |
[out] |
| 245 |
_program.py:3: error: Argument 1 to "write" of "_TextIOBase" has incompatible type "bytes"; expected "str" |
| 246 |
_program.py:4: error: "TextIOWrapper[_WrappedBuffer]" has no attribute "foobar" |
| 247 |
|
| 248 |
[case testOpenReturnTypeInference] |
| 249 |
reveal_type(open('x')) |
| 250 |
reveal_type(open('x', 'r')) |
| 251 |
reveal_type(open('x', 'rb')) |
| 252 |
mode = 'rb' |
| 253 |
reveal_type(open('x', mode)) |
| 254 |
[out] |
| 255 |
_program.py:1: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" |
| 256 |
_program.py:2: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" |
| 257 |
_program.py:3: note: Revealed type is "_io.BufferedReader[_io._BufferedReaderStream]" |
| 258 |
_program.py:5: note: Revealed type is "typing.IO[Any]" |
| 259 |
|
| 260 |
[case testOpenReturnTypeInferenceSpecialCases] |
| 261 |
reveal_type(open(mode='rb', file='x')) |
| 262 |
reveal_type(open(file='x', mode='rb')) |
| 263 |
mode = 'rb' |
| 264 |
reveal_type(open(mode=mode, file='r')) |
| 265 |
[out] |
| 266 |
_testOpenReturnTypeInferenceSpecialCases.py:1: note: Revealed type is "_io.BufferedReader[_io._BufferedReaderStream]" |
| 267 |
_testOpenReturnTypeInferenceSpecialCases.py:2: note: Revealed type is "_io.BufferedReader[_io._BufferedReaderStream]" |
| 268 |
_testOpenReturnTypeInferenceSpecialCases.py:4: note: Revealed type is "typing.IO[Any]" |
| 269 |
|
| 270 |
[case testPathOpenReturnTypeInference] |
| 271 |
from pathlib import Path |
| 272 |
p = Path("x") |
| 273 |
reveal_type(p.open()) |
| 274 |
reveal_type(p.open('r')) |
| 275 |
reveal_type(p.open('rb')) |
| 276 |
mode = 'rb' |
| 277 |
reveal_type(p.open(mode)) |
| 278 |
[out] |
| 279 |
_program.py:3: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" |
| 280 |
_program.py:4: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" |
| 281 |
_program.py:5: note: Revealed type is "_io.BufferedReader[_io._BufferedReaderStream]" |
| 282 |
_program.py:7: note: Revealed type is "typing.IO[Any]" |
| 283 |
|
| 284 |
[case testPathOpenReturnTypeInferenceSpecialCases] |
| 285 |
from pathlib import Path |
| 286 |
p = Path("x") |
| 287 |
reveal_type(p.open(mode='r', errors='replace')) |
| 288 |
reveal_type(p.open(errors='replace', mode='r')) |
| 289 |
mode = 'r' |
| 290 |
reveal_type(p.open(mode=mode, errors='replace')) |
| 291 |
[out] |
| 292 |
_program.py:3: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" |
| 293 |
_program.py:4: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]" |
| 294 |
_program.py:6: note: Revealed type is "typing.IO[Any]" |
| 295 |
|
| 296 |
[case testGenericPatterns] |
| 297 |
from typing import Pattern |
| 298 |
import re |
| 299 |
p: Pattern[str] |
| 300 |
p = re.compile('foo*') |
| 301 |
b: Pattern[bytes] |
| 302 |
b = re.compile(b'foo*') |
| 303 |
m = p.match('fooo') |
| 304 |
assert m |
| 305 |
print(m.group(0)) |
| 306 |
[out] |
| 307 |
fooo |
| 308 |
|
| 309 |
[case testGenericMatch] |
| 310 |
from typing import Match, Optional |
| 311 |
import re |
| 312 |
def f(m: Optional[Match[bytes]]) -> None: |
| 313 |
assert m |
| 314 |
print(m.group(0)) |
| 315 |
f(re.match(b'x*', b'xxy')) |
| 316 |
[out] |
| 317 |
b'xx' |
| 318 |
|
| 319 |
[case testIntFloatDucktyping] |
| 320 |
x: float |
| 321 |
x = 2.2 |
| 322 |
x = 2 |
| 323 |
def f(x: float) -> None: pass |
| 324 |
f(1.1) |
| 325 |
f(1) |
| 326 |
[out] |
| 327 |
|
| 328 |
[case testsFloatOperations] |
| 329 |
import typing |
| 330 |
print(1.5 + 1.5) |
| 331 |
print(1.5 + 1) |
| 332 |
[out] |
| 333 |
3.0 |
| 334 |
2.5 |
| 335 |
|
| 336 |
[case testMathFunctionWithIntArgument] |
| 337 |
import typing |
| 338 |
import math |
| 339 |
math.sin(2) |
| 340 |
math.sin(2.2) |
| 341 |
|
| 342 |
[case testAbsReturnType] |
| 343 |
f: float |
| 344 |
n: int |
| 345 |
n = abs(2) |
| 346 |
f = abs(2.2) |
| 347 |
abs(2.2) + 'x' |
| 348 |
[out] |
| 349 |
_program.py:5: error: Unsupported operand types for + ("float" and "str") |
| 350 |
|
| 351 |
[case testROperatorMethods] |
| 352 |
b: bytes |
| 353 |
s: str |
| 354 |
if int(): |
| 355 |
s = b'foo' * 5 # Error |
| 356 |
if int(): |
| 357 |
b = 5 * b'foo' |
| 358 |
if int(): |
| 359 |
b = b'foo' * 5 |
| 360 |
if int(): |
| 361 |
s = 5 * 'foo' |
| 362 |
if int(): |
| 363 |
s = 'foo' * 5 |
| 364 |
[out] |
| 365 |
_program.py:4: error: Incompatible types in assignment (expression has type "bytes", variable has type "str") |
| 366 |
|
| 367 |
[case testROperatorMethods2] |
| 368 |
import typing |
| 369 |
print(2 / 0.5) |
| 370 |
print(' ', 2 * [3, 4]) |
| 371 |
[out] |
| 372 |
4.0 |
| 373 |
[3, 4, 3, 4] |
| 374 |
|
| 375 |
[case testNotImplemented] |
| 376 |
import typing |
| 377 |
class A: |
| 378 |
def __add__(self, x: int) -> int: |
| 379 |
if isinstance(x, int): |
| 380 |
return x + 1 |
| 381 |
return NotImplemented |
| 382 |
class B: |
| 383 |
def __radd__(self, x: A) -> str: |
| 384 |
return 'x' |
| 385 |
print(A() + 1) |
| 386 |
print(A() + B()) |
| 387 |
[out] |
| 388 |
2 |
| 389 |
x |
| 390 |
|
| 391 |
[case testMappingMethods] |
| 392 |
# Regression test |
| 393 |
from typing import Mapping |
| 394 |
x = {'x': 'y'} # type: Mapping[str, str] |
| 395 |
print('x' in x) |
| 396 |
print('y' in x) |
| 397 |
[out] |
| 398 |
True |
| 399 |
False |
| 400 |
|
| 401 |
[case testOverlappingOperatorMethods] |
| 402 |
class X: pass |
| 403 |
class A: |
| 404 |
def __add__(self, x: object) -> int: |
| 405 |
if isinstance(x, X): |
| 406 |
return 1 |
| 407 |
return NotImplemented |
| 408 |
class B: |
| 409 |
def __radd__(self, x: A) -> str: return 'x' |
| 410 |
class C(X, B): pass |
| 411 |
b: B |
| 412 |
b = C() |
| 413 |
print(A() + b) |
| 414 |
[out] |
| 415 |
_program.py:8: error: Signatures of "__radd__" of "B" and "__add__" of "A" are unsafely overlapping |
| 416 |
|
| 417 |
[case testBytesAndBytearrayComparisons] |
| 418 |
import typing |
| 419 |
print(b'ab' < bytearray(b'b')) |
| 420 |
print(bytearray(b'ab') < b'a') |
| 421 |
[out] |
| 422 |
True |
| 423 |
False |
| 424 |
|
| 425 |
[case testBytesAndBytearrayComparisons2] |
| 426 |
import typing |
| 427 |
'' < b'' |
| 428 |
b'' < '' |
| 429 |
'' < bytearray() |
| 430 |
bytearray() < '' |
| 431 |
[out] |
| 432 |
_program.py:2: error: Unsupported operand types for < ("str" and "bytes") |
| 433 |
_program.py:3: error: Unsupported operand types for < ("bytes" and "str") |
| 434 |
_program.py:4: error: Unsupported operand types for < ("str" and "bytearray") |
| 435 |
_program.py:5: error: Unsupported operand types for < ("bytearray" and "str") |
| 436 |
|
| 437 |
[case testInplaceOperatorMethod] |
| 438 |
import typing |
| 439 |
a = [1] |
| 440 |
print('', a.__iadd__([2])) |
| 441 |
print('', a) |
| 442 |
[out] |
| 443 |
[1, 2] |
| 444 |
[1, 2] |
| 445 |
|
| 446 |
[case testListInplaceAdd] |
| 447 |
import typing |
| 448 |
a = [1] |
| 449 |
a += iter([2, 3]) |
| 450 |
print(tuple(a)) |
| 451 |
[out] |
| 452 |
(1, 2, 3) |
| 453 |
|
| 454 |
[case testInferHeterogeneousListOfIterables] |
| 455 |
from typing import Sequence |
| 456 |
s = ['x', 'y'] # type: Sequence[str] |
| 457 |
a = [['x', 'x'], 'fo', s, iter('foo'), {'aa'}] |
| 458 |
for i, x in enumerate(a): |
| 459 |
print(i, next(iter(x))) |
| 460 |
[out] |
| 461 |
0 x |
| 462 |
1 f |
| 463 |
2 x |
| 464 |
3 f |
| 465 |
4 aa |
| 466 |
|
| 467 |
[case testTextIOProperties] |
| 468 |
import typing |
| 469 |
import sys |
| 470 |
print(type(sys.stdin.encoding)) |
| 471 |
print(type(sys.stdin.errors)) |
| 472 |
sys.stdin.line_buffering |
| 473 |
sys.stdin.buffer |
| 474 |
sys.stdin.newlines |
| 475 |
[out] |
| 476 |
<class 'str'> |
| 477 |
<class 'str'> |
| 478 |
|
| 479 |
[case testIOProperties] |
| 480 |
import typing |
| 481 |
import sys |
| 482 |
print(sys.stdin.name) |
| 483 |
print(sys.stdin.buffer.mode) |
| 484 |
[out] |
| 485 |
<stdin> |
| 486 |
rb |
| 487 |
|
| 488 |
[case testFromFuturePrintFunction] |
| 489 |
from __future__ import print_function |
| 490 |
print('a', 'b') |
| 491 |
[out] |
| 492 |
a b |
| 493 |
|
| 494 |
[case testListMethods] |
| 495 |
import typing |
| 496 |
import sys |
| 497 |
l = [0, 1, 2, 3, 4] |
| 498 |
if sys.version >= '3.3': |
| 499 |
l.clear() |
| 500 |
else: |
| 501 |
l = [] |
| 502 |
l.append(0) |
| 503 |
print('>', l) |
| 504 |
if sys.version >= '3.3': |
| 505 |
m = l.copy() |
| 506 |
else: |
| 507 |
m = l[:] |
| 508 |
m.extend([1, 2, 3, 4]) |
| 509 |
print('>', m) |
| 510 |
print(l.index(0)) |
| 511 |
print(l.index(0, 0)) |
| 512 |
print(l.index(0, 0, 1)) |
| 513 |
try: |
| 514 |
print(l.index(1)) |
| 515 |
print('expected ValueError') |
| 516 |
except ValueError: |
| 517 |
pass |
| 518 |
l.insert(0, 1) |
| 519 |
print('>', l) |
| 520 |
print(l.pop(0)) |
| 521 |
print(l.pop()) |
| 522 |
m.remove(0) |
| 523 |
try: |
| 524 |
m.remove(0) |
| 525 |
print('expected ValueError') |
| 526 |
except ValueError: |
| 527 |
pass |
| 528 |
m.reverse() |
| 529 |
m.sort() |
| 530 |
m.sort(key=lambda x: -x) |
| 531 |
m.sort(reverse=False) |
| 532 |
m.sort(key=lambda x: -x, reverse=True) |
| 533 |
print('>', m) |
| 534 |
[out] |
| 535 |
> [0] |
| 536 |
> [0, 1, 2, 3, 4] |
| 537 |
0 |
| 538 |
0 |
| 539 |
0 |
| 540 |
> [1, 0] |
| 541 |
1 |
| 542 |
0 |
| 543 |
> [1, 2, 3, 4] |
| 544 |
|
| 545 |
[case testListOperators] |
| 546 |
import typing |
| 547 |
l = [0, 1] |
| 548 |
print('+', l + [2]) |
| 549 |
print('*', l * 2) |
| 550 |
print('*', 2 * l) |
| 551 |
print('in', 1 in l) |
| 552 |
print('==', l == [1, 2]) |
| 553 |
print('!=', l != [1, 2]) |
| 554 |
print('>', l > [1, 2, 3]) |
| 555 |
print('>=', l >= [1, 2, 3]) |
| 556 |
print('<', l < [1, 2, 3]) |
| 557 |
print('<=', l <= [1, 2, 3]) |
| 558 |
print('>[0]', l[0]) |
| 559 |
l += [2] |
| 560 |
print('+=', l) |
| 561 |
l *= 2 |
| 562 |
print('*=', l) |
| 563 |
print('iter', list(iter(l))) |
| 564 |
print('len', len(l)) |
| 565 |
print('repr', repr(l)) |
| 566 |
l[:3] = [] |
| 567 |
print('setslice', l) |
| 568 |
print('reversed', list(reversed(l))) |
| 569 |
[out] |
| 570 |
+ [0, 1, 2] |
| 571 |
* [0, 1, 0, 1] |
| 572 |
* [0, 1, 0, 1] |
| 573 |
in True |
| 574 |
== False |
| 575 |
!= True |
| 576 |
> False |
| 577 |
>= False |
| 578 |
< True |
| 579 |
<= True |
| 580 |
>[0] 0 |
| 581 |
+= [0, 1, 2] |
| 582 |
*= [0, 1, 2, 0, 1, 2] |
| 583 |
iter [0, 1, 2, 0, 1, 2] |
| 584 |
len 6 |
| 585 |
repr [0, 1, 2, 0, 1, 2] |
| 586 |
setslice [0, 1, 2] |
| 587 |
reversed [2, 1, 0] |
| 588 |
|
| 589 |
[case testTupleAsSubtypeOfSequence] |
| 590 |
from typing import TypeVar, Sequence |
| 591 |
T = TypeVar('T') |
| 592 |
def f(a: Sequence[T]) -> None: print(a) |
| 593 |
f(tuple()) |
| 594 |
[out] |
| 595 |
() |
| 596 |
|
| 597 |
[case testMapWithLambdaSpecialCase] |
| 598 |
from typing import List, Iterator |
| 599 |
a = [[1], [3]] |
| 600 |
b = map(lambda y: y[0], a) |
| 601 |
print('>', list(b)) |
| 602 |
[out] |
| 603 |
> [1, 3] |
| 604 |
|
| 605 |
[case testInternalBuiltinDefinition] |
| 606 |
import typing |
| 607 |
def f(x: _T) -> None: pass |
| 608 |
s: FrozenSet |
| 609 |
[out] |
| 610 |
_program.py:2: error: Name "_T" is not defined |
| 611 |
_program.py:3: error: Name "FrozenSet" is not defined; did you mean "frozenset"? |
| 612 |
|
| 613 |
[case testVarArgsFunctionSubtyping] |
| 614 |
import typing |
| 615 |
def f(*args: str) -> str: return args[0] |
| 616 |
map(f, ['x']) |
| 617 |
map(f, [1]) |
| 618 |
[out] |
| 619 |
_program.py:4: error: Argument 1 to "map" has incompatible type "def f(*args: str) -> str"; expected "Callable[[int], str]" |
| 620 |
|
| 621 |
[case testMapStr] |
| 622 |
import typing |
| 623 |
x = range(3) |
| 624 |
a = list(map(str, x)) |
| 625 |
a + 1 |
| 626 |
[out] |
| 627 |
_testMapStr.py:4: error: No overload variant of "__add__" of "list" matches argument type "int" |
| 628 |
_testMapStr.py:4: note: Possible overload variants: |
| 629 |
_testMapStr.py:4: note: def __add__(self, list[str], /) -> list[str] |
| 630 |
_testMapStr.py:4: note: def [_S] __add__(self, list[_S], /) -> list[_S | str] |
| 631 |
|
| 632 |
[case testRelativeImport] |
| 633 |
import typing |
| 634 |
from m import x |
| 635 |
print(x) |
| 636 |
[file m/__init__.py] |
| 637 |
from .n import x |
| 638 |
[file m/n.py] |
| 639 |
x = 1 |
| 640 |
[out] |
| 641 |
1 |
| 642 |
|
| 643 |
[case testRelativeImport2] |
| 644 |
import typing |
| 645 |
from m.n import x |
| 646 |
print(x) |
| 647 |
[file m/__init__.py] |
| 648 |
[file m/n.py] |
| 649 |
from .nn import x |
| 650 |
[file m/nn.py] |
| 651 |
x = 2 |
| 652 |
[out] |
| 653 |
2 |
| 654 |
|
| 655 |
[case testPyiTakesPrecedenceOverPy] |
| 656 |
import m |
| 657 |
m.f(1) |
| 658 |
[file m.py] |
| 659 |
def f(x): |
| 660 |
print(x) |
| 661 |
[file m.pyi] |
| 662 |
import typing |
| 663 |
def f(x: str) -> None: pass |
| 664 |
[out] |
| 665 |
_program.py:2: error: Argument 1 to "f" has incompatible type "int"; expected "str" |
| 666 |
|
| 667 |
[case testComplexArithmetic] |
| 668 |
import typing |
| 669 |
print(5 + 8j) |
| 670 |
print(3j * 2.0) |
| 671 |
print(4J / 2.0) |
| 672 |
[out] |
| 673 |
(5+8j) |
| 674 |
6j |
| 675 |
2j |
| 676 |
|
| 677 |
[case testComplexArithmetic2] |
| 678 |
x = 5 + 8j |
| 679 |
if int(): |
| 680 |
x = '' # E |
| 681 |
y = 3j * 2.0 |
| 682 |
if int(): |
| 683 |
y = '' # E |
| 684 |
[out] |
| 685 |
_program.py:3: error: Incompatible types in assignment (expression has type "str", variable has type "complex") |
| 686 |
_program.py:6: error: Incompatible types in assignment (expression has type "str", variable has type "complex") |
| 687 |
|
| 688 |
[case testSuperNew] |
| 689 |
from typing import Dict, Any |
| 690 |
class MyType(type): |
| 691 |
def __new__(cls, name: str, bases: tuple, namespace: Dict[str, Any]) -> Any: |
| 692 |
return super().__new__(cls, name + 'x', bases, namespace) |
| 693 |
class A(metaclass=MyType): pass |
| 694 |
print(type(A()).__name__) |
| 695 |
[out] |
| 696 |
Ax |
| 697 |
|
| 698 |
[case testSubclassBothGenericAndNonGenericABC] |
| 699 |
from typing import Generic, TypeVar |
| 700 |
from abc import ABCMeta |
| 701 |
T = TypeVar('T') |
| 702 |
class A(metaclass=ABCMeta): pass |
| 703 |
class B(Generic[T]): pass |
| 704 |
class C(A, B): pass |
| 705 |
class D(B, A): pass |
| 706 |
class E(A, B[T], Generic[T]): pass |
| 707 |
class F(B[T], A, Generic[T]): pass |
| 708 |
def f(e: E[int], f: F[int]) -> None: pass |
| 709 |
[out] |
| 710 |
|
| 711 |
[case testTypeVariableTypeComparability] |
| 712 |
from typing import TypeVar |
| 713 |
T = TypeVar('T') |
| 714 |
def eq(x: T, y: T, z: T) -> T: |
| 715 |
if x == y: |
| 716 |
return y |
| 717 |
else: |
| 718 |
return z |
| 719 |
print(eq(1, 2, 3)) |
| 720 |
print(eq('x', 'x', 'z')) |
| 721 |
[out] |
| 722 |
3 |
| 723 |
x |
| 724 |
|
| 725 |
[case testIntDecimalCompatibility] |
| 726 |
import typing |
| 727 |
from decimal import Decimal |
| 728 |
print(Decimal(1) + 2) |
| 729 |
print(Decimal(1) - 2) |
| 730 |
print(1 + Decimal('2.34')) |
| 731 |
print(1 - Decimal('2.34')) |
| 732 |
print(2 * Decimal('2.34')) |
| 733 |
[out] |
| 734 |
3 |
| 735 |
-1 |
| 736 |
3.34 |
| 737 |
-1.34 |
| 738 |
4.68 |
| 739 |
|
| 740 |
[case testInstantiateBuiltinTypes] |
| 741 |
from typing import Dict, Set, List |
| 742 |
d = dict() # type: Dict[int, str] |
| 743 |
s = set() # type: Set[int] |
| 744 |
l = list() # type: List[int] |
| 745 |
str() |
| 746 |
bytes() |
| 747 |
bytearray() |
| 748 |
int() |
| 749 |
float() |
| 750 |
complex() |
| 751 |
slice(1) |
| 752 |
bool() |
| 753 |
|
| 754 |
[case testVariableLengthTupleError] |
| 755 |
from typing import Tuple |
| 756 |
def p(t: Tuple[str, ...]) -> None: |
| 757 |
n = 5 |
| 758 |
print(t[n]) |
| 759 |
for s in t: |
| 760 |
s() |
| 761 |
''.startswith(('x', 'y')) |
| 762 |
''.startswith(('x', b'y')) |
| 763 |
[out] |
| 764 |
_program.py:6: error: "str" not callable |
| 765 |
_program.py:8: error: Argument 1 to "startswith" of "str" has incompatible type "tuple[str, bytes]"; expected "str | tuple[str, ...]" |
| 766 |
|
| 767 |
[case testMultiplyTupleByInteger] |
| 768 |
n = 4 |
| 769 |
t = ('',) * n |
| 770 |
t + 1 |
| 771 |
[out] |
| 772 |
_program.py:3: error: No overload variant of "__add__" of "tuple" matches argument type "int" |
| 773 |
_program.py:3: note: Possible overload variants: |
| 774 |
_program.py:3: note: def __add__(self, tuple[str, ...], /) -> tuple[str, ...] |
| 775 |
_program.py:3: note: def [_T] __add__(self, tuple[_T, ...], /) -> tuple[str | _T, ...] |
| 776 |
|
| 777 |
[case testMultiplyTupleByIntegerReverse] |
| 778 |
n = 4 |
| 779 |
t = n * ('',) |
| 780 |
t + 1 |
| 781 |
[out] |
| 782 |
_program.py:3: error: No overload variant of "__add__" of "tuple" matches argument type "int" |
| 783 |
_program.py:3: note: Possible overload variants: |
| 784 |
_program.py:3: note: def __add__(self, tuple[str, ...], /) -> tuple[str, ...] |
| 785 |
_program.py:3: note: def [_T] __add__(self, tuple[_T, ...], /) -> tuple[str | _T, ...] |
| 786 |
|
| 787 |
[case testDictWithKeywordArgs] |
| 788 |
from typing import Dict, Any, List |
| 789 |
d1 = dict(a=1, b=2) # type: Dict[str, int] |
| 790 |
d2 = dict(a=1, b='') # type: Dict[str, int] # E |
| 791 |
d3 = dict(a=1, b=1) |
| 792 |
d3.xyz # E |
| 793 |
d4 = dict(a=1, b='') # type: Dict[str, Any] |
| 794 |
result = dict(x=[], y=[]) # type: Dict[str, List[str]] |
| 795 |
[out] |
| 796 |
_program.py:3: error: Dict entry 1 has incompatible type "str": "str"; expected "str": "int" |
| 797 |
_program.py:5: error: "dict[str, int]" has no attribute "xyz" |
| 798 |
|
| 799 |
[case testDefaultDict] |
| 800 |
import typing as t |
| 801 |
from collections import defaultdict |
| 802 |
|
| 803 |
T = t.TypeVar('T') |
| 804 |
|
| 805 |
d1 = defaultdict(list) # type: t.DefaultDict[int, str] |
| 806 |
d2 = defaultdict() # type: t.DefaultDict[int, str] |
| 807 |
d2[0] = '0' |
| 808 |
d2['0'] = 0 |
| 809 |
|
| 810 |
def tst(dct: t.DefaultDict[int, T]) -> T: |
| 811 |
return dct[0] |
| 812 |
|
| 813 |
collections = ['coins', 'stamps', 'comics'] # type: t.List[str] |
| 814 |
d3 = defaultdict(str) # type: t.DefaultDict[int, str] |
| 815 |
collections[2] |
| 816 |
|
| 817 |
tst(defaultdict(list, {0: []})) |
| 818 |
tst(defaultdict(list, {'0': []})) |
| 819 |
|
| 820 |
class MyDDict(t.DefaultDict[int,T], t.Generic[T]): |
| 821 |
pass |
| 822 |
MyDDict(dict)['0'] |
| 823 |
MyDDict(dict)[0] |
| 824 |
[out] |
| 825 |
_program.py:6: error: Argument 1 to "defaultdict" has incompatible type "type[list[_T]]"; expected "Callable[[], str] | None" |
| 826 |
_program.py:9: error: Invalid index type "str" for "defaultdict[int, str]"; expected type "int" |
| 827 |
_program.py:9: error: Incompatible types in assignment (expression has type "int", target has type "str") |
| 828 |
_program.py:19: error: Argument 1 to "tst" has incompatible type "defaultdict[str, list[Never]]"; expected "defaultdict[int, list[Never]]" |
| 829 |
_program.py:23: error: Invalid index type "str" for "MyDDict[dict[Never, Never]]"; expected type "int" |
| 830 |
|
| 831 |
[case testCollectionsAliases] |
| 832 |
import typing as t |
| 833 |
import collections as c |
| 834 |
|
| 835 |
o1 = c.Counter() # type: t.Counter[int] |
| 836 |
reveal_type(o1) |
| 837 |
o1['string'] |
| 838 |
|
| 839 |
o2 = c.ChainMap() # type: t.ChainMap[int, str] |
| 840 |
reveal_type(o2) |
| 841 |
|
| 842 |
o3 = c.deque() # type: t.Deque[int] |
| 843 |
reveal_type(o3) |
| 844 |
|
| 845 |
o4 = t.Counter[int]() |
| 846 |
reveal_type(o4) |
| 847 |
|
| 848 |
o5 = t.ChainMap[int, str]() |
| 849 |
reveal_type(o5) |
| 850 |
|
| 851 |
o6 = t.Deque[int]() |
| 852 |
reveal_type(o6) |
| 853 |
|
| 854 |
[out] |
| 855 |
_testCollectionsAliases.py:5: note: Revealed type is "collections.Counter[int]" |
| 856 |
_testCollectionsAliases.py:6: error: Invalid index type "str" for "Counter[int]"; expected type "int" |
| 857 |
_testCollectionsAliases.py:9: note: Revealed type is "collections.ChainMap[int, str]" |
| 858 |
_testCollectionsAliases.py:12: note: Revealed type is "collections.deque[int]" |
| 859 |
_testCollectionsAliases.py:15: note: Revealed type is "collections.Counter[int]" |
| 860 |
_testCollectionsAliases.py:18: note: Revealed type is "collections.ChainMap[int, str]" |
| 861 |
_testCollectionsAliases.py:21: note: Revealed type is "collections.deque[int]" |
| 862 |
|
| 863 |
[case testChainMapUnimported] |
| 864 |
ChainMap[int, str]() |
| 865 |
|
| 866 |
[out] |
| 867 |
_testChainMapUnimported.py:1: error: Name "ChainMap" is not defined |
| 868 |
|
| 869 |
[case testDequeWrongCase] |
| 870 |
import collections |
| 871 |
import typing |
| 872 |
|
| 873 |
collections.Deque() |
| 874 |
typing.deque() |
| 875 |
|
| 876 |
[out] |
| 877 |
_testDequeWrongCase.py:4: error: Module has no attribute "Deque"; maybe "deque"? |
| 878 |
_testDequeWrongCase.py:5: error: Module has no attribute "deque"; maybe "Deque"? |
| 879 |
|
| 880 |
[case testDictUpdateInference] |
| 881 |
from typing import Dict, Optional |
| 882 |
d = {} # type: Dict[str, Optional[int]] |
| 883 |
d.update({str(i): None for i in range(4)}) |
| 884 |
|
| 885 |
[case testSuperAndSetattr] |
| 886 |
class A: |
| 887 |
def __init__(self) -> None: |
| 888 |
super().__setattr__('a', 1) |
| 889 |
super().__setattr__(1, 'a') |
| 890 |
[out] |
| 891 |
_program.py:4: error: Argument 1 to "__setattr__" of "object" has incompatible type "int"; expected "str" |
| 892 |
|
| 893 |
[case testMetaclassAndSuper] |
| 894 |
from typing import Any |
| 895 |
|
| 896 |
class A(type): |
| 897 |
def __new__(cls, name, bases, namespace) -> Any: |
| 898 |
return super().__new__(cls, '', (object,), {'x': 7}) |
| 899 |
|
| 900 |
class B(metaclass=A): |
| 901 |
pass |
| 902 |
|
| 903 |
print(getattr(B(), 'x')) |
| 904 |
[out] |
| 905 |
7 |
| 906 |
|
| 907 |
[case testSortedNoError] |
| 908 |
from typing import Iterable, Callable, TypeVar, List, Dict, Optional |
| 909 |
T = TypeVar('T') |
| 910 |
def sorted(x: Iterable[T], *, key: Optional[Callable[[T], object]] = None) -> None: ... |
| 911 |
a = [] # type: List[Dict[str, str]] |
| 912 |
sorted(a, key=lambda y: y['']) |
| 913 |
|
| 914 |
[case testAbstractProperty] |
| 915 |
from abc import abstractproperty, ABCMeta # type: ignore[deprecated] |
| 916 |
class A(metaclass=ABCMeta): |
| 917 |
@abstractproperty |
| 918 |
def x(self) -> int: pass |
| 919 |
class B(A): |
| 920 |
@property |
| 921 |
def x(self) -> int: |
| 922 |
return 3 |
| 923 |
b = B() |
| 924 |
print(b.x + 1) |
| 925 |
[out] |
| 926 |
4 |
| 927 |
|
| 928 |
[case testInferenceWithLambda] |
| 929 |
from typing import TypeVar, Iterable, Iterator, List |
| 930 |
import itertools |
| 931 |
|
| 932 |
_T = TypeVar('_T') |
| 933 |
|
| 934 |
def f(iterable): # type: (Iterable[_T]) -> Iterator[List[_T]] |
| 935 |
grouped = itertools.groupby(enumerate(iterable), lambda pair: pair[0] // 2) |
| 936 |
return ([elem for _, elem in group] for _, group in grouped) |
| 937 |
|
| 938 |
[case testReModuleBytes] |
| 939 |
# Regression tests for various overloads in the re module -- bytes version |
| 940 |
import re |
| 941 |
bre = b'a+' |
| 942 |
bpat = re.compile(bre) |
| 943 |
bpat = re.compile(bpat) |
| 944 |
s1 = re.search(bre, b'') |
| 945 |
assert s1 |
| 946 |
s1.groups() |
| 947 |
re.search(bre, u'') # Error |
| 948 |
s2 = re.search(bpat, b'') |
| 949 |
assert s2 |
| 950 |
s2.groups() |
| 951 |
re.search(bpat, u'') # Error |
| 952 |
# match(), split(), findall(), finditer() are much the same, so skip those. |
| 953 |
# sub(), subn() have more overloads and we are checking these: |
| 954 |
re.sub(bre, b'', b'') + b'' |
| 955 |
re.sub(bpat, b'', b'') + b'' |
| 956 |
re.sub(bre, lambda m: b'', b'') + b'' |
| 957 |
re.sub(bpat, lambda m: b'', b'') + b'' |
| 958 |
re.subn(bre, b'', b'')[0] + b'' |
| 959 |
re.subn(bpat, b'', b'')[0] + b'' |
| 960 |
re.subn(bre, lambda m: b'', b'')[0] + b'' |
| 961 |
re.subn(bpat, lambda m: b'', b'')[0] + b'' |
| 962 |
[out] |
| 963 |
_testReModuleBytes.py:9: error: No overload variant of "search" matches argument types "bytes", "str" |
| 964 |
_testReModuleBytes.py:9: note: Possible overload variants: |
| 965 |
_testReModuleBytes.py:9: note: def search(pattern: str | Pattern[str], string: str, flags: int | RegexFlag = ...) -> Match[str] | None |
| 966 |
_testReModuleBytes.py:9: note: def search(pattern: bytes | Pattern[bytes], string: Buffer, flags: int | RegexFlag = ...) -> Match[bytes] | None |
| 967 |
_testReModuleBytes.py:13: error: Argument 1 to "search" has incompatible type "Pattern[bytes]"; expected "str | Pattern[str]" |
| 968 |
|
| 969 |
[case testReModuleString] |
| 970 |
# Regression tests for various overloads in the re module -- string version |
| 971 |
import re |
| 972 |
sre = 'a+' |
| 973 |
spat = re.compile(sre) |
| 974 |
spat = re.compile(spat) |
| 975 |
s1 = re.search(sre, '') |
| 976 |
assert s1 |
| 977 |
s1.groups() |
| 978 |
re.search(sre, b'') # Error |
| 979 |
s2 = re.search(spat, '') |
| 980 |
assert s2 |
| 981 |
s2.groups() |
| 982 |
re.search(spat, b'') # Error |
| 983 |
# match(), split(), findall(), finditer() are much the same, so skip those. |
| 984 |
# sus(), susn() have more overloads and we are checking these: |
| 985 |
re.sub(sre, '', '') + '' |
| 986 |
re.sub(spat, '', '') + '' |
| 987 |
re.sub(sre, lambda m: '', '') + '' |
| 988 |
re.sub(spat, lambda m: '', '') + '' |
| 989 |
re.subn(sre, '', '')[0] + '' |
| 990 |
re.subn(spat, '', '')[0] + '' |
| 991 |
re.subn(sre, lambda m: '', '')[0] + '' |
| 992 |
re.subn(spat, lambda m: '', '')[0] + '' |
| 993 |
[out] |
| 994 |
_testReModuleString.py:9: error: No overload variant of "search" matches argument types "str", "bytes" |
| 995 |
_testReModuleString.py:9: note: Possible overload variants: |
| 996 |
_testReModuleString.py:9: note: def search(pattern: str | Pattern[str], string: str, flags: int | RegexFlag = ...) -> Match[str] | None |
| 997 |
_testReModuleString.py:9: note: def search(pattern: bytes | Pattern[bytes], string: Buffer, flags: int | RegexFlag = ...) -> Match[bytes] | None |
| 998 |
_testReModuleString.py:13: error: Argument 1 to "search" has incompatible type "Pattern[str]"; expected "bytes | Pattern[bytes]" |
| 999 |
|
| 1000 |
[case testListSetitemTuple] |
| 1001 |
from typing import List, Tuple |
| 1002 |
a = [] # type: List[Tuple[str, int]] |
| 1003 |
a[0] = 'x', 1 |
| 1004 |
a[1] = 2, 'y' |
| 1005 |
a[:] = [('z', 3)] |
| 1006 |
[out] |
| 1007 |
_program.py:4: error: Incompatible types in assignment (expression has type "tuple[int, str]", target has type "tuple[str, int]") |
| 1008 |
|
| 1009 |
[case testContextManager] |
| 1010 |
import contextlib |
| 1011 |
from contextlib import contextmanager |
| 1012 |
from typing import Iterator |
| 1013 |
|
| 1014 |
@contextmanager |
| 1015 |
def f(x: int) -> Iterator[str]: |
| 1016 |
yield 'foo' |
| 1017 |
|
| 1018 |
@contextlib.contextmanager |
| 1019 |
def g(*x: str) -> Iterator[int]: |
| 1020 |
yield 1 |
| 1021 |
|
| 1022 |
reveal_type(f) |
| 1023 |
reveal_type(g) |
| 1024 |
|
| 1025 |
with f('') as s: |
| 1026 |
reveal_type(s) |
| 1027 |
[out] |
| 1028 |
_program.py:13: note: Revealed type is "def (x: int) -> contextlib._GeneratorContextManager[str, None, None]" |
| 1029 |
_program.py:14: note: Revealed type is "def (*x: str) -> contextlib._GeneratorContextManager[int, None, None]" |
| 1030 |
_program.py:16: error: Argument 1 to "f" has incompatible type "str"; expected "int" |
| 1031 |
_program.py:17: note: Revealed type is "str" |
| 1032 |
|
| 1033 |
[case testTypedDictGet] |
| 1034 |
# Test that TypedDict get plugin works with typeshed stubs |
| 1035 |
from typing import TypedDict |
| 1036 |
class A: pass |
| 1037 |
D_total = TypedDict('D_total', {'x': int, 'y': str}, total=True) |
| 1038 |
D_not_total = TypedDict('D_not_total', {'x': int, 'y': str}, total=False) |
| 1039 |
|
| 1040 |
def test_total(d: D_total) -> None: |
| 1041 |
reveal_type(d.get('x')) |
| 1042 |
reveal_type(d.get('y')) |
| 1043 |
reveal_type(d.get('z')) |
| 1044 |
d.get() |
| 1045 |
s = '' |
| 1046 |
reveal_type(d.get(s)) |
| 1047 |
|
| 1048 |
def test_not_total(d: D_not_total) -> None: |
| 1049 |
reveal_type(d.get('x')) |
| 1050 |
reveal_type(d.get('y')) |
| 1051 |
reveal_type(d.get('z')) |
| 1052 |
d.get() |
| 1053 |
s = '' |
| 1054 |
reveal_type(d.get(s)) |
| 1055 |
[out] |
| 1056 |
_testTypedDictGet.py:8: note: Revealed type is "int" |
| 1057 |
_testTypedDictGet.py:9: note: Revealed type is "str" |
| 1058 |
_testTypedDictGet.py:10: note: Revealed type is "object" |
| 1059 |
_testTypedDictGet.py:11: error: All overload variants of "get" of "Mapping" require at least one argument |
| 1060 |
_testTypedDictGet.py:11: note: Possible overload variants: |
| 1061 |
_testTypedDictGet.py:11: note: def get(self, str, /) -> object |
| 1062 |
_testTypedDictGet.py:11: note: def get(self, str, object, /) -> object |
| 1063 |
_testTypedDictGet.py:11: note: def [_T] get(self, str, _T, /) -> object |
| 1064 |
_testTypedDictGet.py:13: note: Revealed type is "object" |
| 1065 |
_testTypedDictGet.py:16: note: Revealed type is "int | None" |
| 1066 |
_testTypedDictGet.py:17: note: Revealed type is "str | None" |
| 1067 |
_testTypedDictGet.py:18: note: Revealed type is "object" |
| 1068 |
_testTypedDictGet.py:19: error: All overload variants of "get" of "Mapping" require at least one argument |
| 1069 |
_testTypedDictGet.py:19: note: Possible overload variants: |
| 1070 |
_testTypedDictGet.py:19: note: def get(self, str, /) -> object |
| 1071 |
_testTypedDictGet.py:19: note: def get(self, str, object, /) -> object |
| 1072 |
_testTypedDictGet.py:19: note: def [_T] get(self, str, _T, /) -> object |
| 1073 |
_testTypedDictGet.py:21: note: Revealed type is "object" |
| 1074 |
|
| 1075 |
[case testTypedDictMappingMethods] |
| 1076 |
from typing import TypedDict |
| 1077 |
Cell = TypedDict('Cell', {'value': int}) |
| 1078 |
c = Cell(value=42) |
| 1079 |
for x in c: |
| 1080 |
reveal_type(x) |
| 1081 |
reveal_type(iter(c)) |
| 1082 |
reveal_type(len(c)) |
| 1083 |
reveal_type('value' in c) |
| 1084 |
reveal_type(c.keys()) |
| 1085 |
reveal_type(c.items()) |
| 1086 |
reveal_type(c.values()) |
| 1087 |
reveal_type(c.copy()) |
| 1088 |
reveal_type(c.setdefault('value', False)) |
| 1089 |
c.update({'value': 2}) |
| 1090 |
c.update({'invalid': 2}) |
| 1091 |
c.pop('value') |
| 1092 |
c == c |
| 1093 |
c != c |
| 1094 |
Cell2 = TypedDict('Cell2', {'value': int}, total=False) |
| 1095 |
c2 = Cell2() |
| 1096 |
reveal_type(c2.pop('value')) |
| 1097 |
[out] |
| 1098 |
_testTypedDictMappingMethods.py:5: note: Revealed type is "str" |
| 1099 |
_testTypedDictMappingMethods.py:6: note: Revealed type is "typing.Iterator[str]" |
| 1100 |
_testTypedDictMappingMethods.py:7: note: Revealed type is "int" |
| 1101 |
_testTypedDictMappingMethods.py:8: note: Revealed type is "bool" |
| 1102 |
_testTypedDictMappingMethods.py:9: note: Revealed type is "_collections_abc.dict_keys[str, object]" |
| 1103 |
_testTypedDictMappingMethods.py:10: note: Revealed type is "_collections_abc.dict_items[str, object]" |
| 1104 |
_testTypedDictMappingMethods.py:11: note: Revealed type is "_collections_abc.dict_values[str, object]" |
| 1105 |
_testTypedDictMappingMethods.py:12: note: Revealed type is "TypedDict(_testTypedDictMappingMethods.Cell, {'value': int})" |
| 1106 |
_testTypedDictMappingMethods.py:13: note: Revealed type is "int" |
| 1107 |
_testTypedDictMappingMethods.py:15: error: Unexpected TypedDict key "invalid" |
| 1108 |
_testTypedDictMappingMethods.py:16: error: Key "value" of TypedDict "Cell" cannot be deleted |
| 1109 |
_testTypedDictMappingMethods.py:21: note: Revealed type is "int" |
| 1110 |
|
| 1111 |
[case testCrashOnComplexCheckWithNamedTupleNext] |
| 1112 |
from typing import NamedTuple, Optional |
| 1113 |
|
| 1114 |
MyNamedTuple = NamedTuple('MyNamedTuple', [('parent', 'MyNamedTuple')]) # type: ignore |
| 1115 |
def foo(mymap) -> Optional[MyNamedTuple]: |
| 1116 |
return next((mymap[key] for key in mymap), None) |
| 1117 |
[out] |
| 1118 |
|
| 1119 |
[case testCanConvertTypedDictToAnySuperclassOfMapping] |
| 1120 |
from typing import Sized, TypedDict, Iterable, Container |
| 1121 |
|
| 1122 |
Point = TypedDict('Point', {'x': int, 'y': int}) |
| 1123 |
|
| 1124 |
p: Point |
| 1125 |
s: Sized = p |
| 1126 |
it: Iterable[str] = p |
| 1127 |
c: Container[str] = p |
| 1128 |
o: object = p |
| 1129 |
it2: Iterable[int] = p |
| 1130 |
[out] |
| 1131 |
_testCanConvertTypedDictToAnySuperclassOfMapping.py:10: error: Incompatible types in assignment (expression has type "Point", variable has type "Iterable[int]") |
| 1132 |
_testCanConvertTypedDictToAnySuperclassOfMapping.py:10: note: Following member(s) of "Point" have conflicts: |
| 1133 |
_testCanConvertTypedDictToAnySuperclassOfMapping.py:10: note: Expected: |
| 1134 |
_testCanConvertTypedDictToAnySuperclassOfMapping.py:10: note: def __iter__(self) -> Iterator[int] |
| 1135 |
_testCanConvertTypedDictToAnySuperclassOfMapping.py:10: note: Got: |
| 1136 |
_testCanConvertTypedDictToAnySuperclassOfMapping.py:10: note: def __iter__(self) -> Iterator[str] |
| 1137 |
|
| 1138 |
[case testAsyncioGatherPreciseType-xfail] |
| 1139 |
# Mysteriously regressed in #11905 |
| 1140 |
import asyncio |
| 1141 |
from typing import Tuple |
| 1142 |
|
| 1143 |
async def get_location(arg: str) -> Tuple[str, str]: |
| 1144 |
return arg, arg |
| 1145 |
|
| 1146 |
async def main() -> None: |
| 1147 |
((a_x, a_y),) = await asyncio.gather(get_location('start')) |
| 1148 |
reveal_type(a_x) |
| 1149 |
reveal_type(a_y) |
| 1150 |
reveal_type(asyncio.gather(*[asyncio.sleep(1), asyncio.sleep(1)])) |
| 1151 |
[out] |
| 1152 |
_testAsyncioGatherPreciseType.py:9: note: Revealed type is "str" |
| 1153 |
_testAsyncioGatherPreciseType.py:10: note: Revealed type is "str" |
| 1154 |
_testAsyncioGatherPreciseType.py:11: note: Revealed type is "asyncio.futures.Future[list[Any]]" |
| 1155 |
|
| 1156 |
[case testMultipleInheritanceWorksWithTupleTypeGeneric] |
| 1157 |
from typing import SupportsAbs, NamedTuple |
| 1158 |
|
| 1159 |
class Point(NamedTuple('Point', [('x', int), ('y', int)]), SupportsAbs[int]): |
| 1160 |
def __abs__(p) -> int: |
| 1161 |
return abs(p.x) + abs(p.y) |
| 1162 |
|
| 1163 |
def test(a: Point) -> bool: |
| 1164 |
return abs(a) == 2 |
| 1165 |
[out] |
| 1166 |
|
| 1167 |
[case testNoCrashOnGenericUnionUnpacking] |
| 1168 |
from typing import Union, Dict |
| 1169 |
|
| 1170 |
TEST = {'key': ('a', 'b')} |
| 1171 |
def test() -> None: |
| 1172 |
a, b = TEST.get('foo', ('x', 'y')) |
| 1173 |
reveal_type(a) |
| 1174 |
reveal_type(b) |
| 1175 |
def test2() -> None: |
| 1176 |
a, b = TEST.get('foo', (1, 2)) |
| 1177 |
reveal_type(a) |
| 1178 |
reveal_type(b) |
| 1179 |
|
| 1180 |
x: Union[Dict[int, int], Dict[str, str]] = dict(a='b') |
| 1181 |
for a, b in x.items(): |
| 1182 |
reveal_type(a) |
| 1183 |
reveal_type(b) |
| 1184 |
[out] |
| 1185 |
_testNoCrashOnGenericUnionUnpacking.py:6: note: Revealed type is "str" |
| 1186 |
_testNoCrashOnGenericUnionUnpacking.py:7: note: Revealed type is "str" |
| 1187 |
_testNoCrashOnGenericUnionUnpacking.py:10: note: Revealed type is "str | int" |
| 1188 |
_testNoCrashOnGenericUnionUnpacking.py:11: note: Revealed type is "str | int" |
| 1189 |
_testNoCrashOnGenericUnionUnpacking.py:15: note: Revealed type is "int | str" |
| 1190 |
_testNoCrashOnGenericUnionUnpacking.py:16: note: Revealed type is "int | str" |
| 1191 |
|
| 1192 |
[case testMetaclassOpAccess] |
| 1193 |
from typing import Type |
| 1194 |
class A: |
| 1195 |
pass |
| 1196 |
|
| 1197 |
class Meta(type): |
| 1198 |
def __mul__(self, other: int) -> Type[A]: |
| 1199 |
pass |
| 1200 |
def __add__(self, other: int) -> Type[C]: |
| 1201 |
pass |
| 1202 |
def __radd__(self, other: int) -> Type[C]: |
| 1203 |
pass |
| 1204 |
class C(metaclass=Meta): |
| 1205 |
pass |
| 1206 |
|
| 1207 |
bar: Type[C] |
| 1208 |
def get_c_type() -> Type[C]: |
| 1209 |
pass |
| 1210 |
|
| 1211 |
res = bar * 4 |
| 1212 |
other = 4 + get_c_type() + 5 |
| 1213 |
reveal_type(res) |
| 1214 |
reveal_type(other) |
| 1215 |
[out] |
| 1216 |
_testMetaclassOpAccess.py:21: note: Revealed type is "type[_testMetaclassOpAccess.A]" |
| 1217 |
_testMetaclassOpAccess.py:22: note: Revealed type is "type[_testMetaclassOpAccess.C]" |
| 1218 |
|
| 1219 |
[case testMetaclassOpAccessUnion] |
| 1220 |
from typing import Type, Union |
| 1221 |
|
| 1222 |
class MetaA(type): |
| 1223 |
def __mul__(self, other: int) -> str: |
| 1224 |
pass |
| 1225 |
class A(metaclass=MetaA): |
| 1226 |
pass |
| 1227 |
class MetaB(type): |
| 1228 |
def __mul__(self, other: int) -> int: |
| 1229 |
pass |
| 1230 |
class B(metaclass=MetaB): |
| 1231 |
pass |
| 1232 |
|
| 1233 |
bar: Type[Union[A, B]] |
| 1234 |
res = bar * 4 |
| 1235 |
reveal_type(res) |
| 1236 |
[out] |
| 1237 |
_testMetaclassOpAccessUnion.py:16: note: Revealed type is "str | int" |
| 1238 |
|
| 1239 |
[case testMetaclassOpAccessAny] |
| 1240 |
from typing import Type |
| 1241 |
from nonexistent import C |
| 1242 |
bar: Type[C] |
| 1243 |
|
| 1244 |
bar * 4 + bar + 3 # should not produce more errors |
| 1245 |
[out] |
| 1246 |
_testMetaclassOpAccessAny.py:2: error: Cannot find implementation or library stub for module named "nonexistent" |
| 1247 |
_testMetaclassOpAccessAny.py:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports |
| 1248 |
|
| 1249 |
[case testEnumIterationAndPreciseElementType] |
| 1250 |
# Regression test for #2305 |
| 1251 |
from enum import Enum |
| 1252 |
class E(Enum): |
| 1253 |
A = 'a' |
| 1254 |
(reveal_type(e) for e in E) |
| 1255 |
for e in E: |
| 1256 |
reveal_type(e) |
| 1257 |
[out] |
| 1258 |
_testEnumIterationAndPreciseElementType.py:5: note: Revealed type is "_testEnumIterationAndPreciseElementType.E" |
| 1259 |
_testEnumIterationAndPreciseElementType.py:7: note: Revealed type is "_testEnumIterationAndPreciseElementType.E" |
| 1260 |
|
| 1261 |
[case testEnumIterable] |
| 1262 |
from enum import Enum |
| 1263 |
from typing import Iterable |
| 1264 |
class E(Enum): |
| 1265 |
A = 'a' |
| 1266 |
def f(ie: Iterable[E]): |
| 1267 |
pass |
| 1268 |
f(E) |
| 1269 |
|
| 1270 |
[case testIntEnumIterable] |
| 1271 |
from enum import IntEnum |
| 1272 |
from typing import Iterable |
| 1273 |
class N(IntEnum): |
| 1274 |
X = 1 |
| 1275 |
def f(ni: Iterable[N]): |
| 1276 |
pass |
| 1277 |
def g(ii: Iterable[int]): |
| 1278 |
pass |
| 1279 |
f(N) |
| 1280 |
g(N) |
| 1281 |
reveal_type(list(N)) |
| 1282 |
[out] |
| 1283 |
_testIntEnumIterable.py:11: note: Revealed type is "list[_testIntEnumIterable.N]" |
| 1284 |
|
| 1285 |
[case testDerivedEnumIterable] |
| 1286 |
from enum import Enum |
| 1287 |
from typing import Iterable |
| 1288 |
class E(str, Enum): |
| 1289 |
A = 'foo' |
| 1290 |
def f(ei: Iterable[E]): |
| 1291 |
pass |
| 1292 |
def g(si: Iterable[str]): |
| 1293 |
pass |
| 1294 |
f(E) |
| 1295 |
g(E) |
| 1296 |
|
| 1297 |
[case testInvalidSlots] |
| 1298 |
from typing import List |
| 1299 |
class A: |
| 1300 |
__slots__ = 1 |
| 1301 |
class B: |
| 1302 |
__slots__ = (1, 2) |
| 1303 |
class C: |
| 1304 |
__slots__: List[int] = [] |
| 1305 |
[out] |
| 1306 |
_testInvalidSlots.py:3: error: Invalid type for "__slots__" (actual type "int", expected type "str | Iterable[str]") |
| 1307 |
_testInvalidSlots.py:5: error: Invalid type for "__slots__" (actual type "tuple[int, int]", expected type "str | Iterable[str]") |
| 1308 |
_testInvalidSlots.py:7: error: Invalid type for "__slots__" (actual type "list[int]", expected type "str | Iterable[str]") |
| 1309 |
|
| 1310 |
[case testDictWithStarStarSpecialCase] |
| 1311 |
from typing import Dict |
| 1312 |
|
| 1313 |
def f() -> Dict[int, str]: |
| 1314 |
return {1: '', **d()} |
| 1315 |
|
| 1316 |
def d() -> Dict[int, int]: |
| 1317 |
return {} |
| 1318 |
[out] |
| 1319 |
_testDictWithStarStarSpecialCase.py:4: error: Unpacked dict entry 1 has incompatible type "dict[int, int]"; expected "SupportsKeysAndGetItem[int, str]" |
| 1320 |
|
| 1321 |
[case testLoadsOfOverloads] |
| 1322 |
from typing import overload, Any, TypeVar, Iterable, List, Dict, Callable, Union |
| 1323 |
|
| 1324 |
S = TypeVar('S') |
| 1325 |
T = TypeVar('T') |
| 1326 |
|
| 1327 |
@overload |
| 1328 |
def simple_map() -> None: ... |
| 1329 |
@overload |
| 1330 |
def simple_map(func: Callable[[T], S], one: Iterable[T]) -> S: ... |
| 1331 |
@overload |
| 1332 |
def simple_map(func: Callable[..., S], *iterables: Iterable[Any]) -> S: ... |
| 1333 |
def simple_map(*args): pass |
| 1334 |
|
| 1335 |
def format_row(*entries: object) -> str: pass |
| 1336 |
|
| 1337 |
class DateTime: pass |
| 1338 |
JsonBlob = Dict[str, Any] |
| 1339 |
Column = Union[List[str], List[int], List[bool], List[float], List[DateTime], List[JsonBlob]] |
| 1340 |
|
| 1341 |
def print_custom_table() -> None: |
| 1342 |
a: Column |
| 1343 |
|
| 1344 |
for row in simple_map(format_row, a, a, a, a, a, a, a, a): # 8 columns |
| 1345 |
reveal_type(row) |
| 1346 |
[out] |
| 1347 |
_testLoadsOfOverloads.py:24: note: Revealed type is "str" |
| 1348 |
|
| 1349 |
[case testReduceWithAnyInstance] |
| 1350 |
from typing import Iterable |
| 1351 |
from functools import reduce |
| 1352 |
M = Iterable |
| 1353 |
def f(m1: M, m2): |
| 1354 |
... |
| 1355 |
def g(ms: 'T[M]') -> None: |
| 1356 |
reduce(f, ms) |
| 1357 |
T = Iterable |
| 1358 |
[out] |
| 1359 |
|
| 1360 |
[case testNamedTupleNew] |
| 1361 |
# This is an eval test because there was a snag found only with full stubs |
| 1362 |
from typing import NamedTuple |
| 1363 |
|
| 1364 |
Base = NamedTuple('Base', [('param', int)]) |
| 1365 |
|
| 1366 |
class Child(Base): |
| 1367 |
def __new__(cls, param: int = 1) -> 'Child': |
| 1368 |
return Base.__new__(cls, param) |
| 1369 |
|
| 1370 |
Base(param=10) |
| 1371 |
Child(param=10) |
| 1372 |
reveal_type(Child()) |
| 1373 |
|
| 1374 |
from collections import namedtuple |
| 1375 |
X = namedtuple('X', ['a', 'b']) |
| 1376 |
x = X(a=1, b='s') |
| 1377 |
|
| 1378 |
[out] |
| 1379 |
_testNamedTupleNew.py:12: note: Revealed type is "tuple[int, fallback=_testNamedTupleNew.Child]" |
| 1380 |
|
| 1381 |
[case testNamedTupleTypeInheritanceSpecialCase] |
| 1382 |
from typing import NamedTuple, Tuple |
| 1383 |
from collections import namedtuple |
| 1384 |
|
| 1385 |
A = NamedTuple('A', [('param', int)]) |
| 1386 |
B = namedtuple('B', ['param']) |
| 1387 |
|
| 1388 |
def accepts_named_tuple(arg: NamedTuple): |
| 1389 |
reveal_type(arg._asdict()) |
| 1390 |
reveal_type(arg._fields) |
| 1391 |
reveal_type(arg._field_defaults) |
| 1392 |
|
| 1393 |
a = A(1) |
| 1394 |
b = B(1) |
| 1395 |
|
| 1396 |
accepts_named_tuple(a) |
| 1397 |
accepts_named_tuple(b) |
| 1398 |
accepts_named_tuple(1) |
| 1399 |
accepts_named_tuple((1, 2)) |
| 1400 |
[out] |
| 1401 |
_testNamedTupleTypeInheritanceSpecialCase.py:8: note: Revealed type is "dict[str, Any]" |
| 1402 |
_testNamedTupleTypeInheritanceSpecialCase.py:9: note: Revealed type is "tuple[str, ...]" |
| 1403 |
_testNamedTupleTypeInheritanceSpecialCase.py:10: note: Revealed type is "dict[str, Any]" |
| 1404 |
_testNamedTupleTypeInheritanceSpecialCase.py:17: error: Argument 1 to "accepts_named_tuple" has incompatible type "int"; expected "NamedTuple" |
| 1405 |
_testNamedTupleTypeInheritanceSpecialCase.py:18: error: Argument 1 to "accepts_named_tuple" has incompatible type "tuple[int, int]"; expected "NamedTuple" |
| 1406 |
|
| 1407 |
[case testNewAnalyzerBasicTypeshed_newsemanal] |
| 1408 |
from typing import Dict, List, Tuple |
| 1409 |
|
| 1410 |
x: Dict[str, List[int]] |
| 1411 |
reveal_type(x['test'][0]) |
| 1412 |
[out] |
| 1413 |
_testNewAnalyzerBasicTypeshed_newsemanal.py:4: note: Revealed type is "int" |
| 1414 |
|
| 1415 |
[case testNewAnalyzerTypedDictInStub_newsemanal] |
| 1416 |
import stub |
| 1417 |
reveal_type(stub.thing) |
| 1418 |
|
| 1419 |
[file stub.pyi] |
| 1420 |
from typing_extensions import TypedDict |
| 1421 |
|
| 1422 |
class StuffDict(TypedDict): |
| 1423 |
foo: str |
| 1424 |
bar: int |
| 1425 |
|
| 1426 |
def thing(stuff: StuffDict) -> int: ... |
| 1427 |
|
| 1428 |
[out] |
| 1429 |
_testNewAnalyzerTypedDictInStub_newsemanal.py:2: note: Revealed type is "def (stuff: TypedDict(stub.StuffDict, {'foo': str, 'bar': int})) -> int" |
| 1430 |
|
| 1431 |
[case testStrictEqualityAllowlist] |
| 1432 |
# mypy: strict-equality |
| 1433 |
{1} == frozenset({1}) |
| 1434 |
frozenset({1}) == {1} |
| 1435 |
|
| 1436 |
frozenset({1}) == [1] # Error |
| 1437 |
|
| 1438 |
{1: 2}.keys() == {1} |
| 1439 |
{1: 2}.keys() == frozenset({1}) |
| 1440 |
{1: 2}.items() == {(1, 2)} |
| 1441 |
|
| 1442 |
{1: 2}.keys() == {'no'} # OK |
| 1443 |
{1: 2}.values() == {2} # Error |
| 1444 |
{1: 2}.keys() == [1] # OK |
| 1445 |
[out] |
| 1446 |
_testStrictEqualityAllowlist.py:5: error: Non-overlapping equality check (left operand type: "frozenset[int]", right operand type: "list[int]") |
| 1447 |
_testStrictEqualityAllowlist.py:12: error: Non-overlapping equality check (left operand type: "dict_values[int, int]", right operand type: "set[int]") |
| 1448 |
|
| 1449 |
[case testUnreachableWithStdlibContextManagers] |
| 1450 |
# mypy: warn-unreachable, strict-optional |
| 1451 |
|
| 1452 |
from contextlib import suppress |
| 1453 |
|
| 1454 |
# This test overlaps with some of the warn-unreachable tests in check-unreachable-code, |
| 1455 |
# but 'open(...)' is a very common function so we want to make sure we don't regress |
| 1456 |
# against it specifically |
| 1457 |
def f_open() -> str: |
| 1458 |
with open("foo.txt", "r") as f: |
| 1459 |
return f.read() |
| 1460 |
print("noop") |
| 1461 |
|
| 1462 |
# contextlib.suppress is less common, but it's a fairly prominent example of an |
| 1463 |
# exception-suppressing context manager, so it'd be good to double-check. |
| 1464 |
def f_suppresses() -> int: |
| 1465 |
with suppress(Exception): |
| 1466 |
return 3 |
| 1467 |
print("noop") |
| 1468 |
[out] |
| 1469 |
_testUnreachableWithStdlibContextManagers.py:11: error: Statement is unreachable |
| 1470 |
_testUnreachableWithStdlibContextManagers.py:15: error: Missing return statement |
| 1471 |
|
| 1472 |
[case testUnreachableWithStdlibContextManagersNoStrictOptional] |
| 1473 |
# mypy: warn-unreachable, no-strict-optional |
| 1474 |
|
| 1475 |
from contextlib import suppress |
| 1476 |
|
| 1477 |
# When strict-optional is disabled, 'open' should still behave in the same way as before |
| 1478 |
def f_open() -> str: |
| 1479 |
with open("foo.txt", "r") as f: |
| 1480 |
return f.read() |
| 1481 |
print("noop") |
| 1482 |
|
| 1483 |
# ...but unfortunately, we can't |
| 1484 |
def f_suppresses() -> int: |
| 1485 |
with suppress(Exception): |
| 1486 |
return 3 |
| 1487 |
print("noop") |
| 1488 |
[out] |
| 1489 |
_testUnreachableWithStdlibContextManagersNoStrictOptional.py:9: error: Statement is unreachable |
| 1490 |
_testUnreachableWithStdlibContextManagersNoStrictOptional.py:15: error: Statement is unreachable |
| 1491 |
|
| 1492 |
[case testIsInstanceAdHocIntersectionWithStrAndBytes] |
| 1493 |
# mypy: warn-unreachable |
| 1494 |
x: str |
| 1495 |
if isinstance(x, bytes): |
| 1496 |
reveal_type(x) |
| 1497 |
y: str |
| 1498 |
if isinstance(x, int): |
| 1499 |
reveal_type(x) |
| 1500 |
[out] |
| 1501 |
_testIsInstanceAdHocIntersectionWithStrAndBytes.py:3: error: Subclass of "str" and "bytes" cannot exist: have distinct disjoint bases |
| 1502 |
_testIsInstanceAdHocIntersectionWithStrAndBytes.py:4: error: Statement is unreachable |
| 1503 |
_testIsInstanceAdHocIntersectionWithStrAndBytes.py:6: error: Subclass of "str" and "int" cannot exist: have distinct disjoint bases |
| 1504 |
_testIsInstanceAdHocIntersectionWithStrAndBytes.py:7: error: Statement is unreachable |
| 1505 |
|
| 1506 |
[case testAsyncioFutureWait] |
| 1507 |
# mypy: strict-optional |
| 1508 |
from asyncio import Future, wait |
| 1509 |
from typing import List |
| 1510 |
|
| 1511 |
async def foo() -> None: |
| 1512 |
f = [] # type: List[Future[None]] |
| 1513 |
await wait(f) |
| 1514 |
|
| 1515 |
[case testShadowTypingModule] |
| 1516 |
1 + '' |
| 1517 |
[file typing.py] |
| 1518 |
x = 0 |
| 1519 |
1 + '' |
| 1520 |
[out] |
| 1521 |
typing.py: error: This file shadows library module "typing" |
| 1522 |
typing.py: note: A user-defined top-level module with name "typing" is not supported |
| 1523 |
|
| 1524 |
|
| 1525 |
[case testNoPython3StubAvailable] |
| 1526 |
import scribe |
| 1527 |
from scribe import x |
| 1528 |
import pytz |
| 1529 |
[out] |
| 1530 |
_testNoPython3StubAvailable.py:1: error: Cannot find implementation or library stub for module named "scribe" |
| 1531 |
_testNoPython3StubAvailable.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports |
| 1532 |
_testNoPython3StubAvailable.py:3: error: Library stubs not installed for "pytz" |
| 1533 |
_testNoPython3StubAvailable.py:3: note: Hint: "python3 -m pip install types-pytz" |
| 1534 |
_testNoPython3StubAvailable.py:3: note: (or run "mypy --install-types" to install all missing stub packages) |
| 1535 |
|
| 1536 |
|
| 1537 |
[case testTypingOrderedDictAlias] |
| 1538 |
from typing import OrderedDict |
| 1539 |
x: OrderedDict[str, int] = OrderedDict({}) |
| 1540 |
reveal_type(x) |
| 1541 |
[out] |
| 1542 |
_testTypingOrderedDictAlias.py:3: note: Revealed type is "collections.OrderedDict[str, int]" |
| 1543 |
|
| 1544 |
[case testTypingExtensionsOrderedDictAlias] |
| 1545 |
from typing_extensions import OrderedDict |
| 1546 |
x: OrderedDict[str, str] = OrderedDict({}) |
| 1547 |
reveal_type(x) |
| 1548 |
[out] |
| 1549 |
_testTypingExtensionsOrderedDictAlias.py:3: note: Revealed type is "collections.OrderedDict[str, str]" |
| 1550 |
|
| 1551 |
[case testSpecialTypingProtocols] |
| 1552 |
# flags: --warn-unreachable |
| 1553 |
from typing import Awaitable, Hashable, Union, Tuple, List |
| 1554 |
|
| 1555 |
obj: Union[Tuple[int], List[int]] |
| 1556 |
if isinstance(obj, Hashable): |
| 1557 |
reveal_type(obj) |
| 1558 |
if isinstance(obj, Awaitable): |
| 1559 |
reveal_type(obj) |
| 1560 |
[out] |
| 1561 |
_testSpecialTypingProtocols.py:6: note: Revealed type is "tuple[int]" |
| 1562 |
_testSpecialTypingProtocols.py:8: error: Statement is unreachable |
| 1563 |
|
| 1564 |
[case testTypeshedRecursiveTypesExample] |
| 1565 |
from typing import List, Union |
| 1566 |
|
| 1567 |
Recursive = Union[str, List["Recursive"]] |
| 1568 |
|
| 1569 |
def foo(r: Recursive) -> None: |
| 1570 |
if not isinstance(r, str): |
| 1571 |
if r: |
| 1572 |
foo(r[0]) |
| 1573 |
if not isinstance(r, list): |
| 1574 |
r.casefold() |
| 1575 |
|
| 1576 |
foo("") |
| 1577 |
foo(list("")) |
| 1578 |
foo(list((list(""), ""))) |
| 1579 |
[out] |
| 1580 |
|
| 1581 |
[case testNarrowTypeForDictKeys] |
| 1582 |
from typing import Dict, KeysView, Optional |
| 1583 |
|
| 1584 |
d: Dict[str, int] |
| 1585 |
key: Optional[str] |
| 1586 |
if key in d.keys(): |
| 1587 |
reveal_type(key) |
| 1588 |
else: |
| 1589 |
reveal_type(key) |
| 1590 |
|
| 1591 |
kv: KeysView[str] |
| 1592 |
k: Optional[str] |
| 1593 |
if k in kv: |
| 1594 |
reveal_type(k) |
| 1595 |
else: |
| 1596 |
reveal_type(k) |
| 1597 |
|
| 1598 |
[out] |
| 1599 |
_testNarrowTypeForDictKeys.py:6: note: Revealed type is "str" |
| 1600 |
_testNarrowTypeForDictKeys.py:8: note: Revealed type is "str | None" |
| 1601 |
_testNarrowTypeForDictKeys.py:13: note: Revealed type is "str" |
| 1602 |
_testNarrowTypeForDictKeys.py:15: note: Revealed type is "str | None" |
| 1603 |
|
| 1604 |
[case testTypeAliasWithNewStyleUnion] |
| 1605 |
from typing import Literal, Type, TypeAlias, TypeVar |
| 1606 |
|
| 1607 |
Foo = Literal[1, 2] |
| 1608 |
reveal_type(Foo) |
| 1609 |
Bar1 = Foo | Literal[3] |
| 1610 |
Bar2 = Literal[3] | Foo |
| 1611 |
Bar3 = Foo | Foo | Literal[3] | Foo |
| 1612 |
|
| 1613 |
U1 = int | str |
| 1614 |
U2 = U1 | bytes |
| 1615 |
U3 = bytes | U1 |
| 1616 |
|
| 1617 |
Opt1 = None | int |
| 1618 |
Opt2 = None | float |
| 1619 |
Opt3 = int | None |
| 1620 |
Opt4 = float | None |
| 1621 |
|
| 1622 |
A = Type[int] | str |
| 1623 |
B: TypeAlias = Type[int] | str |
| 1624 |
C = type[int] | str |
| 1625 |
|
| 1626 |
D = type[int] | str |
| 1627 |
x: D |
| 1628 |
reveal_type(x) |
| 1629 |
E: TypeAlias = type[int] | str |
| 1630 |
y: E |
| 1631 |
reveal_type(y) |
| 1632 |
F = list[type[int] | str] |
| 1633 |
|
| 1634 |
T = TypeVar("T", int, str) |
| 1635 |
def foo(x: T) -> T: |
| 1636 |
A = type[int] | str |
| 1637 |
a: A |
| 1638 |
return x |
| 1639 |
[out] |
| 1640 |
_testTypeAliasWithNewStyleUnion.py:4: note: Revealed type is "typing._SpecialForm" |
| 1641 |
_testTypeAliasWithNewStyleUnion.py:24: note: Revealed type is "type[int] | str" |
| 1642 |
_testTypeAliasWithNewStyleUnion.py:27: note: Revealed type is "type[int] | str" |
| 1643 |
|
| 1644 |
[case testTypeAliasWithNewStyleUnionInStub] |
| 1645 |
import m |
| 1646 |
a: m.A |
| 1647 |
reveal_type(a) |
| 1648 |
b: m.B |
| 1649 |
reveal_type(b) |
| 1650 |
c: m.C |
| 1651 |
reveal_type(c) |
| 1652 |
d: m.D |
| 1653 |
reveal_type(d) |
| 1654 |
e: m.E |
| 1655 |
reveal_type(e) |
| 1656 |
f: m.F |
| 1657 |
reveal_type(f) |
| 1658 |
|
| 1659 |
[file m.pyi] |
| 1660 |
from typing import Type, Callable, Literal |
| 1661 |
from typing_extensions import TypeAlias |
| 1662 |
|
| 1663 |
Foo = Literal[1, 2] |
| 1664 |
reveal_type(Foo) |
| 1665 |
Bar1 = Foo | Literal[3] |
| 1666 |
Bar2 = Literal[3] | Foo |
| 1667 |
Bar3 = Foo | Foo | Literal[3] | Foo |
| 1668 |
|
| 1669 |
U1 = int | str |
| 1670 |
U2 = U1 | bytes |
| 1671 |
U3 = bytes | U1 |
| 1672 |
|
| 1673 |
Opt1 = None | int |
| 1674 |
Opt2 = None | float |
| 1675 |
Opt3 = int | None |
| 1676 |
Opt4 = float | None |
| 1677 |
|
| 1678 |
A = Type[int] | str |
| 1679 |
B: TypeAlias = Type[int] | str |
| 1680 |
C = type[int] | str |
| 1681 |
reveal_type(C) |
| 1682 |
D: TypeAlias = type[int] | str |
| 1683 |
E = str | type[int] |
| 1684 |
F: TypeAlias = str | type[int] |
| 1685 |
G = list[type[int] | str] |
| 1686 |
H = list[str | type[int]] |
| 1687 |
|
| 1688 |
CU1 = int | Callable[[], str | bool] |
| 1689 |
CU2: TypeAlias = int | Callable[[], str | bool] |
| 1690 |
CU3 = int | Callable[[str | bool], str] |
| 1691 |
CU4: TypeAlias = int | Callable[[str | bool], str] |
| 1692 |
[out] |
| 1693 |
m.pyi:5: note: Revealed type is "typing._SpecialForm" |
| 1694 |
m.pyi:22: note: Revealed type is "types.UnionType[type[int], str]" |
| 1695 |
_testTypeAliasWithNewStyleUnionInStub.py:3: note: Revealed type is "type[int] | str" |
| 1696 |
_testTypeAliasWithNewStyleUnionInStub.py:5: note: Revealed type is "type[int] | str" |
| 1697 |
_testTypeAliasWithNewStyleUnionInStub.py:7: note: Revealed type is "type[int] | str" |
| 1698 |
_testTypeAliasWithNewStyleUnionInStub.py:9: note: Revealed type is "type[int] | str" |
| 1699 |
_testTypeAliasWithNewStyleUnionInStub.py:11: note: Revealed type is "str | type[int]" |
| 1700 |
_testTypeAliasWithNewStyleUnionInStub.py:13: note: Revealed type is "str | type[int]" |
| 1701 |
|
| 1702 |
[case testEnumNameWorkCorrectlyOn311] |
| 1703 |
# flags: --python-version 3.11 |
| 1704 |
import enum |
| 1705 |
|
| 1706 |
class E(enum.Enum): |
| 1707 |
X = 1 |
| 1708 |
Y = 2 |
| 1709 |
@enum.property |
| 1710 |
def foo(self) -> int: ... |
| 1711 |
|
| 1712 |
e: E |
| 1713 |
reveal_type(e.name) |
| 1714 |
reveal_type(e.value) |
| 1715 |
reveal_type(E.X.name) |
| 1716 |
reveal_type(e.foo) |
| 1717 |
reveal_type(E.Y.foo) |
| 1718 |
[out] |
| 1719 |
_testEnumNameWorkCorrectlyOn311.py:11: note: Revealed type is "str" |
| 1720 |
_testEnumNameWorkCorrectlyOn311.py:12: note: Revealed type is "Literal[1]? | Literal[2]?" |
| 1721 |
_testEnumNameWorkCorrectlyOn311.py:13: note: Revealed type is "Literal['X']?" |
| 1722 |
_testEnumNameWorkCorrectlyOn311.py:14: note: Revealed type is "int" |
| 1723 |
_testEnumNameWorkCorrectlyOn311.py:15: note: Revealed type is "int" |
| 1724 |
|
| 1725 |
[case testTypedDictUnionGetFull] |
| 1726 |
from typing import Dict |
| 1727 |
from typing_extensions import TypedDict |
| 1728 |
|
| 1729 |
class TD(TypedDict, total=False): |
| 1730 |
x: int |
| 1731 |
y: int |
| 1732 |
|
| 1733 |
A = Dict[str, TD] |
| 1734 |
x: A |
| 1735 |
def foo(k: str) -> TD: |
| 1736 |
reveal_type(x.get(k, {})) |
| 1737 |
return x.get(k, {}) |
| 1738 |
[out] |
| 1739 |
_testTypedDictUnionGetFull.py:11: note: Revealed type is "TypedDict(_testTypedDictUnionGetFull.TD, {'x'?: int, 'y'?: int})" |
| 1740 |
|
| 1741 |
[case testTupleWithDifferentArgsPy310] |
| 1742 |
# https://github.com/python/mypy/issues/11098 |
| 1743 |
Correct1 = str | tuple[float, float, str] |
| 1744 |
Correct2 = tuple[float] | str |
| 1745 |
Correct3 = tuple[float, ...] | str |
| 1746 |
Correct4 = tuple[float, str] |
| 1747 |
Correct5 = tuple[float, ...] |
| 1748 |
Correct6 = list[tuple[int, str]] |
| 1749 |
c1: Correct1 |
| 1750 |
c2: Correct2 |
| 1751 |
c3: Correct3 |
| 1752 |
c4: Correct4 |
| 1753 |
c5: Correct5 |
| 1754 |
c6: Correct6 |
| 1755 |
reveal_type(c1) |
| 1756 |
reveal_type(c2) |
| 1757 |
reveal_type(c3) |
| 1758 |
reveal_type(c4) |
| 1759 |
reveal_type(c5) |
| 1760 |
reveal_type(c6) |
| 1761 |
|
| 1762 |
RHSAlias1: type = tuple[int, int] |
| 1763 |
RHSAlias2: type = tuple[int] |
| 1764 |
RHSAlias3: type = tuple[int, ...] |
| 1765 |
|
| 1766 |
WrongTypeElement = str | tuple[float, 1] # Error |
| 1767 |
WrongEllipsis = tuple[float, float, ...] | str # Error |
| 1768 |
|
| 1769 |
reveal_type(tuple[int, str]((1, "x"))) |
| 1770 |
[out] |
| 1771 |
_testTupleWithDifferentArgsPy310.py:14: note: Revealed type is "str | tuple[float, float, str]" |
| 1772 |
_testTupleWithDifferentArgsPy310.py:15: note: Revealed type is "tuple[float] | str" |
| 1773 |
_testTupleWithDifferentArgsPy310.py:16: note: Revealed type is "tuple[float, ...] | str" |
| 1774 |
_testTupleWithDifferentArgsPy310.py:17: note: Revealed type is "tuple[float, str]" |
| 1775 |
_testTupleWithDifferentArgsPy310.py:18: note: Revealed type is "tuple[float, ...]" |
| 1776 |
_testTupleWithDifferentArgsPy310.py:19: note: Revealed type is "list[tuple[int, str]]" |
| 1777 |
_testTupleWithDifferentArgsPy310.py:25: error: Invalid type: try using Literal[1] instead? |
| 1778 |
_testTupleWithDifferentArgsPy310.py:26: error: Unexpected "..." |
| 1779 |
_testTupleWithDifferentArgsPy310.py:28: note: Revealed type is "tuple[int, str]" |
| 1780 |
|
| 1781 |
[case testEnumIterMetaInference] |
| 1782 |
import socket |
| 1783 |
from enum import Enum |
| 1784 |
from typing import Iterable, Iterator, Type, TypeVar |
| 1785 |
|
| 1786 |
_E = TypeVar("_E", bound=Enum) |
| 1787 |
|
| 1788 |
def enum_iter(cls: Type[_E]) -> Iterable[_E]: |
| 1789 |
reveal_type(iter(cls)) |
| 1790 |
reveal_type(next(iter(cls))) |
| 1791 |
return iter(cls) |
| 1792 |
|
| 1793 |
for value in enum_iter(socket.SocketKind): |
| 1794 |
reveal_type(value) |
| 1795 |
[out] |
| 1796 |
_testEnumIterMetaInference.py:8: note: Revealed type is "typing.Iterator[_E]" |
| 1797 |
_testEnumIterMetaInference.py:9: note: Revealed type is "_E" |
| 1798 |
_testEnumIterMetaInference.py:13: note: Revealed type is "socket.SocketKind" |
| 1799 |
|
| 1800 |
[case testEnumUnpackedViaMetaclass] |
| 1801 |
from enum import Enum |
| 1802 |
|
| 1803 |
class FooEnum(Enum): |
| 1804 |
A = 1 |
| 1805 |
B = 2 |
| 1806 |
C = 3 |
| 1807 |
|
| 1808 |
a, b, c = FooEnum |
| 1809 |
reveal_type(a) |
| 1810 |
reveal_type(b) |
| 1811 |
reveal_type(c) |
| 1812 |
[out] |
| 1813 |
_testEnumUnpackedViaMetaclass.py:9: note: Revealed type is "_testEnumUnpackedViaMetaclass.FooEnum" |
| 1814 |
_testEnumUnpackedViaMetaclass.py:10: note: Revealed type is "_testEnumUnpackedViaMetaclass.FooEnum" |
| 1815 |
_testEnumUnpackedViaMetaclass.py:11: note: Revealed type is "_testEnumUnpackedViaMetaclass.FooEnum" |
| 1816 |
|
| 1817 |
[case testNativeIntTypes] |
| 1818 |
# Spot check various native int operations with full stubs. |
| 1819 |
from mypy_extensions import i64, i32 |
| 1820 |
|
| 1821 |
x: i64 = 0 |
| 1822 |
y: int = x |
| 1823 |
x = i64(0) |
| 1824 |
y = int(x) |
| 1825 |
i64() |
| 1826 |
i64("12") |
| 1827 |
i64("ab", 16) |
| 1828 |
i64(1.2) |
| 1829 |
float(i64(1)) |
| 1830 |
|
| 1831 |
i64(1) + i32(2) # Error |
| 1832 |
reveal_type(x + y) |
| 1833 |
reveal_type(y + x) |
| 1834 |
a = [0] |
| 1835 |
a[x] |
| 1836 |
[out] |
| 1837 |
_testNativeIntTypes.py:14: error: Unsupported operand types for + ("i64" and "i32") |
| 1838 |
_testNativeIntTypes.py:15: note: Revealed type is "mypy_extensions.i64" |
| 1839 |
_testNativeIntTypes.py:16: note: Revealed type is "mypy_extensions.i64" |
| 1840 |
|
| 1841 |
[case testStarUnpackNestedUnderscore] |
| 1842 |
from typing import Tuple, Dict, List |
| 1843 |
|
| 1844 |
def crash() -> None: |
| 1845 |
d: Dict[int, Tuple[str, int, str]] = {} |
| 1846 |
k, (v1, *_) = next(iter(d.items())) |
| 1847 |
|
| 1848 |
def test1() -> None: |
| 1849 |
vs: List[str] |
| 1850 |
d: Dict[int, Tuple[str, int, int]] = {} |
| 1851 |
k, (v1, *vs) = next(iter(d.items())) |
| 1852 |
reveal_type(vs) |
| 1853 |
|
| 1854 |
def test2() -> None: |
| 1855 |
d: Dict[int, Tuple[str, int, str]] = {} |
| 1856 |
k, (v1, *vs) = next(iter(d.items())) |
| 1857 |
reveal_type(vs) |
| 1858 |
[out] |
| 1859 |
_testStarUnpackNestedUnderscore.py:10: error: List item 0 has incompatible type "int"; expected "str" |
| 1860 |
_testStarUnpackNestedUnderscore.py:10: error: List item 1 has incompatible type "int"; expected "str" |
| 1861 |
_testStarUnpackNestedUnderscore.py:11: note: Revealed type is "list[str]" |
| 1862 |
_testStarUnpackNestedUnderscore.py:16: note: Revealed type is "list[object]" |
| 1863 |
|
| 1864 |
[case testStrictEqualitywithParamSpec] |
| 1865 |
# flags: --strict-equality |
| 1866 |
from typing import Generic |
| 1867 |
from typing_extensions import Concatenate, ParamSpec |
| 1868 |
|
| 1869 |
P = ParamSpec("P") |
| 1870 |
|
| 1871 |
class Foo(Generic[P]): ... |
| 1872 |
class Bar(Generic[P]): ... |
| 1873 |
|
| 1874 |
def bad(foo: Foo[[int]], bar: Bar[[int]]) -> bool: |
| 1875 |
return foo == bar |
| 1876 |
|
| 1877 |
def bad1(foo1: Foo[[int]], foo2: Foo[[str]]) -> bool: |
| 1878 |
return foo1 == foo2 |
| 1879 |
|
| 1880 |
def bad2(foo1: Foo[[int, str]], foo2: Foo[[int, bytes]]) -> bool: |
| 1881 |
return foo1 == foo2 |
| 1882 |
|
| 1883 |
def bad3(foo1: Foo[[int]], foo2: Foo[[int, int]]) -> bool: |
| 1884 |
return foo1 == foo2 |
| 1885 |
|
| 1886 |
def good4(foo1: Foo[[int]], foo2: Foo[[int]]) -> bool: |
| 1887 |
return foo1 == foo2 |
| 1888 |
|
| 1889 |
def good5(foo1: Foo[[int]], foo2: Foo[[bool]]) -> bool: |
| 1890 |
return foo1 == foo2 |
| 1891 |
|
| 1892 |
def good6(foo1: Foo[[int, int]], foo2: Foo[[bool, bool]]) -> bool: |
| 1893 |
return foo1 == foo2 |
| 1894 |
|
| 1895 |
def good7(foo1: Foo[[int]], foo2: Foo[P], *args: P.args, **kwargs: P.kwargs) -> bool: |
| 1896 |
return foo1 == foo2 |
| 1897 |
|
| 1898 |
def good8(foo1: Foo[P], foo2: Foo[[int, str, bytes]], *args: P.args, **kwargs: P.kwargs) -> bool: |
| 1899 |
return foo1 == foo2 |
| 1900 |
|
| 1901 |
def good9(foo1: Foo[Concatenate[int, P]], foo2: Foo[[int, str, bytes]], *args: P.args, **kwargs: P.kwargs) -> bool: |
| 1902 |
return foo1 == foo2 |
| 1903 |
|
| 1904 |
[out] |
| 1905 |
_testStrictEqualitywithParamSpec.py:11: error: Non-overlapping equality check (left operand type: "Foo[[int]]", right operand type: "Bar[[int]]") |
| 1906 |
_testStrictEqualitywithParamSpec.py:14: error: Non-overlapping equality check (left operand type: "Foo[[int]]", right operand type: "Foo[[str]]") |
| 1907 |
_testStrictEqualitywithParamSpec.py:17: error: Non-overlapping equality check (left operand type: "Foo[[int, str]]", right operand type: "Foo[[int, bytes]]") |
| 1908 |
_testStrictEqualitywithParamSpec.py:20: error: Non-overlapping equality check (left operand type: "Foo[[int]]", right operand type: "Foo[[int, int]]") |
| 1909 |
|
| 1910 |
[case testInferenceOfDunderDictOnClassObjects] |
| 1911 |
class Foo: ... |
| 1912 |
reveal_type(Foo.__dict__) |
| 1913 |
reveal_type(Foo().__dict__) |
| 1914 |
Foo.__dict__ = {} |
| 1915 |
Foo().__dict__ = {} |
| 1916 |
|
| 1917 |
[out] |
| 1918 |
_testInferenceOfDunderDictOnClassObjects.py:2: note: Revealed type is "types.MappingProxyType[str, Any]" |
| 1919 |
_testInferenceOfDunderDictOnClassObjects.py:3: note: Revealed type is "dict[str, Any]" |
| 1920 |
_testInferenceOfDunderDictOnClassObjects.py:4: error: Cannot assign to final attribute "__dict__" |
| 1921 |
_testInferenceOfDunderDictOnClassObjects.py:4: error: Incompatible types in assignment (expression has type "dict[Never, Never]", variable has type "MappingProxyType[str, Any]") |
| 1922 |
|
| 1923 |
[case testTypeVarTuple] |
| 1924 |
# flags: --python-version=3.11 |
| 1925 |
from typing import Any, Callable, Unpack, TypeVarTuple |
| 1926 |
|
| 1927 |
Ts = TypeVarTuple("Ts") |
| 1928 |
|
| 1929 |
def foo(callback: Callable[[], Any]) -> None: |
| 1930 |
call(callback) |
| 1931 |
|
| 1932 |
def call(callback: Callable[[Unpack[Ts]], Any], *args: Unpack[Ts]) -> Any: |
| 1933 |
... |
| 1934 |
|
| 1935 |
[case testTypeVarTupleTypingExtensions] |
| 1936 |
from typing_extensions import Unpack, TypeVarTuple |
| 1937 |
from typing import Any, Callable |
| 1938 |
|
| 1939 |
Ts = TypeVarTuple("Ts") |
| 1940 |
|
| 1941 |
def foo(callback: Callable[[], Any]) -> None: |
| 1942 |
call(callback) |
| 1943 |
|
| 1944 |
def call(callback: Callable[[Unpack[Ts]], Any], *args: Unpack[Ts]) -> Any: |
| 1945 |
... |
| 1946 |
|
| 1947 |
[case testDataclassReplace] |
| 1948 |
from dataclasses import dataclass, replace |
| 1949 |
|
| 1950 |
@dataclass |
| 1951 |
class A: |
| 1952 |
x: int |
| 1953 |
|
| 1954 |
a = A(x=42) |
| 1955 |
a2 = replace(a, x=42) |
| 1956 |
reveal_type(a2) |
| 1957 |
a2 = replace() |
| 1958 |
a2 = replace(a, x='spam') |
| 1959 |
a2 = replace(a, x=42, q=42) |
| 1960 |
[out] |
| 1961 |
_testDataclassReplace.py:9: note: Revealed type is "_testDataclassReplace.A" |
| 1962 |
_testDataclassReplace.py:10: error: Too few arguments for "replace" |
| 1963 |
_testDataclassReplace.py:11: error: Argument "x" to "replace" of "A" has incompatible type "str"; expected "int" |
| 1964 |
_testDataclassReplace.py:12: error: Unexpected keyword argument "q" for "replace" of "A" |
| 1965 |
|
| 1966 |
[case testGenericInferenceWithTuple] |
| 1967 |
from typing import TypeVar, Callable, Tuple |
| 1968 |
|
| 1969 |
T = TypeVar("T") |
| 1970 |
|
| 1971 |
def f(x: Callable[..., T]) -> T: |
| 1972 |
return x() |
| 1973 |
|
| 1974 |
x: Tuple[str, ...] = f(tuple) |
| 1975 |
[out] |
| 1976 |
|
| 1977 |
[case testGenericInferenceWithDataclass] |
| 1978 |
from typing import Any, Collection, List |
| 1979 |
from dataclasses import dataclass, field |
| 1980 |
|
| 1981 |
class Foo: |
| 1982 |
pass |
| 1983 |
|
| 1984 |
@dataclass |
| 1985 |
class A: |
| 1986 |
items: Collection[Foo] = field(default_factory=list) |
| 1987 |
[out] |
| 1988 |
|
| 1989 |
[case testGenericInferenceWithItertools] |
| 1990 |
from typing import TypeVar, Tuple |
| 1991 |
from itertools import groupby |
| 1992 |
K = TypeVar("K") |
| 1993 |
V = TypeVar("V") |
| 1994 |
|
| 1995 |
def fst(kv: Tuple[K, V]) -> K: |
| 1996 |
k, v = kv |
| 1997 |
return k |
| 1998 |
|
| 1999 |
pairs = [(len(s), s) for s in ["one", "two", "three"]] |
| 2000 |
grouped = groupby(pairs, key=fst) |
| 2001 |
[out] |
| 2002 |
|
| 2003 |
[case testDataclassReplaceOptional] |
| 2004 |
from dataclasses import dataclass, replace |
| 2005 |
from typing import Optional |
| 2006 |
|
| 2007 |
@dataclass |
| 2008 |
class A: |
| 2009 |
x: Optional[int] |
| 2010 |
|
| 2011 |
a = A(x=42) |
| 2012 |
reveal_type(a) |
| 2013 |
a2 = replace(a, x=None) # OK |
| 2014 |
reveal_type(a2) |
| 2015 |
[out] |
| 2016 |
_testDataclassReplaceOptional.py:9: note: Revealed type is "_testDataclassReplaceOptional.A" |
| 2017 |
_testDataclassReplaceOptional.py:11: note: Revealed type is "_testDataclassReplaceOptional.A" |
| 2018 |
|
| 2019 |
[case testDataclassStrictOptionalAlwaysSet] |
| 2020 |
from dataclasses import dataclass |
| 2021 |
from typing import Callable, Optional |
| 2022 |
|
| 2023 |
@dataclass |
| 2024 |
class Description: |
| 2025 |
name_fn: Callable[[Optional[int]], Optional[str]] |
| 2026 |
|
| 2027 |
def f(d: Description) -> None: |
| 2028 |
reveal_type(d.name_fn) |
| 2029 |
[out] |
| 2030 |
_testDataclassStrictOptionalAlwaysSet.py:9: note: Revealed type is "def (int | None) -> str | None" |
| 2031 |
|
| 2032 |
[case testPEP695VarianceInference] |
| 2033 |
# flags: --python-version=3.12 |
| 2034 |
from typing import Callable, Final |
| 2035 |
|
| 2036 |
class Job[_R_co]: |
| 2037 |
def __init__(self, target: Callable[[], _R_co]) -> None: |
| 2038 |
self.target: Final = target |
| 2039 |
|
| 2040 |
def func( |
| 2041 |
action: Job[int | None], |
| 2042 |
a1: Job[int | None], |
| 2043 |
a2: Job[int], |
| 2044 |
a3: Job[None], |
| 2045 |
) -> None: |
| 2046 |
action = a1 |
| 2047 |
action = a2 |
| 2048 |
action = a3 |
| 2049 |
a2 = action # Error |
| 2050 |
[out] |
| 2051 |
_testPEP695VarianceInference.py:17: error: Incompatible types in assignment (expression has type "Job[None]", variable has type "Job[int]") |
| 2052 |
|
| 2053 |
[case testPEP695TypeAliasWithDifferentTargetTypes] |
| 2054 |
# flags: --python-version=3.12 |
| 2055 |
from typing import Any, Callable, List, Literal, TypedDict, overload, TypeAlias, TypeVar, Never |
| 2056 |
|
| 2057 |
class C[T]: pass |
| 2058 |
|
| 2059 |
class O[T]: |
| 2060 |
@overload |
| 2061 |
def __init__(self) -> None: ... |
| 2062 |
@overload |
| 2063 |
def __init__(self, x: int) -> None: ... |
| 2064 |
def __init__(self, x: int = 0) -> None: |
| 2065 |
pass |
| 2066 |
|
| 2067 |
class TD(TypedDict): |
| 2068 |
x: int |
| 2069 |
|
| 2070 |
S = TypeVar("S") |
| 2071 |
A = list[S] |
| 2072 |
B: TypeAlias = list[S] |
| 2073 |
|
| 2074 |
type A1 = type[int] |
| 2075 |
type A2 = type[int] | None |
| 2076 |
type A3 = None | type[int] |
| 2077 |
type A4 = type[Any] |
| 2078 |
type A5 = type[C] | None |
| 2079 |
type A6 = None | type[C] |
| 2080 |
type A7 = type[O] | None |
| 2081 |
type A8 = None | type[O] |
| 2082 |
|
| 2083 |
type B1[**P, R] = Callable[P, R] | None |
| 2084 |
type B2[**P, R] = None | Callable[P, R] |
| 2085 |
type B3 = Callable[[str], int] |
| 2086 |
type B4 = Callable[..., int] |
| 2087 |
|
| 2088 |
type C1 = A1 | None |
| 2089 |
type C2 = None | A1 |
| 2090 |
|
| 2091 |
type D1 = Any | None |
| 2092 |
type D2 = None | Any |
| 2093 |
|
| 2094 |
type E1 = List[int] |
| 2095 |
type E2 = List[int] | None |
| 2096 |
type E3 = None | List[int] |
| 2097 |
|
| 2098 |
type F1 = Literal[1] |
| 2099 |
type F2 = Literal['x'] | None |
| 2100 |
type F3 = None | Literal[True] |
| 2101 |
|
| 2102 |
type G1 = tuple[int, Any] |
| 2103 |
type G2 = tuple[int, Any] | None |
| 2104 |
type G3 = None | tuple[int, Any] |
| 2105 |
|
| 2106 |
type H1 = TD |
| 2107 |
type H2 = TD | None |
| 2108 |
type H3 = None | TD |
| 2109 |
|
| 2110 |
type I1 = C[int] |
| 2111 |
type I2 = C[Any] | None |
| 2112 |
type I3 = None | C[TD] |
| 2113 |
type I4 = O[int] | None |
| 2114 |
type I5 = None | O[int] |
| 2115 |
|
| 2116 |
type J1[T] = T | None |
| 2117 |
type J2[T] = None | T |
| 2118 |
type J3[*Ts] = tuple[*Ts] |
| 2119 |
type J4[T] = J1[T] | None |
| 2120 |
type J5[T] = None | J1[T] |
| 2121 |
type J6[*Ts] = J3[*Ts] | None |
| 2122 |
|
| 2123 |
type K1 = A[int] | None |
| 2124 |
type K2 = None | A[int] |
| 2125 |
type K3 = B[int] | None |
| 2126 |
type K4 = None | B[int] |
| 2127 |
|
| 2128 |
type L1 = Never |
| 2129 |
type L2 = list[Never] |
| 2130 |
|
| 2131 |
[case testPEP695VarianceInferenceSpecialCaseWithTypeshed] |
| 2132 |
# flags: --python-version=3.12 |
| 2133 |
class C1[T1, T2](list[T1]): |
| 2134 |
def m(self, a: T2) -> None: ... |
| 2135 |
|
| 2136 |
def func1(p: C1[int, object]): |
| 2137 |
x: C1[int, int] = p |
| 2138 |
|
| 2139 |
class C2[T1, T2, T3](dict[T2, T3]): |
| 2140 |
def m(self, a: T1) -> None: ... |
| 2141 |
|
| 2142 |
def func2(p: C2[object, int, int]): |
| 2143 |
x: C2[int, int, int] = p |
| 2144 |
|
| 2145 |
class C3[T1, T2](tuple[T1, ...]): |
| 2146 |
def m(self, a: T2) -> None: ... |
| 2147 |
|
| 2148 |
def func3(p: C3[int, object]): |
| 2149 |
x: C3[int, int] = p |
| 2150 |
|
| 2151 |
|
| 2152 |
[case testDynamicClassAttribute] |
| 2153 |
# Some things that can break if DynamicClassAttribute isn't handled properly |
| 2154 |
from types import DynamicClassAttribute |
| 2155 |
from enum import Enum |
| 2156 |
|
| 2157 |
class TestClass: |
| 2158 |
@DynamicClassAttribute |
| 2159 |
def name(self) -> str: ... |
| 2160 |
|
| 2161 |
class TestClass2(TestClass, Enum): ... |
| 2162 |
|
| 2163 |
class Status(Enum): |
| 2164 |
ABORTED = -1 |
| 2165 |
|
| 2166 |
def imperfect(status: Status) -> str: |
| 2167 |
return status.name.lower() |
| 2168 |
|
| 2169 |
[case testUnpackIteratorBuiltins] |
| 2170 |
# Regression test for https://github.com/python/mypy/issues/18320 |
| 2171 |
# Caused by https://github.com/python/typeshed/pull/12851 |
| 2172 |
x = [1, 2] |
| 2173 |
reveal_type([*reversed(x)]) |
| 2174 |
reveal_type([*map(str, x)]) |
| 2175 |
[out] |
| 2176 |
_testUnpackIteratorBuiltins.py:4: note: Revealed type is "list[int]" |
| 2177 |
_testUnpackIteratorBuiltins.py:5: note: Revealed type is "list[str]" |
| 2178 |
|
| 2179 |
[case testReturnFallbackInferenceDict] |
| 2180 |
# Requires full dict stubs. |
| 2181 |
from typing import Dict, Mapping, TypeVar, Union |
| 2182 |
|
| 2183 |
K = TypeVar("K") |
| 2184 |
V = TypeVar("V") |
| 2185 |
K2 = TypeVar("K2") |
| 2186 |
V2 = TypeVar("V2") |
| 2187 |
|
| 2188 |
def func(one: Dict[K, V], two: Mapping[K2, V2]) -> Dict[Union[K, K2], Union[V, V2]]: |
| 2189 |
... |
| 2190 |
|
| 2191 |
def caller(arg1: Mapping[K, V], arg2: Mapping[K2, V2]) -> Dict[Union[K, K2], Union[V, V2]]: |
| 2192 |
_arg1 = arg1 if isinstance(arg1, dict) else dict(arg1) |
| 2193 |
return func(_arg1, arg2) |
| 2194 |
|
| 2195 |
[case testStrictEqualityWithList] |
| 2196 |
# flags: --strict-equality |
| 2197 |
def f(x: int, y: list[str]): |
| 2198 |
x in y |
| 2199 |
[out] |
| 2200 |
_testStrictEqualityWithList.py:3: error: Non-overlapping container check (element type: "int", container item type: "str") |
| 2201 |
|
| 2202 |
[case testDictOrUnionEdgeCases] |
| 2203 |
from typing import Mapping, Sequence, Union |
| 2204 |
|
| 2205 |
d: dict[str, list[str]] |
| 2206 |
m: Mapping[str, Sequence[str]] = d | d |
| 2207 |
|
| 2208 |
A = dict[str, Union[A, int]] |
| 2209 |
d1: A |
| 2210 |
d2: A |
| 2211 |
d3: A = d1 | d2 |
| 2212 |
reveal_type(d1 | d2) |
| 2213 |
[out] |
| 2214 |
_testDictOrUnionEdgeCases.py:10: note: Revealed type is "dict[str, dict[str, ... | int] | int]" |
| 2215 |
|
| 2216 |
[case testNarrowingMappingAndAbstractSet] |
| 2217 |
# flags: --strict-equality --warn-unreachable |
| 2218 |
from typing import Mapping, AbstractSet |
| 2219 |
|
| 2220 |
def f1(x: Mapping[str, int], y: dict[str, int]) -> None: |
| 2221 |
if isinstance(x, dict): |
| 2222 |
reveal_type(x) |
| 2223 |
|
| 2224 |
if x == y: |
| 2225 |
reveal_type(x) |
| 2226 |
reveal_type(y) |
| 2227 |
|
| 2228 |
if x == {}: |
| 2229 |
reveal_type(x) |
| 2230 |
|
| 2231 |
def f2(x: AbstractSet[int], y: set[int]) -> None: |
| 2232 |
if isinstance(x, set): |
| 2233 |
reveal_type(x) |
| 2234 |
|
| 2235 |
if x == y: |
| 2236 |
reveal_type(x) |
| 2237 |
reveal_type(y) |
| 2238 |
|
| 2239 |
if x == set(): |
| 2240 |
reveal_type(x) |
| 2241 |
|
| 2242 |
def f3(x: frozenset[int], y: set[int]): |
| 2243 |
if x == y: |
| 2244 |
reveal_type(x) |
| 2245 |
reveal_type(y) |
| 2246 |
|
| 2247 |
def f4(x: dict[str, int], y: set[str]): |
| 2248 |
if x.keys() == y: |
| 2249 |
reveal_type(x) |
| 2250 |
reveal_type(y) |
| 2251 |
|
| 2252 |
z = x.keys() |
| 2253 |
if z == y: |
| 2254 |
reveal_type(z) |
| 2255 |
reveal_type(y) |
| 2256 |
[out] |
| 2257 |
_testNarrowingMappingAndAbstractSet.py:6: note: Revealed type is "dict[Any, Any]" |
| 2258 |
_testNarrowingMappingAndAbstractSet.py:9: note: Revealed type is "typing.Mapping[str, int]" |
| 2259 |
_testNarrowingMappingAndAbstractSet.py:10: note: Revealed type is "dict[str, int]" |
| 2260 |
_testNarrowingMappingAndAbstractSet.py:13: note: Revealed type is "typing.Mapping[str, int]" |
| 2261 |
_testNarrowingMappingAndAbstractSet.py:17: note: Revealed type is "set[Any]" |
| 2262 |
_testNarrowingMappingAndAbstractSet.py:20: note: Revealed type is "typing.AbstractSet[int]" |
| 2263 |
_testNarrowingMappingAndAbstractSet.py:21: note: Revealed type is "set[int]" |
| 2264 |
_testNarrowingMappingAndAbstractSet.py:24: note: Revealed type is "typing.AbstractSet[int]" |
| 2265 |
_testNarrowingMappingAndAbstractSet.py:28: note: Revealed type is "frozenset[int]" |
| 2266 |
_testNarrowingMappingAndAbstractSet.py:29: note: Revealed type is "set[int]" |
| 2267 |
_testNarrowingMappingAndAbstractSet.py:33: note: Revealed type is "dict[str, int]" |
| 2268 |
_testNarrowingMappingAndAbstractSet.py:34: note: Revealed type is "set[str]" |
| 2269 |
_testNarrowingMappingAndAbstractSet.py:38: note: Revealed type is "_collections_abc.dict_keys[str, int]" |
| 2270 |
_testNarrowingMappingAndAbstractSet.py:39: note: Revealed type is "set[str]" |
| 2271 |
|
| 2272 |
[case testNativeParserTStringRequiresPython314] |
| 2273 |
# flags: --python-version=3.13 --native-parser --ignore-missing-imports |
| 2274 |
x = t"hello {1}" |
| 2275 |
reveal_type(x) |
| 2276 |
[out] |
| 2277 |
_testNativeParserTStringRequiresPython314.py:2: error: T-strings: requires Python 3.14 or newer (current target: Python 3.13) |
| 2278 |
_testNativeParserTStringRequiresPython314.py:3: note: Revealed type is "Any" |
| 2279 |
|
| 2280 |
[case testNativeParserTStringRequiresPython314InStub] |
| 2281 |
# flags: --python-version=3.13 --native-parser --ignore-missing-imports |
| 2282 |
import m |
| 2283 |
[file m.pyi] |
| 2284 |
x: object |
| 2285 |
def f() -> object: ... |
| 2286 |
y = t"hello {1}" |
| 2287 |
[out] |
| 2288 |
m.pyi:3: error: T-strings: requires Python 3.14 or newer (current target: Python 3.13) |
| 2289 |
|
| 2290 |
[case testNativeParserStarUnpackRequiresPython311] |
| 2291 |
# flags: --python-version=3.10 --native-parser |
| 2292 |
from typing_extensions import TypeVarTuple, Unpack |
| 2293 |
Ts = TypeVarTuple("Ts") |
| 2294 |
def f(x: tuple[Unpack[Ts]]) -> None: ... |
| 2295 |
def g(x: tuple[*Ts]) -> None: ... |
| 2296 |
reveal_type(g) |
| 2297 |
g((1, 2)) |
| 2298 |
[out] |
| 2299 |
_testNativeParserStarUnpackRequiresPython311.py:5: error: Star unpack syntax: requires Python 3.11 or newer (current target: Python 3.10) |
| 2300 |
_testNativeParserStarUnpackRequiresPython311.py:6: note: Revealed type is "def [Ts] (x: tuple[*Ts])" |
| 2301 |
|
| 2302 |
[case testNativeParserPEP695InStubNoVersionError] |
| 2303 |
# flags: --python-version=3.11 --native-parser --ignore-missing-imports |
| 2304 |
import m |
| 2305 |
reveal_type(m.f) |
| 2306 |
[file m.pyi] |
| 2307 |
class C[T]: ... |
| 2308 |
def f[T](x: T) -> T: ... |
| 2309 |
type Alias[T] = list[T] |
| 2310 |
def g[T = int](x: T) -> T: ... |
| 2311 |
[out] |
| 2312 |
_testNativeParserPEP695InStubNoVersionError.py:3: note: Revealed type is "def [T] (x: T) -> T" |