Debian Codegraph @

pypy/doc/cpython_differences.rst

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 Differences between PyPy and CPython
2 ====================================
3
4 This page documents the few differences and incompatibilities between
5 the PyPy Python interpreter and CPython. Some of these differences
6 are "by design", since we think that there are cases in which the
7 behaviour of CPython is buggy, and we do not want to copy bugs.
8
9 Differences that are not listed here should be considered bugs of
10 PyPy.
11
12
13
14 Differences related to garbage collection strategies
15 ----------------------------------------------------
16
17 The garbage collectors used or implemented by PyPy are not based on
18 reference counting, so the objects are not freed instantly when they are no
19 longer reachable. The most obvious effect of this is that files (and sockets, etc) are not
20 promptly closed when they go out of scope. For files that are opened for
21 writing, data can be left sitting in their output buffers for a while, making
22 the on-disk file appear empty or truncated. Moreover, you might reach your
23 OS's limit on the number of concurrently opened files.
24
25 If you are debugging a case where a file in your program is not closed
26 properly on PyPy2, you can use the ``-X track-resources`` command line
27 option. On Python3 (both CPython and PyPy), use the ``-Walways`` command line
28 option. In both cases, you may need to add a call to ``gc.collect()`` at the
29 end of the program. Then a ``ResourceWarning`` is produced for every file and
30 socket that the garbage collector closes. On PyPy, the warning will always
31 contain the stack trace of the position where the file or socket was created,
32 to make it easier to see which parts of the program don't close files
33 explicitly.
34
35 Fixing this difference to CPython is essentially impossible without forcing a
36 reference-counting approach to garbage collection. The effect that you
37 get in CPython has clearly been described as a side-effect of the
38 implementation and not a language design decision: programs relying on
39 this are basically bogus. It would be a too strong restriction to try to enforce
40 CPython's behavior in a language spec, given that it has no chance to be
41 adopted by Jython or IronPython (or any other port of Python to Java or
42 .NET).
43
44 Even the naive idea of forcing a full GC when we're getting dangerously
45 close to the OS's limit can be very bad in some cases. If your program
46 leaks open files heavily, then it would work, but force a complete GC
47 cycle every n'th leaked file. The value of n is a constant, but the
48 program can take an arbitrary amount of memory, which makes a complete
49 GC cycle arbitrarily long. The end result is that PyPy would spend an
50 arbitrarily large fraction of its run time in the GC --- slowing down
51 the actual execution, not by 10% nor 100% nor 1000% but by essentially
52 any factor.
53
54 To the best of our knowledge this problem has no better solution than
55 fixing the programs. If it occurs in 3rd-party code, this means going
56 to the authors and explaining the problem to them: they need to close
57 their open files in order to run on any non-CPython-based implementation
58 of Python.
59
60 ---------------------------------
61
62 Here are some more technical details. This issue affects the precise
63 time at which ``__del__`` methods are called, which
64 is not reliable or timely in PyPy (nor Jython nor IronPython). It also means that
65 **weak references** may stay alive for a bit longer than expected. This
66 makes "weak proxies" (as returned by ``weakref.proxy()``) somewhat less
67 useful: they will appear to stay alive for a bit longer in PyPy, and
68 suddenly they will really be dead, raising a ``ReferenceError`` on the
69 next access. Any code that uses weak proxies must carefully catch such
70 ``ReferenceError`` at any place that uses them. (Or, better yet, don't use
71 ``weakref.proxy()`` at all; use ``weakref.ref()``.)
72
73 Note a detail in the `documentation for weakref callbacks`__:
74
75 If callback is provided and not None, *and the returned weakref
76 object is still alive,* the callback will be called when the object
77 is about to be finalized.
78
79 There are cases where, due to CPython's refcount semantics, a weakref
80 dies immediately before or after the objects it points to (typically
81 with some circular reference). If it happens to die just after, then
82 the callback will be invoked. In a similar case in PyPy, both the
83 object and the weakref will be considered as dead at the same time,
84 and the callback will not be invoked. (Issue `#2030`__)
85
86 .. __: https://docs.python.org/2/library/weakref.html
87 .. __: https://github.com/pypy/pypy/issues/2030/
88
89 A new difference: before CPython 3.4, a weakref to ``x`` was always
90 cleared before the ``x.__del__()`` method was called. Since CPython 3.4
91 the picture is more muddy. Often, the weakref is still alive while
92 ``x.__del__()`` runs, but not always (e.g. not in case of reference
93 cycles). In PyPy3 we have kept the more consistent pre-3.4 behavior; we
94 can't do something really different if there are cycles or not.
95
96 ---------------------------------
97
98 There are a few extra implications from the difference in the GC. Most
99 notably, if an object has a ``__del__``, the ``__del__`` is never called more
100 than once in PyPy; but CPython will call the same ``__del__`` several times
101 if the object is resurrected and dies again (at least it is reliably so in
102 older CPythons; newer CPythons try to call destructors not more than once,
103 but there are counter-examples). The ``__del__`` methods are
104 called in "the right" order if they are on objects pointing to each
105 other, as in CPython, but unlike CPython, if there is a dead cycle of
106 objects referencing each other, their ``__del__`` methods are called anyway;
107 CPython would instead put them into the list ``garbage`` of the ``gc``
108 module. More information is available on the blog `[1]`__ `[2]`__.
109
110 .. __: https://www.pypy.org/posts/2008/02/python-finalizers-semantics-part-1-1196956834543115766.html
111 .. __: https://www.pypy.org/posts/2008/02/python-finalizers-semantics-part-2-2748812428675325525.html
112
113 Note that this difference might show up indirectly in some cases. For
114 example, a generator left pending in the middle is --- again ---
115 garbage-collected later in PyPy than in CPython. You can see the
116 difference if the ``yield`` keyword it is suspended at is itself
117 enclosed in a ``try:`` or a ``with:`` block. This shows up for example
118 as `issue 736`__.
119
120 .. __: https://github.com/pypy/pypy/issues/736
121
122 Using the default GC (called ``minimark``), the built-in function ``id()``
123 works like it does in CPython. With other GCs it returns numbers that
124 are not real addresses (because an object can move around several times)
125 and calling it a lot can lead to performance problems.
126
127 Note that if you have a long chain of objects, each with a reference to
128 the next one, and each with a ``__del__``, PyPy's GC will perform badly. On
129 the bright side, in most other cases, benchmarks have shown that PyPy's
130 GCs perform much better than CPython's.
131
132 Another difference is that if you add a ``__del__`` to an existing class it will
133 not be called::
134
135 >>>> class A(object):
136 .... pass
137 ....
138 >>>> A.__del__ = lambda self: None
139 __main__:1: RuntimeWarning: a __del__ method added to an existing type will not be called
140
141 Even more obscure: the same is true, for old-style classes, if you attach
142 the ``__del__`` to an instance (even in CPython this does not work with
143 new-style classes). You get a RuntimeWarning in PyPy. To fix these cases
144 just make sure there is a ``__del__`` method in the class to start with
145 (even containing only ``pass``; replacing or overriding it later works fine).
146
147 CPython tries to do a ``gc.collect()`` automatically when the
148 program finishes; not PyPy. (It is possible in both CPython and PyPy to
149 design a case where several ``gc.collect()`` are needed before all objects
150 die. This makes CPython's approach only work "most of the time" anyway.)
151
152 Missing ``sys.getrefcount``
153 ---------------------------
154
155 Because of the different strategy above, ``sys.getrefcount()`` would return
156 an unreliable number. So PyPy does not implement that, trying to use it will
157 raise ``AttributeError: module 'sys' has no attribute 'getrefcount'``. Note
158 that newer versions of CPython also change the meaning of ``sys.getrefcount()``.
159
160 Subclasses of built-in types
161 ----------------------------
162
163 Officially, CPython has no rule at all for when exactly
164 overridden method of subclasses of built-in types get
165 implicitly called or not. As an approximation, these methods
166 are never called by other built-in methods of the same object.
167 For example, an overridden ``__getitem__()`` in a subclass of
168 ``dict`` will not be called by e.g. the built-in ``get()``
169 method.
170
171 The above is true both in CPython and in PyPy. Differences
172 can occur about whether a built-in function or method will
173 call an overridden method of *another* object than ``self``.
174 In PyPy, they are often called in cases where CPython would not.
175 Two examples::
176
177 class D(dict):
178 def __getitem__(self, key):
179 if key == 'print':
180 return print
181 return "%r from D" % (key,)
182
183 class A(object):
184 pass
185
186 a = A()
187 a.__dict__ = D()
188 a.foo = "a's own foo"
189 print(a.foo)
190 # CPython => a's own foo
191 # PyPy => 'foo' from D
192
193 print('==========')
194
195 glob = D(foo="base item")
196 loc = {}
197 exec("print(foo)", glob, loc)
198 # CPython => base item, and never looks up "print" in D
199 # PyPy => 'foo' from D, and looks up "print" in D
200
201
202 Mutating classes of objects which are already used as dictionary keys
203 ---------------------------------------------------------------------
204
205 Consider the following snippet of code::
206
207 class X(object):
208 pass
209
210 def __evil_eq__(self, other):
211 print 'hello world'
212 return False
213
214 def evil(y):
215 d = {X(): 1}
216 X.__eq__ = __evil_eq__
217 d[y] # might trigger a call to __eq__?
218
219 In CPython, __evil_eq__ **might** be called, although there is no way to write
220 a test which reliably calls it. It happens if ``y is not x`` and ``hash(y) ==
221 hash(x)``, where ``hash(x)`` is computed when ``x`` is inserted into the
222 dictionary. If **by chance** the condition is satisfied, then ``__evil_eq__``
223 is called.
224
225 PyPy uses a special strategy to optimize dictionaries whose keys are instances
226 of user-defined classes which do not override the default ``__hash__``,
227 ``__eq__`` and ``__cmp__``: when using this strategy, ``__eq__`` and
228 ``__cmp__`` are never called, but instead the lookup is done by identity, so
229 in the case above it is guaranteed that ``__eq__`` won't be called.
230
231 Note that in all other cases (e.g., if you have a custom ``__hash__`` and
232 ``__eq__`` in ``y``) the behavior is exactly the same as CPython.
233
234
235 Ignored exceptions
236 -----------------------
237
238 In many corner cases, CPython can silently swallow exceptions.
239 The precise list of when this occurs is rather long, even
240 though most cases are very uncommon. The most well-known
241 places are custom rich comparison methods (like \_\_eq\_\_);
242 dictionary lookup; calls to some built-in functions like
243 isinstance().
244
245 Unless this behavior is clearly present by design and
246 documented as such (as e.g. for hasattr()), in most cases PyPy
247 lets the exception propagate instead.
248
249
250 Object Identity of Primitive Values, ``is`` and ``id``
251 -------------------------------------------------------
252
253 Object identity of primitive values works by value equality, not by identity of
254 the wrapper. This means that ``x + 1 is x + 1`` is always true, for arbitrary
255 integers ``x``. The rule applies for the following types:
256
257 - ``int``
258
259 - ``float``
260
261 - ``long``
262
263 - ``complex``
264
265 - ``str`` (empty or single-character strings only)
266
267 - ``unicode`` (empty or single-character strings only)
268
269 - ``tuple`` (empty tuples only)
270
271 - ``frozenset`` (empty frozenset only)
272
273 - unbound method objects (for Python 2 only)
274
275 This change requires some changes to ``id`` as well. ``id`` fulfills the
276 following condition: ``x is y <=> id(x) == id(y)``. Therefore ``id`` of the
277 above types will return a value that is computed from the argument, and can
278 thus be arbitrarily large; larger than ``sys.maxsize`` (or ``sys.maxint`` on
279 PyPy2).
280
281 Note that strings of length 2 or greater can be equal without being
282 identical. Similarly, ``x is (2,)`` is not necessarily true even if
283 ``x`` contains a tuple and ``x == (2,)``. The uniqueness rules apply
284 only to the particular cases described above. The ``str``, ``unicode``,
285 ``tuple`` and ``frozenset`` rules were added in PyPy 5.4; before that, a
286 test like ``if x is "?"`` or ``if x is ()`` could fail even if ``x`` was
287 equal to ``"?"`` or ``()``. The new behavior added in PyPy 5.4 is
288 closer to CPython's, which caches precisely the empty tuple/frozenset,
289 and (generally but not always) the strings and unicodes of length <= 1.
290
291 Note that for floats there "``is``" only one object per "bit pattern"
292 of the float. So ``float('nan') is float('nan')`` is true on PyPy,
293 but not on CPython because they are two objects; but ``0.0 is -0.0``
294 is always False, as the bit patterns are different. As usual,
295 ``float('nan') == float('nan')`` is always False. When used in
296 containers (as list items or in sets for example), the exact rule of
297 equality used is "``if x is y or x == y``" (on both CPython and PyPy);
298 as a consequence, because all ``nans`` are identical in PyPy, you
299 cannot have several of them in a set, unlike in CPython. (Issue `#1974`__).
300 Another consequence is that ``cmp(float('nan'), float('nan')) == 0``, because
301 ``cmp`` checks with ``is`` first whether the arguments are identical (there is
302 no good value to return from this call to ``cmp``, because ``cmp`` pretends
303 that there is a total order on floats, but that is wrong for NaNs).
304
305 .. __: https://github.com/pypy/pypy/issues/1974
306
307 Order of dictionary keys in instance dicts
308 ------------------------------------------
309
310 Instance dictionaries are not always ordered by insertion in PyPy.
311 Specifically, this can happen if the ``__init__`` of the class adds attributes
312 in different orders. Here's an example::
313
314 >>>> class A:
315 .... def __init__(self, a, b, reorder=False):
316 .... if not reorder:
317 .... self.a = a
318 .... self.b = b
319 .... else:
320 .... self.b = b
321 .... self.a = a
322 ....
323 >>>> print(A(1, 2).__dict__)
324 {'a': 1, 'b': 2}
325 >>>> print(A(1, 2, reorder=True).__dict__)
326 {'a': 1, 'b': 2}
327
328 CPython prints ``{'b': 2, 'a': 1}`` in the last line.
329
330 Background: In CPython 3.6, dictionaries became `ordered by insertion`__.
331 This is also true for instance dictionaries. In PyPy, regular
332 dictionaries have been ordered since 2015__. For instance dictionaries, this is
333 not always possible, because they are represented using `Self-style maps/hidden
334 classes`__, which are one of the cornerstones of PyPy's performance.
335
336 .. __: https://docs.python.org/3/whatsnew/3.6.html#new-dict-implementation
337 .. __: https://pypy.org/posts/2015/01/faster-more-memory-efficient-and-more-4096950404745375390.html#
338 .. __: https://pypy.org/posts/2010/11/efficiently-implementing-python-objects-3838329944323946932.html
339
340
341 Permitted ABI tags in extensions
342 --------------------------------
343
344 CPython supports the limited C-API with modules that have an ``abi3`` ABI tag,
345 and will also import extension modules with no ABI or platform tags. This can
346 be seen by comparing ``_imp.extension_suffix()`` calls (on Python3.9, x86_64,
347 linux):
348
349 ========== ===================================== ==============
350 python _imp.extension_suffixes() notes
351 ========== ===================================== ==============
352 cpython3.9 [".cpython-39-x86_64-linux-gnu.so", normal [#f1]_
353 .. ".abi3.so", limited C-API
354 .. ".so"] bare extension
355 pypy3.9 ['.pypy39-pp73-x86_64-linux-gnu.so'] normal [#f1]_
356 ========== ===================================== ==============
357
358 .. rubric:: Footnotes
359
360 .. [#f1] normal extensions use <python-tag>-<abi-tag>-<platform-tag>
361
362 CMake will `support the correct suffix`_ for PyPy3.9 in release 3.26, scheduled for early 2023
363
364 .. _support the correct suffix: https://gitlab.kitware.com/cmake/cmake/-/merge_requests/7917
365
366 .. _cpyext:
367
368 C-API Differences
369 -----------------
370
371 The external C-API has been reimplemented in PyPy as an internal cpyext module.
372 We support most of the documented C-API, but sometimes internal C-abstractions
373 leak out on CPython and are abused, perhaps even unknowingly. For instance,
374 assignment to a ``PyTupleObject`` is not supported after the tuple is
375 used internally, even by another C-API function call. On CPython this will
376 succeed as long as the refcount is 1. On PyPy this will always raise a
377 ``SystemError('PyTuple_SetItem called on tuple after use of tuple")``
378 exception (explicitly listed here for search engines).
379
380 Another similar problem is assignment of a new function pointer to any of the
381 ``tp_as_*`` structures after calling ``PyType_Ready``. For instance, overriding
382 ``tp_as_number.nb_int`` with a different function after calling ``PyType_Ready``
383 on CPython will result in the old function being called for ``x.__int__()``
384 (via class ``__dict__`` lookup) and the new function being called for ``int(x)``
385 (via slot lookup). On PyPy we will always call the __new__ function, not the
386 old, this quirky behaviour is unfortunately necessary to fully support NumPy.
387
388 The cpyext layer `adds complexity`_ and is slow. If possible, use cffi_ or HPy_.
389
390 .. _adds complexity: https://www.pypy.org/posts/2018/09/inside-cpyext-why-emulating-cpython-c-8083064623681286567.html
391 .. _cffi: https://cffi.readthedocs.io/en/latest/
392 .. _HPy: https://hpyproject.org/
393
394 Performance Differences
395 -------------------------
396
397 CPython has an optimization that can make repeated string concatenation not
398 quadratic. For example, this kind of code runs in O(n) time::
399
400 s = ''
401 for string in mylist:
402 s += string
403
404 In PyPy, this code will always have quadratic complexity. Note also, that the
405 CPython optimization is brittle and can break by having slight variations in
406 your code anyway. So you should anyway replace the code with::
407
408 parts = []
409 for string in mylist:
410 parts.append(string)
411 s = "".join(parts)
412
413 Bytecode differences in Python 3.11
414 -----------------------------------
415
416 There are bytecode differences between PyPy 3.11 and CPython 3.11:
417
418 * No ``RESUME`` opcode.
419
420 CPython 3.11 inserts a ``RESUME`` opcode at the start of every function, class
421 body, and module. It is assigned line number 0 and is used by the adaptive
422 specialising interpreter for tracing and profiling. PyPy does not emit RESUME.
423
424 Visible effects:
425
426 - ``co.co_lines()`` / ``co_positions()``: the first entry in CPython has line
427 0 (the ``RESUME``); PyPy's first entry is the first real statement.
428 - ``dis.get_instructions()`` on a trivial function returns one fewer
429 instruction in PyPy.
430
431 * Unified ``BINARY_OP`` vs per-operator opcodes
432
433 CPython 3.11 replaced the family of type-specific binary opcodes
434 (``BINARY_ADD``, ``BINARY_SUBTRACT``, etc and their ``INPLACE_*``
435 counterparts) with a single ``BINARY_OP`` instruction that takes the operator
436 as an argument. PyPy retains the original per-operator opcodes.
437
438 * Unified ``CALL`` vs ``CALL_FUNCTION`` / ``CALL_METHOD``
439
440 CPython 3.11 replaced ``CALL_FUNCTION``, ``CALL_FUNCTION_KW``,
441 ``CALL_FUNCTION_EX``, and ``CALL_METHOD`` with a unified ``CALL`` instruction
442 (preceded by ``PUSH_NULL`` or ``PRECALL``). PyPy retains the old behaviour. Note
443 that ``PRECALL`` is used by the specialiser to rewrite the call site.
444
445 Visible effects: code that dispatches on opcode names or checks for ``PRECALL``
446 will not find it in PyPy.
447
448 * ``LOAD_METHOD`` still present
449
450 CPython 3.11 eliminated ``LOAD_METHOD`` and folded method loading into
451 ``LOAD_ATTR`` (which inspects the descriptor at runtime and leaves a flag on
452 the stack). PyPy still emits ``LOAD_METHOD`` for method calls and follows it
453 with ``CALL_METHOD``.
454
455 * No inline caches
456
457 CPython 3.11 embeds inline cache entries directly in the bytecode stream
458 (``CACHE`` pseudo-instructions) to support the adaptive specialising
459 interpreter. These inflate ``co_code`` considerably. PyPy has no adaptive
460 specialiser and its inline caches are stored elsewhere, so its code objects are smaller. Any test
461 that uses ``len(co_code)`` or ``log(len(co_code))`` as a proxy for stack
462 depth will see different values.
463
464 Miscellaneous
465 -------------
466 .. _hash-randomization:
467
468 * Hash randomization (``-R``) `is ignored in PyPy`_. In CPython
469 before 3.4 it has `little point`_. Both CPython >= 3.4 and PyPy3
470 implement the randomized SipHash algorithm and ignore ``-R``.
471
472 .. _non-string-locals-keys:
473
474 * You can't store non-string keys in type objects. For example::
475
476 class A(object):
477 locals()[42] = 3
478
479 won't work.
480
481 .. _setrecursionlimit:
482
483 * ``sys.setrecursionlimit(n)`` sets the limit only approximately,
484 by setting the usable stack space to ``n * 768`` bytes. On Linux,
485 depending on the compiler settings, the default of 768KB is enough
486 for about 1400 calls.
487
488 .. _hash_calls:
489
490 * since the implementation of dictionary is different, the exact number
491 of times that ``__hash__`` and ``__eq__`` are called is different.
492 Since CPython
493 does not give any specific guarantees either, don't rely on it.
494
495 .. _builtins:
496
497 * the ``__builtins__`` name is always referencing the ``__builtin__`` module,
498 never a dictionary as it sometimes is in CPython. Assigning to
499 ``__builtins__`` has no effect. (For usages of tools like
500 RestrictedPython, see `issue #2653`_.) This also means PyPy does not add
501 a ``__builtins__`` attribute to functions (python3.10+)
502
503 .. _dunder-failures:
504
505 * directly calling the internal magic methods of a few built-in types
506 with invalid arguments may have a slightly different result. For
507 example, ``[].__add__(None)`` and ``(2).__add__(None)`` both return
508 ``NotImplemented`` on PyPy; on CPython, only the latter does, and the
509 former raises ``TypeError``. (Of course, ``[]+None`` and ``2+None``
510 both raise ``TypeError`` everywhere.) This difference is an
511 implementation detail that shows up because of internal C-level slots
512 that PyPy does not have.
513
514 .. _method-types:
515
516 * on CPython, ``[].__add__`` is a ``method-wrapper``, ``list.__add__``
517 is a ``slot wrapper`` and ``list.extend`` is a (built-in) ``method``
518 object. On PyPy these are all normal method or function objects (or
519 unbound method objects on PyPy2). This can occasionally confuse some
520 tools that inspect built-in types. For example, the standard
521 library ``inspect`` module has a function ``ismethod()`` that returns
522 True on unbound method objects but False on method-wrappers or slot
523 wrappers. On PyPy we can't tell the difference. So on PyPy2 we
524 have ``ismethod([].__add__) == ismethod(list.extend) == True``;
525 on PyPy3 we have ``isfunction(list.extend) == True``. On CPython
526 all of these are False.
527
528 .. _builtin-change-attribute:
529
530 * in CPython, the built-in types have attributes that can be
531 implemented in various ways. Depending on the way, if you try to
532 write to (or delete) a read-only (or undeletable) attribute, you get
533 either a ``TypeError`` or an ``AttributeError``. PyPy tries to
534 strike some middle ground between full consistency and full
535 compatibility here. This means that a few corner cases don't raise
536 the same exception, like ``del (lambda:None).__closure__``.
537
538 .. _subclass-methods:
539
540 * in pure Python, if you write ``class A(object): def f(self): pass``
541 and have a subclass ``B`` which doesn't override ``f()``, then
542 ``B.f(x)`` still checks that ``x`` is an instance of ``B``. In
543 CPython, types written in C use a different rule. If ``A`` is
544 written in C, any instance of ``A`` will be accepted by ``B.f(x)``
545 (and actually, ``B.f is A.f`` in this case). Some code that could
546 work on CPython but not on PyPy includes:
547 ``datetime.datetime.strftime(datetime.date.today(), ...)`` (here,
548 ``datetime.date`` is the superclass of ``datetime.datetime``).
549 Anyway, the proper fix is arguably to use a regular method call in
550 the first place: ``datetime.date.today().strftime(...)``
551
552 .. _gc-functions:
553
554 * some functions and attributes of the ``gc`` module behave in a
555 slightly different way: for example, ``gc.enable`` and
556 ``gc.disable`` are supported, but "enabling and disabling the GC" has
557 a different meaning in PyPy than in CPython. These functions
558 actually enable and disable the major collections and the
559 execution of finalizers.
560
561 .. _irc-topic:
562
563 * PyPy prints a random line from past #pypy IRC topics at startup in
564 interactive mode. In a released version, this behaviour is suppressed, but
565 setting the environment variable PYPY_IRC_TOPIC will bring it back. Note that
566 downstream package providers have been known to totally disable this feature.
567
568 .. _readline:
569
570 * PyPy's readline module was rewritten from scratch: it is not GNU's
571 readline. It should be mostly compatible, and it adds multiline
572 support (see ``multiline_input()``). On the other hand,
573 ``parse_and_bind()`` calls are ignored (issue `#2072`_).
574
575 .. _sys-getsizeof:
576
577 * ``sys.getsizeof()`` always raises ``TypeError`` (and objects do not have a
578 ``__sizeof__`` method). This is because a
579 memory profiler using this function is most likely to give results
580 inconsistent with reality on PyPy. It would be possible to have
581 ``sys.getsizeof()`` return a number (with enough work), but that may
582 or may not represent how much memory the object uses. It doesn't even
583 make really sense to ask how much *one* object uses, in isolation with
584 the rest of the system. For example, instances have maps, which are
585 often shared across many instances; in this case the maps would
586 probably be ignored by an implementation of ``sys.getsizeof()``, but
587 their overhead is important in some cases if they are many instances
588 with unique maps. Conversely, equal strings may share their internal
589 string data even if they are different objects---even a unicode string
590 and its utf8-encoded ``bytes`` version are shared---or empty containers
591 may share parts of their internals as long as they are empty. Even
592 stranger, some lists create objects as you read them; if you try to
593 estimate the size in memory of ``range(10**6)`` as the sum of all
594 items' size, that operation will by itself create one million integer
595 objects that never existed in the first place. Note that some of
596 these concerns also exist on CPython, just less so. For this reason
597 we explicitly don't implement ``sys.getsizeof()`` (nor ``__sizeof__``).
598
599 .. _timeit:
600
601 * The ``timeit`` module behaves differently under PyPy: it prints the average
602 time and the standard deviation, instead of the minimum, since the minimum is
603 often misleading.
604
605 .. _get_config_vars:
606
607 * The ``get_config_vars`` method of ``sysconfig`` and ``distutils.sysconfig``
608 are not complete. On POSIX platforms, CPython fishes configuration variables
609 from the Makefile used to build the interpreter. PyPy should bake the values
610 in during compilation, but does not do that yet.
611
612 * CPython's ``sys.settrace()`` sometimes reports an ``exception`` at the
613 end of ``for`` or ``yield from`` lines for the ``StopIteration``, and
614 sometimes not. The problem is that it occurs in an ill-defined subset
615 of cases. PyPy attempts to emulate that but the precise set of cases
616 is not exactly the same.
617
618 .. _mod-long:
619
620 * ``"%d" % x`` and ``"%x" % x`` and similar constructs, where ``x`` is
621 an instance of a subclass of ``long`` that overrides the special
622 methods ``__str__`` or ``__hex__`` or ``__oct__``: PyPy doesn't call
623 the special methods; CPython does---but only if it is a subclass of
624 ``long``, not ``int``. CPython's behavior is really messy: e.g. for
625 ``%x`` it calls ``__hex__()``, which is supposed to return a string
626 like ``-0x123L``; then the ``0x`` and the final ``L`` are removed, and
627 the rest is kept. If you return an unexpected string from
628 ``__hex__()`` you get an exception (or a crash before CPython 2.7.13).
629
630 .. _kwargs-strings:
631
632 * In PyPy, dictionaries passed as ``**kwargs`` can contain only string keys,
633 even for ``dict()`` and ``dict.update()``. CPython 2.7 allows non-string
634 keys in these two cases (and only there, as far as we know). E.g. this
635 code produces a ``TypeError``, on CPython 3.x as well as on any PyPy:
636 ``dict(**{1: 2})``. (Note that ``dict(**d1)`` is equivalent to
637 ``dict(d1)``.)
638
639 .. _class_assignment:
640
641 * assignment to ``__class__`` is limited to the cases where it
642 works on CPython 2.5. On CPython 2.6 and 2.7 it works in a bit
643 more cases, which are not supported by PyPy so far. (If needed,
644 it could be supported, but then it will likely work in many
645 *more* case on PyPy than on CPython 2.6/2.7.)
646 In PyPy 3, ``__class__`` attribute assignment between heaptypes and non
647 heaptypes. CPython allows that for module subtypes, but not for e.g. ``int``
648 or ``float`` subtypes. Currently PyPy does not support the
649 ``__class__`` attribute assignment for any non heaptype subtype.
650
651 .. _del_class_attributes:
652
653 * In PyPy, module and class dictionaries are optimized under the assumption
654 that deleting attributes from them are rare. Because of this, e.g.
655 ``del foo.bar`` where ``foo`` is a module (or class) that contains the
656 function ``bar``, is significantly slower than CPython.
657
658 .. _positional-keyword:
659
660 * Various built-in functions in CPython accept only positional arguments
661 and not keyword arguments. That can be considered a long-running
662 historical detail: newer functions tend to accept keyword arguments
663 and older function are occasionally fixed to do so as well. In PyPy,
664 most built-in functions accept keyword arguments (``help()`` shows the
665 argument names). But don't rely on it too much because future
666 versions of PyPy may have to rename the arguments if CPython starts
667 accepting them too.
668
669 .. _distutils-windows:
670
671 * PyPy3: ``distutils`` has been enhanced to allow finding ``VsDevCmd.bat`` in the
672 directory pointed to by the ``VS%0.f0COMNTOOLS`` (typically ``VS140COMNTOOLS``)
673 environment variable. CPython searches for ``vcvarsall.bat`` somewhere **above**
674 that value.
675
676 .. _syntax-error-messages:
677
678 * SyntaxError_ s try harder to give details about the cause of the failure, so
679 the error messages are not the same as in CPython
680
681 .. _ordered-sets:
682
683 * Dictionaries and sets are ordered on PyPy. On CPython < 3.6 they are not;
684 on CPython >= 3.6 dictionaries (but not sets) are ordered.
685
686 .. _lonepycfile-pypy2:
687
688 * PyPy2 refuses to load lone ``.pyc`` files, i.e. ``.pyc`` files that are
689 still there after you deleted the ``.py`` file. PyPy3 instead behaves like
690 CPython. We could be amenable to fix this difference in PyPy2: the current
691 version reflects `our annoyance`__ with this detail of CPython, which bit
692 us too often while developing PyPy. (It is as easy as passing the
693 ``--lonepycfile`` flag when translating PyPy, if you really need it.)
694
695 .. __: https://stackoverflow.com/a/55499713/1556290
696
697 * PyPy3 does not implement the ``_pth`` `file protocol`_ to override ``sys.path``.
698
699 .. _`file protocol`: https://docs.python.org/3/library/sys_path_init.html#pth-files
700
701 .. _extension-modules:
702
703 Extension modules
704 -----------------
705
706 List of extension modules that we support:
707
708 * Supported as built-in modules (in :source:`pypy/module/`):
709
710 __builtin__
711 :doc:`__pypy__ <__pypy__-module>`
712 _ast
713 _codecs
714 _collections
715 :doc:`_continuation <stackless>`
716 :doc:`_ffi <discussion/ctypes-implementation>`
717 _hashlib
718 _io
719 _locale
720 _lsprof
721 _md5
722 :doc:`_minimal_curses <config/objspace.usemodules._minimal_curses>`
723 _multiprocessing
724 _random
725 :doc:`_rawffi <discussion/ctypes-implementation>`
726 _sha
727 _socket
728 _sre
729 _ssl
730 _warnings
731 _weakref
732 _winreg
733 array
734 binascii
735 bz2
736 cStringIO
737 cmath
738 `cpyext`_
739 crypt
740 errno
741 exceptions
742 fcntl
743 gc
744 imp
745 itertools
746 marshal
747 math
748 mmap
749 operator
750 parser
751 posix
752 pyexpat
753 select
754 signal
755 struct
756 symbol
757 sys
758 termios
759 thread
760 time
761 token
762 unicodedata
763 zlib
764
765 When translated on Windows, a few Unix-only modules are skipped,
766 and the following module is built instead:
767
768 _winreg
769
770 * Supported by being rewritten in pure Python (possibly using ``cffi``):
771 see the :source:`lib_pypy/` directory. Examples of modules that we
772 support this way: ``ctypes``, ``cPickle``, ``cmath``, ``dbm``, ``datetime``...
773 Note that some modules are both in there and in the list above;
774 by default, the built-in module is used (but can be disabled
775 at translation time).
776
777 The extension modules (i.e. modules written in C, in the standard CPython)
778 that are neither mentioned above nor in :source:`lib_pypy/` are not available in PyPy.
779
780 .. _`is ignored in PyPy`: https://bugs.python.org/issue14621
781 .. _`little point`: https://events.ccc.de/congress/2012/Fahrplan/events/5152.en.html
782 .. _`#2072`: https://github.com/pypy/pypy/issues/2072/
783 .. _`issue #2653`: https://github.com/pypy/pypy/issues/2653/
784 .. _SyntaxError: https://www.pypy.org/posts/2018/04/improving-syntaxerror-in-pypy-5733639208090522433.html