| 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 |
Compiled code replaces a reference to an attribute declared ``Final`` with |
| 241 |
the value of the attribute computed at compile time. This is an example of |
| 242 |
:ref:`early binding <early-binding>`. Example:: |
| 243 |
|
| 244 |
MAX: Final = 100 |
| 245 |
|
| 246 |
def limit_to_max(x: int) -> int: |
| 247 |
if x > MAX: |
| 248 |
return MAX |
| 249 |
return x |
| 250 |
|
| 251 |
The two references to ``MAX`` don't involve any module namespace lookups, |
| 252 |
and are equivalent to this code:: |
| 253 |
|
| 254 |
def limit_to_max(x: int) -> int: |
| 255 |
if x > 100: |
| 256 |
return 100 |
| 257 |
return x |
| 258 |
|
| 259 |
When run as interpreted, the first example will execute slower due to |
| 260 |
the extra namespace lookups. In interpreted code final attributes can |
| 261 |
also be modified. |
| 262 |
|
| 263 |
.. _free-threading: |
| 264 |
|
| 265 |
Free threading |
| 266 |
-------------- |
| 267 |
|
| 268 |
Mypyc has basic support for free threading, but it doesn't provide the |
| 269 |
same memory safety guarantees as Python in compiled modules, since |
| 270 |
in current Python versions this would cause an unacceptable performance |
| 271 |
impact. |
| 272 |
|
| 273 |
The exact details of the memory safety in the presence of data races |
| 274 |
are likely to evolve in the future. Currently, compiled code must |
| 275 |
ensure that proper synchronization is used to prevent data races. In |
| 276 |
particular, these operations require explicit synchronization, such as |
| 277 |
via ``threading.Lock``, if there is a possibility of data races |
| 278 |
(the list is not exhaustive): |
| 279 |
|
| 280 |
* Reads or writes of non-final instance data attributes of native |
| 281 |
classes. |
| 282 |
* List item access or iteration using a ``list`` static type (using |
| 283 |
``Sequence`` or ``MutableSequence`` as the type ensure correct |
| 284 |
implicit synchronization). |
| 285 |
* Dict item access using a static ``dict`` type (using ``Mapping`` |
| 286 |
or ``MutableMapping`` ensures correct implicit synchronization). |
| 287 |
|
| 288 |
As libraries often won't be able to control the concurrent access by |
| 289 |
user code, we recommend that modules document that multi-threaded |
| 290 |
access is only supported via public interfaces that ensure correct |
| 291 |
synchronization. Marking attributes as internal using an underscore |
| 292 |
attribute prefix is another possibility, but this is not enforced at |
| 293 |
runtime. Another option is to document that multithreaded access is |
| 294 |
not supported, or that particular objects should not be used from |
| 295 |
multiple threads concurrently. |
| 296 |
|
| 297 |
It's always safe to perform read-only operations concurrently. Using |
| 298 |
objects with final attributes and tuple objects can help prevent |
| 299 |
race conditions without introducing extra overhead from explicit |
| 300 |
synchronization operations. |
| 301 |
|
| 302 |
Unsupported features |
| 303 |
-------------------- |
| 304 |
|
| 305 |
Some Python features are not supported by mypyc (yet). They can't be |
| 306 |
used in compiled code, or there are some limitations. You can |
| 307 |
partially work around some of these limitations by running your code |
| 308 |
in interpreted mode. |
| 309 |
|
| 310 |
Nested classes |
| 311 |
************** |
| 312 |
|
| 313 |
Nested classes are not supported. |
| 314 |
|
| 315 |
Conditional functions or classes |
| 316 |
******************************** |
| 317 |
|
| 318 |
Function and class definitions guarded by an if-statement are not supported. |
| 319 |
|
| 320 |
Dunder methods |
| 321 |
************** |
| 322 |
|
| 323 |
Native classes **cannot** use these dunders. If defined, they will not |
| 324 |
work as expected. |
| 325 |
|
| 326 |
* ``__index__`` |
| 327 |
* ``__getattribute__`` |
| 328 |
* ``__delattr__`` |
| 329 |
|
| 330 |
Generator expressions |
| 331 |
********************* |
| 332 |
|
| 333 |
Generator expressions are not supported. To make it easier to compile |
| 334 |
existing code, they are implicitly replaced with list comprehensions. |
| 335 |
*This does not always produce the same behavior.* |
| 336 |
|
| 337 |
To work around this limitation, you can usually use a generator |
| 338 |
function instead. You can sometimes replace the generator expression |
| 339 |
with an explicit list comprehension. |
| 340 |
|
| 341 |
Descriptors |
| 342 |
*********** |
| 343 |
|
| 344 |
Native classes can't contain arbitrary descriptors. Properties, static |
| 345 |
methods and class methods are supported. |
| 346 |
|
| 347 |
Introspection |
| 348 |
************* |
| 349 |
|
| 350 |
Various methods of introspection may break by using mypyc. Here's an |
| 351 |
non-exhaustive list of what won't work: |
| 352 |
|
| 353 |
- Instance ``__annotations__`` is usually not kept |
| 354 |
- Frames of compiled functions can't be inspected using ``inspect`` |
| 355 |
- Compiled methods aren't considered methods by ``inspect.ismethod`` |
| 356 |
- ``inspect.signature`` chokes on compiled functions with default arguments that |
| 357 |
are not simple literals |
| 358 |
|
| 359 |
Profiling hooks and tracing |
| 360 |
*************************** |
| 361 |
|
| 362 |
Compiled functions don't trigger profiling and tracing hooks, such as |
| 363 |
when using the ``profile``, ``cProfile``, or ``trace`` modules. |
| 364 |
|
| 365 |
Debuggers |
| 366 |
********* |
| 367 |
|
| 368 |
You can't set breakpoints in compiled functions or step through |
| 369 |
compiled functions using ``pdb``. Often you can debug your code in |
| 370 |
interpreted mode instead. |