aboutsummaryrefslogtreecommitdiffstats
path: root/sources/shiboken6/doc/typesystem_specialfunctions.rst
blob: 78a6ff4896c9d022032655f37fc82997c1af164c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
.. _special-functions:

Special functions
-----------------

.. _sequence-protocol:

Sequence Protocol
^^^^^^^^^^^^^^^^^

Support for the sequence protocol is achieved adding functions with special
names, this is done using the :ref:`add-function` tag.

The special function names are:

============= =============================================== ==================== ===================
Function name Parameters                                      Return type          CPython equivalent
============= =============================================== ==================== ===================
__len__       PyObject* self                                  Py_ssize_t           PySequence_Size
__getitem__   PyObject* self, Py_ssize_t _i                   PyObject*            PySequence_GetItem
__setitem__   PyObject* self, Py_ssize_t _i, PyObject* _value int                  PySequence_SetItem
__contains__  PyObject* self, PyObject* _value                int                  PySequence_Contains
__concat__    PyObject* self, PyObject* _other                PyObject*            PySequence_Concat
============= =============================================== ==================== ===================

You just need to inform the function name to the :ref:`add-function` tag, without any
parameter or return type information, when you do it, |project| will create a C
function with parameters and return type defined by the table above.

The function needs to follow the same semantics of the *CPython equivalent*
function, the only way to do it is using the
:ref:`inject-code <codeinjectionsemantics>` tag.

A concrete example how to add sequence protocol support to a class can be found
on shiboken tests, more precisely in the definition of the Str class in
``tests/samplebinding/typesystem_sample.xml``.

.. _bool-cast:

Bool Cast
^^^^^^^^^

Implementing bool casts enables using values which have a concept of validity
in boolean expressions. In C++, this is commonly implemented as
``operator bool() const``. In Qt, relevant classes have a
``bool isNull() const`` function.

In Python, the function ``__bool__`` is used for this. shiboken can generate
this functions depending on the command line options
:ref:`--use-operator-bool-as-nb-bool <use-operator-bool-as-nb-bool>`
and :ref:`--use-isnull-as-nb-bool <use-isnull-as-nb-bool>`,
which can be overridden by specifying the boolean attributes
**isNull** or **operator-bool** on the :ref:`value-type` or :ref:`object-type`
elements in typesystem XML.