Debian Codegraph @

pypy/doc/objspace.rst

raw ◀ ▶
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 .. py:function:: bytes_w(w_x)
296
297 Takes an application level :py:class:`bytes` (on PyPy2 this equals
298 `str`) and returns a rpython byte string.
299
300 .. py:function:: text_w(w_x)
301
302 PyPy2 takes either a :py:class:`str` and returns a rpython byte
303 string, or it takes an :py:class:`unicode` and uses the systems
304 default encoding to return a rpython byte string.
305
306 .. py:function:: str_w(w_x)
307
308 **Deprecated. use text_w or bytes_w instead**
309 If :py:obj:`w_x` is an application-level string, return an interpreter-level string.
310 Otherwise raise :py:exc:`TypeError`.
311
312 .. py:function:: unicode_w(w_x)
313
314 Takes an application level :py:class:`unicode` and return an
315 interpreter-level unicode string. This method may disappear soon and
316 be replaced by :py:function:`text_w`.
317
318 .. py:function:: float_w(w_x)
319
320 If :py:obj:`w_x` is an application-level float, integer or long, return an
321 interpreter-level float. Otherwise raise :py:exc:`TypeError` (or:py:exc:`OverflowError`
322 in the case of very large longs).
323
324 .. py:function:: getindex_w(w_obj[, w_exception=None])
325
326 Call ``index(w_obj)``. If the resulting integer or long object can be converted
327 to an interpreter-level :py:class:`int`, return that. If not, return a clamped
328 result if :py:obj:`w_exception` is None, otherwise raise the exception at the
329 application level.
330
331 (If :py:obj:`w_obj` can't be converted to an index, :py:func:`index` will raise an
332 application-level :py:exc:`TypeError`.)
333
334 .. py:function:: interp_w(RequiredClass, w_x[, can_be_None=False])
335
336 If :py:obj:`w_x` is a wrapped instance of the given bytecode interpreter class,
337 unwrap it and return it. If :py:obj:`can_be_None` is :py:const:`True`, a wrapped
338 :py:const:`None` is also accepted and returns an interpreter-level :py:const:`None`.
339 Otherwise, raises an :py:exc:`OperationError` encapsulating a :py:exc:`TypeError`
340 with a nice error message.
341
342 .. py:function:: interpclass_w(w_x)
343
344 If :py:obj:`w_x` is a wrapped instance of an bytecode interpreter class -- for
345 example :py:class:`Function`, :py:class:`Frame`, :py:class:`Cell`, etc. -- return
346 it unwrapped. Otherwise return :py:const:`None`.
347
348
349 Data Members
350 ~~~~~~~~~~~~
351
352 .. py:data:: space.builtin
353
354 The :py:class:`Module` containing the builtins.
355
356 .. py:data:: space.sys
357
358 The ``sys`` :py:class:`Module`.
359
360 .. py:data:: space.w_None
361
362 The ObjSpace's instance of :py:const:`None`.
363
364 .. py:data:: space.w_True
365
366 The ObjSpace's instance of :py:const:`True`.
367
368 .. py:data:: space.w_False
369
370 The ObjSpace's instance of :py:const:`False`.
371
372 .. py:data:: space.w_Ellipsis
373
374 The ObjSpace's instance of :py:const:`Ellipsis`.
375
376 .. py:data:: space.w_NotImplemented
377
378 The ObjSpace's instance of :py:const:`NotImplemented`.
379
380 .. py:data:: space.w_int
381 space.w_float
382 space.w_long
383 space.w_tuple
384 space.w_str
385 space.w_unicode
386 space.w_type
387 space.w_instance
388 space.w_slice
389
390 Python's most common basic type objects.
391
392 .. py:data:: space.w_[XYZ]Error
393
394 Python's built-in exception classes (:py:class:`KeyError`, :py:class:`IndexError`,
395 etc).
396
397 .. TODO: is it worth listing out all ~50 builtin exception types (https://docs.python.org/2/library/exceptions.html)?
398
399 .. py:data:: ObjSpace.MethodTable
400
401 List of tuples containing ``(method_name, symbol, number_of_arguments, list_of_special_names)``
402 for the regular part of the interface.
403
404 *NOTE* that tuples are interpreter-level.
405
406 .. py:data:: ObjSpace.BuiltinModuleTable
407
408 List of names of built-in modules.
409
410 .. py:data:: ObjSpace.ConstantTable
411
412 List of names of the constants that the object space should define.
413
414 .. py:data:: ObjSpace.ExceptionTable
415
416 List of names of exception classes.
417
418 .. py:data:: ObjSpace.IrregularOpTable
419
420 List of names of methods that have an irregular API (take and/or return
421 non-wrapped objects).
422
423
424 .. _standard-object-space:
425
426 The Standard Object Space
427 -------------------------
428
429 Introduction
430 ~~~~~~~~~~~~
431
432 The Standard Object Space (:source:`pypy/objspace/std/`) is the direct equivalent
433 of CPython's object library (the ``Objects/`` subdirectory in the distribution).
434 It is an implementation of the common Python types in a lower-level language.
435
436 The Standard Object Space defines an abstract parent class, :py:class:`W_Object`
437 as well as subclasses like :py:class:`W_IntObject`, :py:class:`W_ListObject`,
438 and so on. A wrapped object (a "black box" for the bytecode interpreter's main
439 loop) is an instance of one of these classes. When the main loop invokes an
440 operation (such as addition), between two wrapped objects :py:obj:`w1` and
441 :py:obj:`w2`, the Standard Object Space does some internal dispatching (similar
442 to ``Object/abstract.c`` in CPython) and invokes a method of the proper
443 :py:class:`W_XYZObject` class that can perform the operation.
444
445 The operation itself is done with the primitives allowed by RPython, and the
446 result is constructed as a wrapped object. For example, compare the following
447 implementation of integer addition with the function :c:func:`int_add()` in
448 ``Object/intobject.c``: ::
449
450 def add__Int_Int(space, w_int1, w_int2):
451 x = w_int1.intval
452 y = w_int2.intval
453 try:
454 z = ovfcheck(x + y)
455 except OverflowError:
456 raise FailedToImplementArgs(space.w_OverflowError,
457 space.wrap("integer addition"))
458 return W_IntObject(space, z)
459
460 This may seem like a lot of work just for integer objects (why wrap them into
461 :py:class:`W_IntObject` instances instead of using plain integers?), but the
462 code is kept simple and readable by wrapping all objects (from simple integers
463 to more complex types) in the same way.
464
465 (Interestingly, the obvious optimization above has actually been made in PyPy,
466 but isn't hard-coded at this level -- see :doc:`interpreter-optimizations`.)
467
468
469 Object types
470 ~~~~~~~~~~~~
471
472 The larger part of the :source:`pypy/objspace/std/` package defines and
473 implements the library of Python's standard built-in object types. Each type
474 ``xxx`` (:py:class:`int`, :py:class:`float`, :py:class:`list`,
475 :py:class:`tuple`, :py:class:`str`, :py:class:`type`, etc.) is typically
476 implemented in the module ``xxxobject.py``.
477
478 The ``W_AbstractXxxObject`` class, when present, is the abstract base
479 class, which mainly defines what appears on the Python-level type
480 object. There are then actual implementations as subclasses, which are
481 called ``W_XxxObject`` or some variant for the cases where we have
482 several different implementations. For example,
483 :source:`pypy/objspace/std/bytesobject.py` defines ``W_AbstractBytesObject``,
484 which contains everything needed to build the ``str`` app-level type;
485 and there are subclasses ``W_BytesObject`` (the usual string) and
486 ``W_Buffer`` (a special implementation tweaked for repeated
487 additions, in :source:`pypy/objspace/std/bufferobject.py`). For mutable data
488 types like lists and dictionaries, we have a single class
489 ``W_ListObject`` or ``W_DictMultiObject`` which has an indirection to
490 the real data and a strategy; the strategy can change as the content of
491 the object changes.
492
493 From the user's point of view, even when there are several
494 ``W_AbstractXxxObject`` subclasses, this is not visible: at the
495 app-level, they are still all instances of exactly the same Python type.
496 PyPy knows that (e.g.) the application-level type of its
497 interpreter-level ``W_BytesObject`` instances is str because there is a
498 ``typedef`` class attribute in ``W_BytesObject`` which points back to
499 the string type specification from :source:`pypy/objspace/std/bytesobject.py`;
500 all other implementations of strings use the same ``typedef`` from
501 :source:`pypy/objspace/std/bytesobject.py`.
502
503 For other examples of multiple implementations of the same Python type,
504 see :doc:`interpreter-optimizations`.
505
506
507 Object Space proxies
508 --------------------
509
510 We have implemented several *proxy object spaces*, which wrap another object
511 space (typically the standard one) and add some capabilities to all objects. To
512 find out more, see :doc:`objspace-proxies`.