Debian Codegraph @

mypyc/doc/differences_from_python.rst

raw
1 .. _differences-from-python:
2
3 Differences from Python
4 =======================
5
6 Mypyc aims to be sufficiently compatible with Python semantics so that
7 migrating code to mypyc often doesn't require major code
8 changes. There are various differences to enable performance gains
9 that you need to be aware of, however.
10
11 This section documents notable differences from Python. We discuss
12 many of them also elsewhere, but it's convenient to have them here in
13 one place.
14
15 Running compiled modules
16 ------------------------
17
18 You can't use ``python3 <module>.py`` or ``python3 -m <module>``
19 to run compiled modules. Use ``python3 -c "import <module>"`` instead,
20 or write a wrapper script that imports your module.
21
22 As a side effect, you can't rely on checking the ``__name__`` attribute in compiled
23 code, like this::
24
25 if __name__ == "__main__": # Can't be used in compiled code
26 main()
27
28 Type errors prevent compilation
29 -------------------------------
30
31 You can't compile code that generates mypy type check errors. You can
32 sometimes ignore these with a ``# type: ignore`` comment, but this can
33 result in bad code being generated, and it's considered dangerous.
34
35 .. note::
36
37 In the future, mypyc may reject ``# type: ignore`` comments that
38 may be unsafe.
39
40 Runtime type checking
41 ---------------------
42
43 Non-erased types in annotations will be type checked at runtime. For example,
44 consider this function::
45
46 def twice(x: int) -> int:
47 return x * 2
48
49 If you try to call this function with a ``float`` or ``str`` argument,
50 you'll get a type error on the call site, even if the call site is not
51 being type checked::
52
53 twice(5) # OK
54 twice(2.2) # TypeError
55 twice("blah") # TypeError
56
57 Also, values with *inferred* types will be type checked. For example,
58 consider a call to the stdlib function ``socket.gethostname()`` in
59 compiled code. This function is not compiled (no stdlib modules are
60 compiled with mypyc), but mypyc uses a *library stub file* to infer
61 the return type as ``str``. Compiled code calling ``gethostname()``
62 will fail with ``TypeError`` if ``gethostname()`` would return an
63 incompatible value, such as ``None``::
64
65 import socket
66
67 # Fail if returned value is not a str
68 name = socket.gethostname()
69
70 Note that ``gethostname()`` is defined like this in the stub file for
71 ``socket`` (in typeshed)::
72
73 def gethostname() -> str: ...
74
75 Thus mypyc verifies that library stub files and annotations in
76 non-compiled code match runtime values. This adds an extra layer of
77 type safety.
78
79 Casts such as ``cast(str, x)`` will also result in strict type
80 checks. Consider this example::
81
82 from typing import cast
83 ...
84 x = cast(str, y)
85
86 The last line is essentially equivalent to this Python code when compiled::
87
88 if not isinstance(y, str):
89 raise TypeError(...)
90 x = y
91
92 In interpreted mode ``cast`` does not perform a runtime type check.
93
94 Native classes
95 --------------
96
97 Native classes behave differently from Python classes. See
98 :ref:`native-classes` for the details.
99
100 Primitive types
101 ---------------
102
103 Some primitive types behave differently in compiled code to improve
104 performance.
105
106 ``int`` objects use an unboxed (non-heap-allocated) representation for small
107 integer values. A side effect of this is that the exact runtime type of
108 ``int`` values is lost. For example, consider this simple function::
109
110 def first_int(x: list[int]) -> int:
111 return x[0]
112
113 print(first_int([True])) # Output is 1, instead of True!
114
115 ``bool`` is a subclass of ``int``, so the above code is
116 valid. However, when the list value is converted to ``int``, ``True``
117 is converted to the corresponding ``int`` value, which is ``1``.
118
119 Note that integers still have an arbitrary precision in compiled code,
120 similar to normal Python integers.
121
122 Fixed-length tuples are unboxed, similar to integers. The exact type
123 and identity of fixed-length tuples is not preserved, and you can't
124 reliably use ``is`` checks to compare tuples that are used in compiled
125 code.
126
127 .. _early-binding:
128
129 Early binding
130 -------------
131
132 References to functions, types, most attributes, and methods in the
133 same :ref:`compilation unit <compilation-units>` use *early binding*:
134 the target of the reference is decided at compile time, whenever
135 possible. This contrasts with normal Python behavior of *late
136 binding*, where the target is found by a namespace lookup at
137 runtime. Omitting these namespace lookups improves performance, but
138 some Python idioms don't work without changes.
139
140 Note that non-final module-level variables still use late binding.
141 You may want to avoid these in very performance-critical code.
142
143 Examples of early and late binding::
144
145 from typing import Final
146
147 import lib # "lib" is not compiled
148
149 x = 0
150 y: Final = 1
151
152 def func() -> None:
153 pass
154
155 class Cls:
156 def __init__(self, attr: int) -> None:
157 self.attr = attr
158
159 def method(self) -> None:
160 pass
161
162 def example() -> None:
163 # Early binding:
164 var = y
165 func()
166 o = Cls()
167 o.x
168 o.method()
169
170 # Late binding:
171 var = x # Module-level variable
172 lib.func() # Accessing library that is not compiled
173
174 Pickling and copying objects
175 ----------------------------
176
177 Mypyc tries to enforce that instances native classes are properly
178 initialized by calling ``__init__`` implicitly when constructing
179 objects, even if objects are constructed through ``pickle``,
180 ``copy.copy`` or ``copy.deepcopy``, for example.
181
182 If a native class doesn't support calling ``__init__`` without arguments,
183 you can't pickle or copy instances of the class. Use the
184 ``mypy_extensions.mypyc_attr`` class decorator to override this behavior
185 and enable pickling through the ``serializable`` flag::
186
187 from mypy_extensions import mypyc_attr
188 import pickle
189
190 @mypyc_attr(serializable=True)
191 class Cls:
192 def __init__(self, n: int) -> None:
193 self.n = n
194
195 data = pickle.dumps(Cls(5))
196 obj = pickle.loads(data) # OK
197
198 Additional notes:
199
200 * All subclasses inherit the ``serializable`` flag.
201 * If a class has the ``allow_interpreted_subclasses`` attribute, it
202 implicitly supports serialization.
203 * Enabling serialization may slow down attribute access, since compiled
204 code has to be always prepared to raise ``AttributeError`` in case an
205 attribute is not defined at runtime.
206 * If you try to pickle an object without setting the ``serializable``
207 flag, you'll get a ``TypeError`` about missing arguments to
208 ``__init__``.
209
210
211 Monkey patching
212 ---------------
213
214 Since mypyc function and class definitions are immutable, you can't
215 perform arbitrary monkey patching, such as replacing functions or
216 methods with mocks in tests.
217
218 .. note::
219
220 Each compiled module has a Python namespace that is initialized to
221 point to compiled functions and type objects. This namespace is a
222 regular ``dict`` object, and it *can* be modified. However,
223 compiled code generally doesn't use this namespace, so any changes
224 will only be visible to non-compiled code.
225
226 Stack overflows
227 ---------------
228
229 Compiled code currently doesn't check for stack overflows. Your
230 program may crash in an unrecoverable fashion if you have too many
231 nested function calls, typically due to out-of-control recursion.
232
233 .. note::
234
235 This limitation will be fixed in the future.
236
237 Final values
238 ------------
239
240 Mypy treats variables and attributes defined as ``Final`` specially.
241 For instance attributes of native classes, mypyc prevents reassignment
242 of these attributes.
243
244 Mypyc replaces references to a variable or attribute declared ``Final``
245 with the value of the attribute computed at compile time, when it can
246 be determined during compilation. Example::
247
248 MAX: Final = 100
249
250 def limit_to_max(x: int) -> int:
251 if x > MAX:
252 return MAX
253 return x
254
255 The two references to ``MAX`` don't involve any module namespace lookups,
256 and are equivalent to this code::
257
258 def limit_to_max(x: int) -> int:
259 if x > 100:
260 return 100
261 return x
262
263 When run as interpreted, the first example will execute slower due to
264 the extra namespace lookups.
265
266 For a final class attribute or global variable whose value can't be
267 determined during compilation, mypyc defines a hidden native variable
268 that stores the value when the initialization assignment is evaluated.
269 Redefining the attribute using ``setattr`` or direct namespace access
270 has no effect for mypyc-compiled code (in the same compilation unit).
271
272 Final global variables and class attributes are faster to read in
273 compiled code, since they don't have to be looked up from a namespace
274 dictionary. Thus using a ``Final`` object that holds mutable state in an
275 attribute tends to be faster than a plain global variable in compiled code::
276
277 class Counter:
278 def __init__(self) -> None:
279 self.value = 0
280
281 x: Final = Counter()
282 y = 0
283
284 def inc() -> None:
285 # Faster: no Python namespace lookup
286 x.value += 1
287 # Slower: access through globals() namespace dictionary
288 global y
289 y += 1
290
291 .. _free-threading:
292
293 Free threading
294 --------------
295
296 Mypyc supports free threading. However, optimized primitive operations in
297 compiled code may have different atomicity properties compared to CPython.
298 Use explicit synchronization if code depends on operations being atomic and
299 race conditions are possible. This is already the recommended approach for
300 normal Python code. You can often use :ref:`librt.threading.Lock <librt-threading-lock>`
301 (or :py:class:`threading.Lock`, which is less efficient than
302 ``librt.threading.Lock``) to fix data races.
303
304 Since mypyc 2.3, the vast majority of operations are memory safe even if
305 there are race conditions (unlike earlier mypyc releases). This includes
306 list operations and access to native instance attributes (except for
307 a few less common use cases that will be fixed in future releases).
308
309 .. note::
310
311 Operations that aren't safe under race conditions in interpreted CPython
312 are not expected to be memory safe in compiled code either.
313 Some :ref:`librt <librt>` features are heavily optimized for performance and
314 don't guarantee memory safety when there are race conditions
315 (notably the :ref:`vec <librt-vecs>` type).
316
317 It's always safe to perform read-only operations concurrently. Using
318 objects with final attributes and tuple objects can help prevent
319 race conditions without introducing extra overhead from explicit
320 synchronization operations.
321
322 Unsupported features
323 --------------------
324
325 Some Python features are not supported by mypyc (yet). They can't be
326 used in compiled code, or there are some limitations. You can
327 partially work around some of these limitations by running your code
328 in interpreted mode.
329
330 Nested classes
331 **************
332
333 Nested classes are not supported.
334
335 Conditional functions or classes
336 ********************************
337
338 Function and class definitions guarded by an if-statement are not supported.
339
340 Dunder methods
341 **************
342
343 Native classes **cannot** use these dunders. If defined, they will not
344 work as expected.
345
346 * ``__index__``
347 * ``__getattribute__``
348 * ``__delattr__``
349
350 Generator expressions
351 *********************
352
353 Generator expressions are not supported. To make it easier to compile
354 existing code, they are implicitly replaced with list comprehensions.
355 *This does not always produce the same behavior.*
356
357 To work around this limitation, you can usually use a generator
358 function instead. You can sometimes replace the generator expression
359 with an explicit list comprehension.
360
361 Descriptors
362 ***********
363
364 Native classes can't contain arbitrary descriptors. Properties, static
365 methods and class methods are supported.
366
367 Introspection
368 *************
369
370 Various methods of introspection may break by using mypyc. Here's an
371 non-exhaustive list of what won't work:
372
373 - Instance ``__annotations__`` is usually not kept
374 - Frames of compiled functions can't be inspected using ``inspect``
375 - Compiled methods aren't considered methods by ``inspect.ismethod``
376 - ``inspect.signature`` chokes on compiled functions with default arguments that
377 are not simple literals
378
379 Profiling hooks and tracing
380 ***************************
381
382 Compiled functions don't trigger profiling and tracing hooks, such as
383 when using the ``profile``, ``cProfile``, or ``trace`` modules.
384
385 Debuggers
386 *********
387
388 You can't set breakpoints in compiled functions or step through
389 compiled functions using ``pdb``. Often you can debug your code in
390 interpreted mode instead.