Enums

| Enums

Boost.Python has a nifty facility to capture and wrap C++ enums. While Python has no `enum` type, we'll often want to expose our C++ enums to Python as an `int`. Boost.Python's enum facility makes this easy while taking care of the proper conversions from Python's dynamic typing to C++'s strong static typing (in C++, ints cannot be implicitly converted to enums). To illustrate, given a C++ enum:

`

        enum choice { red, blue };

`

the construct:

`

        enum_<choice>("choice")
            .value("red", red)
            .value("blue", blue)
            ;

`

can be used to expose to Python. The new enum type is created in the current `scope()`, which is usually the current module. The snippet above creates a Python class derived from Python's `int` type which is associated with the C++ type passed as its first parameter.

what is a scope? The scope is a class that has an associated global Python object which controls the Python namespace in which new extension classes and wrapped functions will be defined as attributes. Details can be found here.

You can access those values in Python as

`

        >>> my_module.choice.red
        my_module.choice.red

`

where my_module is the module where the enum is declared. You can also create a new scope around a class:

`

        scope in_X = class_<X>("X")
                        .def( ... )
                        .def( ... )
                    ;

        // Expose X::nested as X.nested
        enum_<X::nested>("nested")
            .value("red", red)
            .value("blue", blue)
            ;

`

Copyright © 2002-2003 David Abrahams
Copyright © 2002-2003 Joel de Guzman
Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.