Debian Codegraph @

pypy/doc/objspace.rst

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 The Object Space
2 ================
3
4 .. contents::
5
6
7 .. _objectspace:
8 .. _Object Space:
9
10 Introduction
11 ------------
12
13 The object space creates all objects in PyPy, and knows how to perform operations
14 on them. It may be helpful to think of an object space as being a library
15 offering a fixed API: a set of *operations*, along with implementations that
16 correspond to the known semantics of Python objects.
17
18 For example, :py:func:`add` is an operation, with implementations in the object
19 space that perform numeric addition (when :py:func:`add` is operating on numbers),
20 concatenation (when :py:func:`add` is operating on sequences), and so on.
21
22 We have some working object spaces which can be plugged into
23 the bytecode interpreter:
24
25 - The *Standard Object Space* is a complete implementation
26 of the various built-in types and objects of Python. The Standard Object
27 Space, together with the bytecode interpreter, is the foundation of our Python
28 implementation. Internally, it is a set of :ref:`interpreter-level <interpreter-level>` classes
29 implementing the various :ref:`application-level <application-level>` objects -- integers, strings,
30 lists, types, etc. To draw a comparison with CPython, the Standard Object
31 Space provides the equivalent of the C structures :c:type:`PyIntObject`,
32 :c:type:`PyListObject`, etc.
33
34 - various `Object Space proxies`_ wrap another object space (e.g. the standard
35 one) and adds new capabilities, like lazily computed objects (computed only
36 when an operation is performed on them), security-checking objects,
37 distributed objects living on several machines, etc.
38
39 The various object spaces documented here can be found in :source:`pypy/objspace`.
40
41 Note that most object-space operations take and return
42 :ref:`application-level <application-level>` objects, which are treated as
43 opaque "black boxes" by the interpreter. Only a very few operations allow the
44 bytecode interpreter to gain some knowledge about the value of an
45 application-level object.
46
47 .. _objspace-interface:
48
49 Object Space Interface
50 ----------------------
51
52 This is the public API that all Object Spaces implement:
53
54
55 Administrative Functions
56 ~~~~~~~~~~~~~~~~~~~~~~~~
57
58 .. py:function:: getexecutioncontext()
59
60 Return the currently active execution context.
61 (:source:`pypy/interpreter/executioncontext.py`).
62
63 .. py:function:: getbuiltinmodule(name)
64
65 Return a :py:class:`Module` object for the built-in module given by ``name``.
66 (:source:`pypy/interpreter/module.py`).
67
68
69 Operations on Objects in the Object Space
70 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
71
72 These functions both take and return "wrapped" (i.e. :ref:`application-level <application-level>`) objects.
73
74 The following functions implement operations with straightforward semantics that
75 directly correspond to language-level constructs:
76
77 ``id, type, issubtype, iter, next, repr, str, len, hash,``
78
79 ``getattr, setattr, delattr, getitem, setitem, delitem,``
80
81 ``pos, neg, abs, invert, add, sub, mul, truediv, floordiv, div, mod, divmod, pow, lshift, rshift, and_, or_, xor,``
82
83 ``nonzero, hex, oct, int, float, long, ord,``
84
85 ``lt, le, eq, ne, gt, ge, cmp, coerce, contains,``
86
87 ``inplace_add, inplace_sub, inplace_mul, inplace_truediv, inplace_floordiv,
88 inplace_div, inplace_mod, inplace_pow, inplace_lshift, inplace_rshift,
89 inplace_and, inplace_or, inplace_xor,``
90
91 ``get, set, delete, userdel``
92
93 .. py:function:: call(w_callable, w_args, w_kwds)
94
95 Calls a function with the given positional (``w_args``) and keyword (``w_kwds``)
96 arguments.
97
98 .. py:function:: index(w_obj)
99
100 Implements index lookup (`as introduced in CPython 2.5`_) using ``w_obj``. Will return a
101 wrapped integer or long, or raise a :py:exc:`TypeError` if the object doesn't have an
102 :py:func:`__index__` special method.
103
104 .. _as introduced in CPython 2.5: https://www.python.org/dev/peps/pep-0357/
105
106 .. py:function:: is_(w_x, w_y)
107
108 Implements ``w_x is w_y``.
109
110 .. py:function:: isinstance(w_obj, w_type)
111
112 Implements :py:func:`issubtype` with ``type(w_obj)`` and ``w_type`` as arguments.
113
114 .. py:function::exception_match(w_exc_type, w_check_class)
115
116 Checks if the given exception type matches :py:obj:`w_check_class`. Used in
117 matching the actual exception raised with the list of those to catch in an
118 except clause.
119
120
121 Convenience Functions
122 ~~~~~~~~~~~~~~~~~~~~~
123
124 The following functions are used so often that it was worthwhile to introduce
125 them as shortcuts -- however, they are not strictly necessary since they can be
126 expressed using several other object space methods.
127
128 .. py:function:: eq_w(w_obj1, w_obj2)
129
130 Returns :py:const:`True` when :py:obj:`w_obj1` and :py:obj:`w_obj2` are equal.
131 Shortcut for ``space.is_true(space.eq(w_obj1, w_obj2))``.
132
133 .. py:function:: is_w(w_obj1, w_obj2)
134
135 Shortcut for ``space.is_true(space.is_(w_obj1, w_obj2))``.
136
137 .. py:function:: hash_w(w_obj)
138
139 Shortcut for ``space.int_w(space.hash(w_obj))``.
140
141 .. py:function:: len_w(w_obj)
142
143 Shortcut for ``space.int_w(space.len(w_obj))``.
144
145 *NOTE* that the above four functions return :ref:`interpreter-level <interpreter-level>`
146 objects, not :ref:`application-level <application-level>` ones!
147
148 .. py:function:: not_(w_obj)
149
150 Shortcut for ``space.newbool(not space.is_true(w_obj))``.
151
152 .. py:function:: finditem(w_obj, w_key)
153
154 Equivalent to ``getitem(w_obj, w_key)`` but returns an **interpreter-level** None
155 instead of raising a KeyError if the key is not found.
156
157 .. py:function:: call_function(w_callable, *args_w, **kw_w)
158
159 Collects the arguments in a wrapped tuple and dict and invokes
160 ``space.call(w_callable, ...)``.
161
162 .. py:function:: call_method(w_object, 'method', ...)
163
164 Uses :py:meth:`space.getattr` to get the method object, and then :py:meth:`space.call_function`
165 to invoke it.
166
167 .. py:function:: unpackiterable(w_iterable[, expected_length=-1])
168
169 Iterates over :py:obj:`w_x` (using :py:meth:`space.iter` and :py:meth:`space.next`)
170 and collects the resulting wrapped objects in a list. If ``expected_length`` is
171 given and the length does not match, raises an exception.
172
173 Of course, in cases where iterating directly is better than collecting the
174 elements in a list first, you should use :py:meth:`space.iter` and :py:meth:`space.next`
175 directly.
176
177 .. py:function:: unpacktuple(w_tuple[, expected_length=None])
178
179 Equivalent to :py:func:`unpackiterable`, but only for tuples.
180
181 .. py:function:: callable(w_obj)
182
183 Implements the built-in :py:func:`callable`.
184
185
186 Creation of Application Level objects
187 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
188
189 .. py:function:: wrap(x)
190
191 **Deprecated! Eventually this method should disappear.**
192 Returns a wrapped object that is a reference to the interpreter-level object
193 :py:obj:`x`. This can be used either on simple immutable objects (integers,
194 strings, etc.) to create a new wrapped object, or on instances of :py:class:`W_Root`
195 to obtain an application-level-visible reference to them. For example,
196 most classes of the bytecode interpreter subclass :py:class:`W_Root` and can
197 be directly exposed to application-level code in this way - functions, frames,
198 code objects, etc.
199
200 .. py:function:: newint(i)
201
202 Creates a wrapped object holding an integral value. ``newint`` creates an object
203 of type ``W_IntObject``.
204
205 .. py:function:: newlong(l)
206
207 Creates a wrapped object holding an integral value. The main difference to ``newint``
208 is the type of the argument (which is ``rpython.rlib.rbigint.rbigint``). On PyPy3 this
209 method will return an :py:class:`int` (PyPy2 it returns a :py:class:`long`).
210
211 .. py:function:: newbytes(t)
212
213 The given argument is a rpython bytestring. Creates a wrapped object
214 of type :py:class:`bytes` (both on PyPy2 and PyPy3).
215
216 .. py:function:: newtext(t)
217
218 The given argument is a rpython bytestring. Creates a wrapped object
219 of type :py:class:`str`. On PyPy3 this will return a wrapped unicode
220 object. The object will hold a utf-8-nosg decoded value of `t`.
221 The "utf-8-nosg" codec used here is slightly different from the
222 "utf-8" implemented in Python 2 or Python 3: it is defined as utf-8
223 without any special handling of surrogate characters. They are
224 encoded using the same three-bytes sequence that encodes any char in
225 the range from ``'\u0800'`` to ``'\uffff'``.
226
227 PyPy2 will return a bytestring object. No encoding/decoding steps will be applied.
228
229 .. py:function:: newbool(b)
230
231 Creates a wrapped :py:class:`bool` object from an :ref:`interpreter-level <interpreter-level>`
232 object.
233
234 .. py:function:: newtuple([w_x, w_y, w_z, ...])
235
236 Creates a new wrapped tuple out of an interpreter-level list of wrapped objects.
237
238 .. py:function:: newlist([..])
239
240 Creates a wrapped :py:class:`list` from an interpreter-level list of wrapped objects.
241
242 .. py:function:: newdict
243
244 Returns a new empty dictionary.
245
246 .. py:function:: newslice(w_start, w_end, w_step)
247
248 Creates a new slice object.
249
250 .. py:function:: newunicode(ustr)
251
252 Creates a Unicode string from an rpython unicode string.
253 This method may disappear soon and be replaced by :py:function:`newutf8`.
254
255 .. py:function:: newutf8(bytestr)
256
257 Creates a Unicode string from an rpython byte string, decoded as
258 "utf-8-nosg". On PyPy3 it is the same as :py:function:`newtext`.
259
260 Many more space operations can be found in :source:`pypy/interpreter/baseobjspace.py`
261 and :source:`pypy/objspace/std/objspace.py`.
262
263
264 Conversions from Application Level to Interpreter Level
265 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
266
267 .. py:function:: unwrap(w_x)
268
269 Returns the interpreter-level equivalent of :py:obj:`w_x` -- use this
270 **ONLY** for testing, because this method is not RPython and thus cannot be
271 translated! In most circumstances you should use the functions described
272 below instead.
273
274 .. py:function:: is_true(w_x)
275
276 Returns an interpreter-level boolean (:py:const:`True` or :py:const:`False`)
277 that gives the truth value of the wrapped object :py:obj:`w_x`.
278
279 This is a particularly important operation because it is necessary to implement,
280 for example, if-statements in the language (or rather, to be pedantic, to
281 implement the conditional-branching bytecodes into which if-statements are
282 compiled).
283
284 .. py:function:: int_w(w_x)
285
286 If :py:obj:`w_x` is an application-level integer or long which can be converted
287 without overflow to an integer, return an interpreter-level integer. Otherwise
288 raise :py:exc:`TypeError` or :py:exc:`OverflowError`.
289
290 .. py:function:: bigint_w(w_x)
291
292 If :py:obj:`w_x` is an application-level integer or long, return an interpreter-level
293 :py:class:`rbigint`. Otherwise raise :py:exc:`TypeError`.
294
295 .. automethod:: pypy.interpreter.baseobjspace.ObjSpace.bytes_w(w_x)
296 .. automethod:: pypy.interpreter.baseobjspace.ObjSpace.text_w(w_x)
297
298 .. py:function:: str_w(w_x)
299
300 **Deprecated. use text_w or bytes_w instead**
301 If :py:obj:`w_x` is an application-level string, return an interpreter-level string.
302 Otherwise raise :py:exc:`TypeError`.
303
304 .. py:function:: unicode_w(w_x)
305
306 Takes an application level :py:class:`unicode` and return an
307 interpreter-level unicode string. This method may disappear soon and
308 be replaced by :py:function:`text_w`.
309
310 .. py:function:: float_w(w_x)
311
312 If :py:obj:`w_x` is an application-level float, integer or long, return an
313 interpreter-level float. Otherwise raise :py:exc:`TypeError` (or:py:exc:`OverflowError`
314 in the case of very large longs).
315
316 .. py:function:: getindex_w(w_obj[, w_exception=None])
317
318 Call ``index(w_obj)``. If the resulting integer or long object can be converted
319 to an interpreter-level :py:class:`int`, return that. If not, return a clamped
320 result if :py:obj:`w_exception` is None, otherwise raise the exception at the
321 application level.
322
323 (If :py:obj:`w_obj` can't be converted to an index, :py:func:`index` will raise an
324 application-level :py:exc:`TypeError`.)
325
326 .. py:function:: interp_w(RequiredClass, w_x[, can_be_None=False])
327
328 If :py:obj:`w_x` is a wrapped instance of the given bytecode interpreter class,
329 unwrap it and return it. If :py:obj:`can_be_None` is :py:const:`True`, a wrapped
330 :py:const:`None` is also accepted and returns an interpreter-level :py:const:`None`.
331 Otherwise, raises an :py:exc:`OperationError` encapsulating a :py:exc:`TypeError`
332 with a nice error message.
333
334 .. py:function:: interpclass_w(w_x)
335
336 If :py:obj:`w_x` is a wrapped instance of an bytecode interpreter class -- for
337 example :py:class:`Function`, :py:class:`Frame`, :py:class:`Cell`, etc. -- return
338 it unwrapped. Otherwise return :py:const:`None`.
339
340
341 Data Members
342 ~~~~~~~~~~~~
343
344 .. py:data:: space.builtin
345
346 The :py:class:`Module` containing the builtins.
347
348 .. py:data:: space.sys
349
350 The ``sys`` :py:class:`Module`.
351
352 .. py:data:: space.w_None
353
354 The ObjSpace's instance of :py:const:`None`.
355
356 .. py:data:: space.w_True
357
358 The ObjSpace's instance of :py:const:`True`.
359
360 .. py:data:: space.w_False
361
362 The ObjSpace's instance of :py:const:`False`.
363
364 .. py:data:: space.w_Ellipsis
365
366 The ObjSpace's instance of :py:const:`Ellipsis`.
367
368 .. py:data:: space.w_NotImplemented
369
370 The ObjSpace's instance of :py:const:`NotImplemented`.
371
372 .. py:data:: space.w_int
373 space.w_float
374 space.w_long
375 space.w_tuple
376 space.w_str
377 space.w_unicode
378 space.w_type
379 space.w_instance
380 space.w_slice
381
382 Python's most common basic type objects.
383
384 .. py:data:: space.w_[XYZ]Error
385
386 Python's built-in exception classes (:py:class:`KeyError`, :py:class:`IndexError`,
387 etc).
388
389 .. TODO: is it worth listing out all ~50 builtin exception types (https://docs.python.org/2/library/exceptions.html)?
390
391 .. py:data:: ObjSpace.MethodTable
392
393 List of tuples containing ``(method_name, symbol, number_of_arguments, list_of_special_names)``
394 for the regular part of the interface.
395
396 *NOTE* that tuples are interpreter-level.
397
398 .. py:data:: ObjSpace.BuiltinModuleTable
399
400 List of names of built-in modules.
401
402 .. py:data:: ObjSpace.ConstantTable
403
404 List of names of the constants that the object space should define.
405
406 .. py:data:: ObjSpace.ExceptionTable
407
408 List of names of exception classes.
409
410 .. py:data:: ObjSpace.IrregularOpTable
411
412 List of names of methods that have an irregular API (take and/or return
413 non-wrapped objects).
414
415
416 .. _standard-object-space:
417
418 The Standard Object Space
419 -------------------------
420
421 Introduction
422 ~~~~~~~~~~~~
423
424 The Standard Object Space (:source:`pypy/objspace/std/`) is the direct equivalent
425 of CPython's object library (the ``Objects/`` subdirectory in the distribution).
426 It is an implementation of the common Python types in a lower-level language.
427
428 The Standard Object Space defines an abstract parent class, :py:class:`W_Object`
429 as well as subclasses like :py:class:`W_IntObject`, :py:class:`W_ListObject`,
430 and so on. A wrapped object (a "black box" for the bytecode interpreter's main
431 loop) is an instance of one of these classes. When the main loop invokes an
432 operation (such as addition), between two wrapped objects :py:obj:`w1` and
433 :py:obj:`w2`, the Standard Object Space does some internal dispatching (similar
434 to ``Object/abstract.c`` in CPython) and invokes a method of the proper
435 :py:class:`W_XYZObject` class that can perform the operation.
436
437 The operation itself is done with the primitives allowed by RPython, and the
438 result is constructed as a wrapped object. For example, compare the following
439 implementation of integer addition with the function :c:func:`int_add()` in
440 ``Object/intobject.c``: ::
441
442 def add__Int_Int(space, w_int1, w_int2):
443 x = w_int1.intval
444 y = w_int2.intval
445 try:
446 z = ovfcheck(x + y)
447 except OverflowError:
448 raise FailedToImplementArgs(space.w_OverflowError,
449 space.wrap("integer addition"))
450 return W_IntObject(space, z)
451
452 This may seem like a lot of work just for integer objects (why wrap them into
453 :py:class:`W_IntObject` instances instead of using plain integers?), but the
454 code is kept simple and readable by wrapping all objects (from simple integers
455 to more complex types) in the same way.
456
457 (Interestingly, the obvious optimization above has actually been made in PyPy,
458 but isn't hard-coded at this level -- see :doc:`interpreter-optimizations`.)
459
460
461 Object types
462 ~~~~~~~~~~~~
463
464 The larger part of the :source:`pypy/objspace/std/` package defines and
465 implements the library of Python's standard built-in object types. Each type
466 ``xxx`` (:py:class:`int`, :py:class:`float`, :py:class:`list`,
467 :py:class:`tuple`, :py:class:`str`, :py:class:`type`, etc.) is typically
468 implemented in the module ``xxxobject.py``.
469
470 The ``W_AbstractXxxObject`` class, when present, is the abstract base
471 class, which mainly defines what appears on the Python-level type
472 object. There are then actual implementations as subclasses, which are
473 called ``W_XxxObject`` or some variant for the cases where we have
474 several different implementations. For example,
475 :source:`pypy/objspace/std/bytesobject.py` defines ``W_AbstractBytesObject``,
476 which contains everything needed to build the ``str`` app-level type;
477 and there are subclasses ``W_BytesObject`` (the usual string) and
478 ``W_Buffer`` (a special implementation tweaked for repeated
479 additions, in :source:`pypy/objspace/std/bufferobject.py`). For mutable data
480 types like lists and dictionaries, we have a single class
481 ``W_ListObject`` or ``W_DictMultiObject`` which has an indirection to
482 the real data and a strategy; the strategy can change as the content of
483 the object changes.
484
485 From the user's point of view, even when there are several
486 ``W_AbstractXxxObject`` subclasses, this is not visible: at the
487 app-level, they are still all instances of exactly the same Python type.
488 PyPy knows that (e.g.) the application-level type of its
489 interpreter-level ``W_BytesObject`` instances is str because there is a
490 ``typedef`` class attribute in ``W_BytesObject`` which points back to
491 the string type specification from :source:`pypy/objspace/std/bytesobject.py`;
492 all other implementations of strings use the same ``typedef`` from
493 :source:`pypy/objspace/std/bytesobject.py`.
494
495 For other examples of multiple implementations of the same Python type,
496 see :doc:`interpreter-optimizations`.
497
498
499 Object Space proxies
500 --------------------
501
502 We have implemented several *proxy object spaces*, which wrap another object
503 space (typically the standard one) and add some capabilities to all objects. To
504 find out more, see :doc:`objspace-proxies`.