Skip to content

Commit c5b5b58

Browse files
committed
Add docs on py3 enums
1 parent fbf5987 commit c5b5b58

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

docs/classes.rst

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,3 +443,46 @@ The entries defined by the enumeration type are exposed in the ``__members__`` p
443443
...
444444
445445
By default, these are omitted to conserve space.
446+
447+
Python 3 enumerations
448+
=====================
449+
450+
Python 3 provides support for rich enumeration types in ``enum`` module [#enum]_ of the
451+
standard library; it can be also used in Python 2 by installing ``enum34`` backport package.
452+
453+
In order to expose a C++ enumeration type as a subclass of ``enum.IntEnum`` in Python,
454+
one can use the :class:`py3_enum` wrapper whose interface is similar to that of :class:`enum_`:
455+
456+
.. code-block:: cpp
457+
458+
enum class Captain {
459+
Kirk = 0,
460+
Picard
461+
};
462+
463+
The binding code will look like this:
464+
465+
.. code-block:: cpp
466+
467+
py::py3_enum<Captain>(m, "Captain")
468+
.value("Kirk", Captain::Kirk)
469+
.value("Picard", Captain::Picard);
470+
471+
The corresponding Python type is a subclass of ``enum.IntEnum`` and, as a result, is also
472+
a subclass of ``int``:
473+
474+
.. code-block:: pycon
475+
476+
>>> Captain.mro()
477+
[<enum 'Captain'>, <enum 'IntEnum'>, int, <enum 'Enum'>, object]
478+
>>> list(Captain)
479+
[<Captain.Kirk: 0>, <Captain.Picard: 1>]
480+
>>> int(Captain.Picard)
481+
1
482+
>>> Captain.Kirk.name, Captain.Kirk.value
483+
('Kirk', 0)
484+
485+
For more details on ``IntEnum`` functionality, see the official docs [#intenum]_.
486+
487+
.. [#enum] https://docs.python.org/3/library/enum.html
488+
.. [#intenum] https://docs.python.org/3/library/enum.html#intenum

0 commit comments

Comments
 (0)