Arslan
Arslan

Reputation: 151

SWIG- Convert C++ enum to Python enum

I am working to get C++ class enum to python enum using swig. I have the following implementation in example.h file.

namespace colors{ 
 enum class Color{
    RED = 0,
    BLUE = 1,
    GREEN = 2
 };
}

My Swig interface file is

    %module api
%{
#include "example.h"
%}
%include "example.h"

But after using swig tool the interface provides the following usage

import pywarp_example as impl 
impl.RED

The question arise here is that is it possible to access enum like below thats the way we use in python?

impl.Color.RED Or impl.Color.RED.value

Upvotes: 4

Views: 3557

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177725

Unlike your example SWIG 3.0.12 would wrap your enum class example as Color_RED, Color_BLUE, and Color_GREEN. Here's an example that adds some additional Python code to remap that pattern into Color.RED, Color.BLUE, and Color.GREEN:

%pythoncode is added to the Python portion of the SWIG wrapper. After the Python extension loads this code runs. It collects and deletes variables starting with prefix_, renames them without prefix_, then creates a class named prefix with the new variables as class variables.

%module test

%inline %{
namespace colors{ 
 enum class Color{
    RED = 0,
    BLUE = 1,
    GREEN = 2
 };
}
%}

%pythoncode %{
from enum import Enum
def redo(prefix):
    tmpD = {k:v for k,v in globals().items() if k.startswith(prefix + '_')}
    for k,v in tmpD.items():
        del globals()[k]
    tmpD = {k[len(prefix)+1:]:v for k,v in tmpD.items()}
    # globals()[prefix] = type(prefix,(),tmpD) # pre-Enum support
    globals()[prefix] = Enum(prefix,tmpD)
redo('Color')
del redo  # cleaning up the namespace
del Enum
%}

Example use:

>>> import test
>>> dir(test)
['Color', '__builtin__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic', '_test']
>>> test.Color
<enum 'Color'>
>>> dir(test.Color)
['BLUE', 'GREEN', 'RED', '__class__', '__doc__', '__members__', '__module__']
>>> test.Color.BLUE
<Color.BLUE: 1>

Upvotes: 3

Arslan
Arslan

Reputation: 151

C++ Enum can be converted to python Enum using this script.

%pythoncode %{
from enum import Enum
def enum(prefix):
    tmpD = {k:v for k,v in globals().items() if k.startswith(prefix + '_')}
    for k,v in tmpD.items():
        del globals()[k]
    tmpD = {k[len(prefix)+1:]:v for k,v in tmpD.items()}
    globals()[prefix] = Enum(prefix,tmpD)
%}

Upvotes: 0

Related Questions