| 1 |
[case testAnnotateNonNativeAttribute] |
| 2 |
from typing import Any |
| 3 |
|
| 4 |
def f1(x): |
| 5 |
return x.foo # A: Get non-native attribute "foo". |
| 6 |
|
| 7 |
def f2(x: Any) -> object: |
| 8 |
return x.foo # A: Get non-native attribute "foo". |
| 9 |
|
| 10 |
def f3(x): |
| 11 |
x.bar = 1 # A: Set non-native attribute "bar". |
| 12 |
|
| 13 |
class C: |
| 14 |
foo: int |
| 15 |
|
| 16 |
def method(self) -> int: |
| 17 |
return self.foo |
| 18 |
|
| 19 |
def good1(x: C) -> int: |
| 20 |
return x.foo |
| 21 |
|
| 22 |
[case testAnnotateMethod] |
| 23 |
class C: |
| 24 |
def method(self, x): |
| 25 |
return x + "y" # A: Generic "+" operation. |
| 26 |
|
| 27 |
[case testAnnotateGenericBinaryOperations] |
| 28 |
def generic_add(x): |
| 29 |
return x + 1 # A: Generic "+" operation. |
| 30 |
|
| 31 |
def generic_sub(x): |
| 32 |
return x - 1 # A: Generic "-" operation. |
| 33 |
|
| 34 |
def generic_mul(x): |
| 35 |
return x * 1 # A: Generic "*" operation. |
| 36 |
|
| 37 |
def generic_div(x): |
| 38 |
return x / 1 # A: Generic "/" operation. |
| 39 |
|
| 40 |
def generic_floor_div(x): |
| 41 |
return x // 1 # A: Generic "//" operation. |
| 42 |
|
| 43 |
def generic_unary_plus(x): |
| 44 |
return +x # A: Generic unary "+" operation. |
| 45 |
|
| 46 |
def generic_unary_minus(x): |
| 47 |
return -x # A: Generic unary "-" operation. |
| 48 |
|
| 49 |
def native_int_ops(x: int, y: int) -> int: |
| 50 |
a = x + 1 - y |
| 51 |
return x * a // y |
| 52 |
|
| 53 |
[case testAnnotateGenericBitwiseOperations] |
| 54 |
def generic_and(x): |
| 55 |
return x & 1 # A: Generic "&" operation. |
| 56 |
|
| 57 |
def generic_or(x): |
| 58 |
return x | 1 # A: Generic "|" operation. |
| 59 |
|
| 60 |
def generic_xor(x): |
| 61 |
return x ^ 1 # A: Generic "^" operation. |
| 62 |
|
| 63 |
def generic_left_shift(x): |
| 64 |
return x << 1 # A: Generic "<<" operation. |
| 65 |
|
| 66 |
def generic_right_shift(x): |
| 67 |
return x >> 1 # A: Generic ">>" operation. |
| 68 |
|
| 69 |
def generic_invert(x): |
| 70 |
return ~x # A: Generic "~" operation. |
| 71 |
|
| 72 |
def native_int_ops(x: int, y: int) -> int: |
| 73 |
a = (x & 1) << y |
| 74 |
return (x | a) >> (y ^ 1) |
| 75 |
|
| 76 |
[case testAnnotateGenericComparisonOperations] |
| 77 |
def generic_eq(x, y): |
| 78 |
return x == y # A: Generic comparison operation. |
| 79 |
|
| 80 |
def generic_ne(x, y): |
| 81 |
return x != y # A: Generic comparison operation. |
| 82 |
|
| 83 |
def generic_lt(x, y): |
| 84 |
return x < y # A: Generic comparison operation. |
| 85 |
|
| 86 |
def generic_le(x, y): |
| 87 |
return x <= y # A: Generic comparison operation. |
| 88 |
|
| 89 |
def generic_gt(x, y): |
| 90 |
return x > y # A: Generic comparison operation. |
| 91 |
|
| 92 |
def generic_ge(x, y): |
| 93 |
return x >= y # A: Generic comparison operation. |
| 94 |
|
| 95 |
def int_comparisons(x: int, y: int) -> int: |
| 96 |
if x == y: |
| 97 |
return 0 |
| 98 |
if x < y: |
| 99 |
return 1 |
| 100 |
if x > y: |
| 101 |
return 2 |
| 102 |
return 3 |
| 103 |
|
| 104 |
[case testAnnotateTwoOperationsOnLine] |
| 105 |
def f(x): |
| 106 |
return x.foo + 1 # A: Get non-native attribute "foo". Generic "+" operation. |
| 107 |
|
| 108 |
[case testAnnotateNonNativeMethod] |
| 109 |
from typing import Any |
| 110 |
|
| 111 |
def f1(x): |
| 112 |
return x.foo() # A: Call non-native method "foo" (it may be defined in a non-native class, or decorated). |
| 113 |
|
| 114 |
def f2(x: Any) -> None: |
| 115 |
x.foo(1) # A: Call non-native method "foo" (it may be defined in a non-native class, or decorated). |
| 116 |
x.foo(a=1) # A: Call non-native method "foo" (it may be defined in a non-native class, or decorated). |
| 117 |
t = (1, 'x') |
| 118 |
x.foo(*t) # A: Get non-native attribute "foo". Generic call operation. |
| 119 |
d = {"a": 1} |
| 120 |
x.foo(*d) # A: Get non-native attribute "foo". Generic call operation. |
| 121 |
|
| 122 |
class C: |
| 123 |
def foo(self) -> int: |
| 124 |
return 0 |
| 125 |
|
| 126 |
def g(c: C) -> int: |
| 127 |
return c.foo() |
| 128 |
|
| 129 |
[case testAnnotateGlobalVariableAccess] |
| 130 |
from typing import Final |
| 131 |
import nonnative |
| 132 |
|
| 133 |
x = 0 |
| 134 |
y: Final = 0 |
| 135 |
|
| 136 |
def read() -> int: |
| 137 |
return x # A: Access global "x" through namespace dictionary (hint: access is faster if you can make it Final). |
| 138 |
|
| 139 |
def assign(a: int) -> None: |
| 140 |
global x |
| 141 |
x = a # A: Access global "x" through namespace dictionary (hint: access is faster if you can make it Final). |
| 142 |
|
| 143 |
def read_final() -> int: |
| 144 |
return y |
| 145 |
|
| 146 |
def read_nonnative() -> int: |
| 147 |
return nonnative.z # A: Get non-native attribute "z". |
| 148 |
|
| 149 |
[file nonnative.py] |
| 150 |
z = 2 |
| 151 |
|
| 152 |
[case testAnnotateNestedFunction] |
| 153 |
def f1() -> None: |
| 154 |
def g() -> None: # A: A nested function object is allocated each time statement is executed. A module-level function would be faster. |
| 155 |
pass |
| 156 |
|
| 157 |
g() |
| 158 |
|
| 159 |
def f2() -> int: |
| 160 |
l = lambda: 1 # A: A new object is allocated for lambda each time it is evaluated. A module-level function would be faster. |
| 161 |
return l() |
| 162 |
|
| 163 |
[case testAnnotateGetSetItem] |
| 164 |
from typing import List, Dict |
| 165 |
|
| 166 |
def f1(x, y): |
| 167 |
return x[y] # A: Generic indexing operation. |
| 168 |
|
| 169 |
def f2(x, y, z): |
| 170 |
x[y] = z # A: Generic indexed assignment. |
| 171 |
|
| 172 |
def list_get_item(x: List[int], y: int) -> int: |
| 173 |
return x[y] |
| 174 |
|
| 175 |
def list_set_item(x: List[int], y: int) -> None: |
| 176 |
x[y] = 5 |
| 177 |
|
| 178 |
def dict_get_item(d: Dict[str, str]) -> str: |
| 179 |
return d['x'] |
| 180 |
|
| 181 |
def dict_set_item(d: Dict[str, str]) -> None: |
| 182 |
d['x'] = 'y' |
| 183 |
|
| 184 |
[case testAnnotateStrMethods] |
| 185 |
def startswith(x: str) -> bool: |
| 186 |
return x.startswith('foo') |
| 187 |
|
| 188 |
def islower(x: str) -> bool: |
| 189 |
return x.islower() # A: Call non-native method "islower" (it may be defined in a non-native class, or decorated). |
| 190 |
|
| 191 |
[case testAnnotateSpecificStdlibFeatures] |
| 192 |
import functools |
| 193 |
import itertools |
| 194 |
from functools import partial |
| 195 |
from itertools import chain, groupby, islice |
| 196 |
|
| 197 |
def f(x: int, y: int) -> None: pass |
| 198 |
|
| 199 |
def use_partial1() -> None: |
| 200 |
p = partial(f, 1) # A: "functools.partial" is inefficient in compiled code. |
| 201 |
p(2) |
| 202 |
|
| 203 |
def use_partial2() -> None: |
| 204 |
p = functools.partial(f, 1) # A: "functools.partial" is inefficient in compiled code. |
| 205 |
p(2) |
| 206 |
|
| 207 |
def use_chain1() -> None: |
| 208 |
for x in chain([1, 3], [4, 5]): # A: "itertools.chain" is inefficient in compiled code (hint: replace with for loops). |
| 209 |
pass |
| 210 |
|
| 211 |
def use_chain2() -> None: |
| 212 |
for x in itertools.chain([1, 3], [4, 5]): # A: "itertools.chain" is inefficient in compiled code (hint: replace with for loops). |
| 213 |
pass |
| 214 |
|
| 215 |
def use_groupby1() -> None: |
| 216 |
for a, b in groupby([('A', 'B')]): # A: "itertools.groupby" is inefficient in compiled code. |
| 217 |
pass |
| 218 |
|
| 219 |
def use_groupby2() -> None: |
| 220 |
for a, b in itertools.groupby([('A', 'B')]): # A: "itertools.groupby" is inefficient in compiled code. |
| 221 |
pass |
| 222 |
|
| 223 |
def use_islice() -> None: |
| 224 |
for x in islice([1, 2, 3], 1, 2): # A: "itertools.islice" is inefficient in compiled code (hint: replace with for loop over index range). |
| 225 |
pass |
| 226 |
|
| 227 |
[case testAnnotateGenericForLoop] |
| 228 |
from typing import Iterable, Sequence, Iterator, List |
| 229 |
|
| 230 |
def f1(a): |
| 231 |
for x in a: # A: For loop uses generic operations (iterable has type "Any"). |
| 232 |
pass |
| 233 |
|
| 234 |
def f2(a: Iterable[str]) -> None: |
| 235 |
for x in a: # A: For loop uses generic operations (iterable has the abstract type "typing.Iterable"). |
| 236 |
pass |
| 237 |
|
| 238 |
def f3(a: Sequence[str]) -> None: |
| 239 |
for x in a: # A: For loop uses generic operations (iterable has the abstract type "typing.Sequence"). |
| 240 |
pass |
| 241 |
|
| 242 |
def f4(a: Iterator[str]) -> None: |
| 243 |
for x in a: # A: For loop uses generic operations (iterable has the abstract type "typing.Iterator"). |
| 244 |
pass |
| 245 |
|
| 246 |
def good1(a: List[str]) -> None: |
| 247 |
for x in a: |
| 248 |
pass |
| 249 |
|
| 250 |
class C: |
| 251 |
def __iter__(self) -> Iterator[str]: |
| 252 |
assert False |
| 253 |
|
| 254 |
def good2(a: List[str]) -> None: |
| 255 |
for x in a: |
| 256 |
pass |
| 257 |
|
| 258 |
[case testAnnotateGenericComprehensionOrGenerator] |
| 259 |
from typing import List, Iterable |
| 260 |
|
| 261 |
def f1(a): |
| 262 |
return [x for x in a] # A: Comprehension or generator uses generic operations (iterable has type "Any"). |
| 263 |
|
| 264 |
def f2(a: Iterable[int]): |
| 265 |
return {x for x in a} # A: Comprehension or generator uses generic operations (iterable has the abstract type "typing.Iterable"). |
| 266 |
|
| 267 |
def f3(a): |
| 268 |
return {x: 1 for x in a} # A: Comprehension uses generic operations (iterable has type "Any"). |
| 269 |
|
| 270 |
def f4(a): |
| 271 |
return (x for x in a) # A: Comprehension or generator uses generic operations (iterable has type "Any"). |
| 272 |
|
| 273 |
def good1(a: List[int]) -> List[int]: |
| 274 |
return [x + 1 for x in a] |
| 275 |
|
| 276 |
[case testAnnotateIsinstance] |
| 277 |
from typing import Protocol, runtime_checkable, Union |
| 278 |
|
| 279 |
@runtime_checkable |
| 280 |
class P(Protocol): |
| 281 |
def foo(self) -> None: ... |
| 282 |
|
| 283 |
class C: pass |
| 284 |
|
| 285 |
class D(C): |
| 286 |
def bar(self) -> None: pass |
| 287 |
|
| 288 |
def bad1(x: object) -> bool: |
| 289 |
return isinstance(x, P) # A: Expensive isinstance() check against protocol "P". |
| 290 |
|
| 291 |
def bad2(x: object) -> bool: |
| 292 |
return isinstance(x, (str, P)) # A: Expensive isinstance() check against protocol "P". |
| 293 |
|
| 294 |
def good1(x: C) -> bool: |
| 295 |
if isinstance(x, D): |
| 296 |
x.bar() |
| 297 |
return isinstance(x, D) |
| 298 |
|
| 299 |
def good2(x: Union[int, str]) -> int: |
| 300 |
if isinstance(x, int): |
| 301 |
return x + 1 |
| 302 |
else: |
| 303 |
return int(x + "1") |
| 304 |
[typing fixtures/typing-full.pyi] |
| 305 |
|
| 306 |
[case testAnnotateDeepcopy] |
| 307 |
from typing import Any |
| 308 |
import copy |
| 309 |
|
| 310 |
def f(x: Any) -> Any: |
| 311 |
return copy.deepcopy(x) # A: "copy.deepcopy" tends to be slow. Make a shallow copy if possible. |
| 312 |
|
| 313 |
[case testAnnotateContextManager] |
| 314 |
from typing import Iterator |
| 315 |
from contextlib import contextmanager |
| 316 |
|
| 317 |
@contextmanager |
| 318 |
def slow_ctx_manager() -> Iterator[None]: |
| 319 |
yield |
| 320 |
|
| 321 |
class FastCtxManager: |
| 322 |
def __enter__(self) -> None: pass |
| 323 |
def __exit__(self, a, b, c) -> None: pass |
| 324 |
|
| 325 |
def f1(x) -> None: |
| 326 |
with slow_ctx_manager(): # A: "slow_ctx_manager" uses @contextmanager, which is slow in compiled code. Use a native class with "__enter__" and "__exit__" methods instead. |
| 327 |
x.foo # A: Get non-native attribute "foo". |
| 328 |
|
| 329 |
def f2(x) -> None: |
| 330 |
with FastCtxManager(): |
| 331 |
x.foo # A: Get non-native attribute "foo". |
| 332 |
|
| 333 |
[case testAnnotateAvoidNoiseAtTopLevel] |
| 334 |
from typing import Final |
| 335 |
|
| 336 |
class C(object): |
| 337 |
x = "s" |
| 338 |
y: Final = 1 |
| 339 |
|
| 340 |
x = "s" |
| 341 |
y: Final = 1 |
| 342 |
|
| 343 |
def f1() -> None: |
| 344 |
x = object # A: Get non-native attribute "object". |
| 345 |
|
| 346 |
[case testAnnotateCreateNonNativeInstance] |
| 347 |
from typing import NamedTuple |
| 348 |
from dataclasses import dataclass |
| 349 |
|
| 350 |
from nonnative import C |
| 351 |
|
| 352 |
def f1() -> None: |
| 353 |
c = C() # A: Creating an instance of non-native class "C" is slow. |
| 354 |
c.foo() # A: Call non-native method "foo" (it may be defined in a non-native class, or decorated). |
| 355 |
|
| 356 |
class NT(NamedTuple): |
| 357 |
x: int |
| 358 |
y: str |
| 359 |
|
| 360 |
def f2() -> int: |
| 361 |
o = NT(1, "x") # A: Creating an instance of non-native class "NT" is slow. |
| 362 |
return o.x |
| 363 |
|
| 364 |
def f3() -> int: |
| 365 |
o = NT(x=1, y="x") # A: Creating an instance of non-native class "NT" is slow. |
| 366 |
a, b = o |
| 367 |
return a |
| 368 |
|
| 369 |
@dataclass |
| 370 |
class D: |
| 371 |
x: int |
| 372 |
|
| 373 |
def f4() -> int: |
| 374 |
o = D(1) # A: Class "D" is only partially native, and constructing an instance is slow. |
| 375 |
return o.x |
| 376 |
|
| 377 |
class Nat: |
| 378 |
x: int |
| 379 |
|
| 380 |
class Deriv(Nat): |
| 381 |
def __init__(self, y: int) -> None: |
| 382 |
self.y = y |
| 383 |
|
| 384 |
def good1() -> int: |
| 385 |
n = Nat() |
| 386 |
d = Deriv(y=1) |
| 387 |
return n.x + d.x + d.y |
| 388 |
|
| 389 |
[file nonnative.py] |
| 390 |
class C: |
| 391 |
def foo(self) -> None: pass |
| 392 |
|
| 393 |
[case testAnnotateGetAttrAndSetAttrBuiltins] |
| 394 |
def f1(x, s: str): |
| 395 |
return getattr("x", s) # A: Dynamic attribute lookup. |
| 396 |
|
| 397 |
def f2(x, s: str): |
| 398 |
setattr(x, s, None) # A: Dynamic attribute set. |
| 399 |
|
| 400 |
[case testAnnotateSpecialAssignments] |
| 401 |
from typing import TypeVar, NamedTuple, List, TypedDict, NewType |
| 402 |
|
| 403 |
# Even though these are slow, we don't complain about them since there is generally |
| 404 |
# no better way (and at module top level these are very unlikely to be bottlenecks) |
| 405 |
A = List[int] |
| 406 |
T = TypeVar("T", bound=List[int]) |
| 407 |
NT = NamedTuple("NT", [("x", List[int])]) |
| 408 |
TD = TypedDict("TD", {"x": List[int]}) |
| 409 |
New = NewType("New", List[int]) |
| 410 |
[typing fixtures/typing-full.pyi] |
| 411 |
|
| 412 |
[case testAnnotateCallDecoratedNativeFunctionOrMethod] |
| 413 |
from typing import TypeVar, Callable, Any |
| 414 |
|
| 415 |
F = TypeVar("F", bound=Callable[..., Any]) |
| 416 |
|
| 417 |
def mydeco(f: F) -> F: |
| 418 |
return f |
| 419 |
|
| 420 |
@mydeco |
| 421 |
def d(x: int) -> int: |
| 422 |
return x |
| 423 |
|
| 424 |
def f1() -> int: |
| 425 |
return d(1) # A: Calling a decorated function ("d") is inefficient, even if it's native. |
| 426 |
|
| 427 |
class C: |
| 428 |
@mydeco |
| 429 |
def d(self) -> None: |
| 430 |
pass |
| 431 |
|
| 432 |
|
| 433 |
def f2() -> None: |
| 434 |
c = C() |
| 435 |
c.d() # A: Call non-native method "d" (it may be defined in a non-native class, or decorated). |
| 436 |
|
| 437 |
[case testAnnotateCallDifferentKindsOfMethods] |
| 438 |
from abc import ABC, abstractmethod |
| 439 |
|
| 440 |
class C: |
| 441 |
@staticmethod |
| 442 |
def s() -> None: ... |
| 443 |
|
| 444 |
@classmethod |
| 445 |
def c(cls) -> None: ... |
| 446 |
|
| 447 |
@property |
| 448 |
def p(self) -> int: |
| 449 |
return 0 |
| 450 |
|
| 451 |
@property |
| 452 |
def p2(self) -> int: |
| 453 |
return 0 |
| 454 |
|
| 455 |
@p2.setter |
| 456 |
def p2(self, x: int) -> None: |
| 457 |
pass |
| 458 |
|
| 459 |
def f1() -> int: |
| 460 |
c = C() |
| 461 |
c.s() |
| 462 |
c.c() |
| 463 |
c.p2 = 1 |
| 464 |
return c.p + c.p2 |
| 465 |
|
| 466 |
class A(ABC): |
| 467 |
@abstractmethod |
| 468 |
def m(self) -> int: |
| 469 |
raise NotImplementedError # A: Get non-native attribute "NotImplementedError". |
| 470 |
|
| 471 |
class D(A): |
| 472 |
def m(self) -> int: |
| 473 |
return 1 |
| 474 |
|
| 475 |
def f2() -> int: |
| 476 |
d = D() |
| 477 |
return d.m() |