Debian Codegraph @

mypyc/doc/using_type_annotations.rst

raw
1 .. _using-type-annotations:
2
3 Using type annotations
4 ======================
5
6 You will get the most out of mypyc if you compile code with precise
7 type annotations. Not all type annotations will help performance
8 equally, however. Using types such as :ref:`primitive types
9 <primitive-types>`, :ref:`native classes <native-class-intro>`,
10 :ref:`union types <union-types>`, :ref:`trait types <trait-types>`,
11 and :ref:`tuple types <tuple-types>` as much as possible is a key to
12 major performance gains over CPython.
13
14 In contrast, some other types, including ``Any``, are treated as
15 :ref:`erased types <erased-types>`. Operations on erased types use
16 generic operations that work with arbitrary objects, similar to how
17 the CPython interpreter works. If you only use erased types, the only
18 notable benefits over CPython will be the removal of interpreter
19 overhead (from compilation) and a bit of :ref:`early binding
20 <early-binding>`, which will usually only give minor performance
21 gains.
22
23 .. _primitive-types:
24
25 Primitive types
26 ---------------
27
28 The following built-in types are treated as *primitive types* by
29 mypyc, and many operations on these types have efficient
30 implementations:
31
32 * ``int`` (:ref:`native operations <int-ops>`)
33 * ``i64`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)
34 * ``i32`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)
35 * ``i16`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)
36 * ``u8`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)
37 * ``float`` (:ref:`native operations <float-ops>`)
38 * ``bool`` (:ref:`native operations <bool-ops>`)
39 * ``str`` (:ref:`native operations <str-ops>`)
40 * ``bytes`` (:ref:`native operations <bytes-ops>`)
41 * ``bytearray`` (:ref:`native operations <bytearray-ops>`)
42 * ``list[T]`` (:ref:`native operations <list-ops>`)
43 * ``dict[K, V]`` (:ref:`native operations <dict-ops>`)
44 * ``set[T]`` (:ref:`native operations <set-ops>`)
45 * ``tuple[T, ...]`` (variable-length tuple; :ref:`native operations <tuple-ops>`)
46 * ``None``
47 * ``range``
48
49 The link after each type lists all supported native, optimized
50 operations for the type. You can use all operations supported by
51 Python, but *native operations* will have custom, optimized
52 implementations.
53
54 Primitive containers
55 --------------------
56
57 Primitive container objects such as ``list`` and ``dict`` don't
58 maintain knowledge of the item types at runtime -- the item type is
59 *erased*.
60
61 This means that item types are checked when items are accessed, not
62 when a container is passed as an argument or assigned to another
63 variable. For example, here we have a runtime type error on the final
64 line of ``example`` (the ``Any`` type means an arbitrary, unchecked
65 value)::
66
67 from typing import Any
68
69 def example(a: list[Any]) -> None:
70 b: list[int] = a # No error -- items are not checked
71 print(b[0]) # Error here -- got str, but expected int
72
73 example(["x"])
74
75 .. _native-class-intro:
76
77 Native classes
78 --------------
79
80 Classes that get compiled to C extensions are called native
81 classes. Most common operations on instances of these classes are
82 optimized, including construction, attribute access and method calls.
83
84 Native class definitions look exactly like normal Python class
85 definitions. A class is usually native if it's in a compiled module
86 (though there are some exceptions).
87
88 Consider this example:
89
90 .. code-block::
91
92 class Point:
93 def __init__(self, x: int, y: int) -> None:
94 self.x = x
95 self.y = y
96
97 def shift(p: Point) -> Point:
98 return Point(p.x + 1, p.y + 1)
99
100 All operations in the above example use native operations, if the file
101 is compiled.
102
103 Native classes have some notable different from Python classes:
104
105 * Only attributes and methods defined in the class body or methods are
106 supported. If you try to assign to an undefined attribute outside
107 the class definition, ``AttributeError`` will be raised. This enables
108 an efficient memory layout and fast method calls for native classes.
109
110 * Native classes usually don't define the ``__dict__`` attribute (they
111 don't have an attribute dictionary). This follows from only having
112 a specific set of attributes.
113
114 * Native classes can't have an arbitrary metaclass or use most class
115 decorators.
116
117 Native classes only support single inheritance. A limited form of
118 multiple inheritance is supported through *trait types*. You generally
119 must inherit from another native class (or ``object``). By default,
120 you can't inherit a Python class from a native class (but there's
121 an :ref:`override <inheritance>` to allow that).
122
123 See :ref:`native-classes` for more details.
124
125 .. _tuple-types:
126
127 Tuple types
128 -----------
129
130 Fixed-length
131 `tuple types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#tuple-types>`_
132 such as ``tuple[int, str]`` are represented
133 as :ref:`value types <value-and-heap-types>` when stored in variables,
134 passed as arguments, or returned from functions. Value types are
135 allocated in the low-level machine stack or in CPU registers, as
136 opposed to *heap types*, which are allocated dynamically from the
137 heap.
138
139 Like all value types, tuples will be *boxed*, i.e. converted to
140 corresponding heap types, when stored in Python containers, or passed
141 to non-native code. A boxed tuple value will be a regular Python tuple
142 object.
143
144 .. _union-types:
145
146 Union types
147 -----------
148
149 `Union types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#union-types>`_
150 and
151 `optional types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#optional-types-and-the-none-type>`_
152 that contain primitive types, native class types and
153 trait types are also efficient. If a union type has
154 :ref:`erased <erased-types>` items, accessing items with
155 non-erased types is often still quite efficient.
156
157 A value with a union types is always :ref:`boxed <value-and-heap-types>`,
158 even if it contains a value that also has an unboxed representation, such
159 as an integer or a boolean.
160
161 For example, using ``Optional[int]`` is quite efficient, but the value
162 will always be boxed. A plain ``int`` value will usually be faster, since
163 it has an unboxed representation.
164
165 .. _trait-types:
166
167 Trait types
168 -----------
169
170 Trait types enable a form of multiple inheritance for native classes.
171 A native class can inherit any number of traits. Trait types are
172 defined as classes using the ``mypy_extensions.trait`` decorator::
173
174 from mypy_extensions import trait
175
176 @trait
177 class MyTrait:
178 def method(self) -> None:
179 ...
180
181 Traits can define methods, properties and attributes. They often
182 define abstract methods. Traits can be generic.
183
184 If a class subclasses both a non-trait class and traits, the traits
185 must be placed at the end of the base class list::
186
187 class Base: ...
188
189 class Derived(Base, MyTrait, FooTrait): # OK
190 ...
191
192 class Derived2(MyTrait, FooTrait, Base):
193 # Error: traits should come last
194 ...
195
196 Traits have some special properties:
197
198 * You shouldn't create instances of traits (though mypyc does not
199 prevent it yet).
200
201 * Traits can subclass other traits or native classes, but the MRO must be
202 linear (just like with native classes).
203
204 * Accessing methods or attributes through a trait type is somewhat
205 less efficient than through a native class type, but this is much
206 faster than through Python class types or other
207 :ref:`erased types <erased-types>`.
208
209 You need to install ``mypy-extensions`` to use ``@trait``:
210
211 .. code-block:: text
212
213 pip install --upgrade mypy-extensions
214
215 .. _erased-types:
216
217 Erased types
218 ------------
219
220 Mypyc supports many other kinds of types as well, beyond those
221 described above. However, these types don't have customized
222 operations, and they are implemented using *type erasure*. Type
223 erasure means that all other types are equivalent to untyped values at
224 runtime, i.e. they are the equivalent of the type ``Any``. Erased
225 types include these:
226
227 * Python classes (including ABCs)
228
229 * Non-mypyc extension types and primitive types (including built-in
230 types that are not primitives)
231
232 * `Callable types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#callable-types-and-lambdas>`_
233
234 * `Type variable types <https://mypy.readthedocs.io/en/stable/generics.html>`_
235
236 * Type `Any <https://mypy.readthedocs.io/en/stable/dynamic_typing.html>`_
237
238 * Protocol types
239
240 Using erased types can still improve performance, since they can
241 enable better types to be inferred for expressions that use these
242 types. For example, a value with type ``Callable[[], int]`` will not
243 allow native calls. However, the return type is a primitive type, and
244 we can use fast operations on the return value::
245
246 from typing import Callable
247
248 def call_and_inc(f: Callable[[], int]) -> int:
249 # Slow call, since f has an erased type
250 n = f()
251 # Fast increment; inferred type of n is int (primitive type)
252 n += 1
253 return n
254
255 If the type of the argument ``f`` was ``Any``, the type of ``n`` would
256 also be ``Any``, resulting in a generic, slower increment operation
257 being used.
258
259 Strict runtime type checking
260 ----------------------------
261
262 Compiled code ensures that any variable or expression with a
263 non-erased type only has compatible values at runtime. This is in
264 contrast with using *optional static typing*, such as by using mypy,
265 when type annotations are not enforced at runtime. Mypyc ensures
266 type safety both statically and at runtime.
267
268 ``Any`` types and erased types in general can compromise type safety,
269 and this is by design. Inserting strict runtime type checks for all
270 possible values would be too expensive and against the goal of
271 high performance.
272
273 .. _value-and-heap-types:
274
275 Value and heap types
276 --------------------
277
278 In CPython, memory for all objects is dynamically allocated on the
279 heap. All Python types are thus *heap types*. In compiled code, some
280 types are *value types* -- no object is (necessarily) allocated on the
281 heap. ``bool``, ``float``, ``None``, :ref:`native integer types <native-ints>`
282 and fixed-length tuples are value types.
283
284 ``int`` is a hybrid. For typical integer values, it is a value
285 type. Large enough integer values, those that require more than 63
286 bits (or 31 bits on 32-bit platforms) to represent, use a heap-based
287 representation (same as CPython).
288
289 Value types have a few differences from heap types:
290
291 * When an instance of a value type is used in a context that expects a
292 heap value, for example as a list item, it will transparently switch
293 to a heap-based representation (boxing) as needed.
294
295 * Similarly, mypyc transparently changes from a heap-based
296 representation to a value representation (unboxing).
297
298 * Object identity of integers, floating point values and tuples is not
299 preserved. You should use ``==`` instead of ``is`` if you are comparing
300 two integers, floats or fixed-length tuples.
301
302 * When an instance of a subclass of a value type is converted to the
303 base type, it is implicitly converted to an instance of the target
304 type. For example, a ``bool`` value assigned to a variable with an
305 ``int`` type will be converted to the corresponding integer.
306
307 The latter conversion is the only implicit type conversion that
308 happens in mypyc programs.
309
310 Example::
311
312 def example() -> None:
313 # A small integer uses the value (unboxed) representation
314 x = 5
315 # A large integer uses the heap (boxed) representation
316 x = 2**500
317 # Lists always contain boxed integers
318 a = [55]
319 # When reading from a list, the object is automatically unboxed
320 x = a[0]
321 # True is converted to 1 on assignment
322 x = True
323
324 Since integers and floating point values have a different runtime
325 representations and neither can represent all the values of the other
326 type, type narrowing of floating point values through assignment is
327 disallowed in compiled code. For consistency, mypyc rejects assigning
328 an integer value to a float variable even in variable initialization.
329 An explicit conversion is required.
330
331 Examples::
332
333 def narrowing(n: int) -> None:
334 # Error: Incompatible value representations in assignment
335 # (expression has type "int", variable has type "float")
336 x: float = 0
337
338 y: float = 0.0 # Ok
339
340 if f():
341 y = n # Error
342 if f():
343 y = float(n) # Ok
344
345 .. _native-ints:
346
347 Native integer types
348 --------------------
349
350 You can use the native integer types ``i64`` (64-bit signed integer),
351 ``i32`` (32-bit signed integer), ``i16`` (16-bit signed integer), and
352 ``u8`` (8-bit unsigned integer) if you know that integer values will
353 always fit within fixed bounds. These types are faster than the
354 arbitrary-precision ``int`` type, since they don't require overflow
355 checks on operations. They may also use less memory than ``int``
356 values. The types are imported from the ``mypy_extensions`` module
357 (installed via ``pip install mypy_extensions``).
358
359 Example::
360
361 from mypy_extensions import i64
362
363 def sum_list(l: list[i64]) -> i64:
364 s: i64 = 0
365 for n in l:
366 s += n
367 return s
368
369 # Implicit conversions from int to i64
370 print(sum_list([1, 3, 5]))
371
372 .. note::
373
374 Since there are no overflow checks when performing native integer
375 arithmetic, the above function could result in an overflow or other
376 undefined behavior if the sum might not fit within 64 bits.
377
378 The behavior when running as interpreted Python program will be
379 different if there are overflows. Declaring native integer types
380 have no effect unless code is compiled. Native integer types are
381 effectively equivalent to ``int`` when interpreted.
382
383 Native integer types have these additional properties:
384
385 * Values can be implicitly converted between ``int`` and a native
386 integer type (both ways).
387
388 * Conversions between different native integer types must be explicit.
389 A conversion to a narrower native integer type truncates the value
390 without a runtime overflow check.
391
392 * If a binary operation (such as ``+``) or an augmented assignment
393 (such as ``+=``) mixes native integer and ``int`` values, the
394 ``int`` operand is implicitly coerced to the native integer type
395 (native integer types are "sticky").
396
397 * You can't mix different native integer types in binary
398 operations. Instead, convert between types explicitly.
399
400 For more information about native integer types, refer to
401 :ref:`native integer operations <int-ops>`.