-1

I'm trying to bind a function that accepts multiple arguments and keyword arguments with PYBIND. The function looks something like this:

{
    OutputSP output;
    InputSP input;
    if (args.size() == 1)
    {
        input = py::cast<InputSP>(args[0]);
    } else if (args.size() == 2)
    {
        query = py::cast<OutputSP>(args[0]);
        expression = py::cast<InputSP>(args[1]);
    }
    // TODO: Default values - should be elsewhere?
    Flags mode(Flags::FIRST_OPTION);
    std::vector<MultiFlags> status({ MultiFlags::COMPLETE });
    for (auto& kv : kwargs)
    {
        auto key_name = py::cast<string>(kv.first);
        if (key_name == "flag")
        {
            mode = py::cast<Flags>(kv.second);
        }
        else if (key_name == "status")
        {
            status = py::cast<std::vector<MultiFlags> >(kv.second);
        }
    }
    return method(output, input, mode, status);
}

Where Flags and MultiFlags are defined like this

    py::enum_<Flags>(m, "Flags")
        .value("FirstOption", Flags::FIRST_OPTION)
        .value("SecondOption", Flags::SECOND_OPTION)
        .export_values();

    py::enum_<MultiFlags>(m, "MultiFlags")
        .value("Complete", MultiFlags::COMPLETE)
        .value("Incomplete", MultiFlags::INCOMPLETE)
        .export_values();

and the wrapper with

m.def("method", &method_wrapper);

Now this should work fine if the call contains

status=[MultiFlags.Complete]

I'm looking for a way to check the type of the kwarg in advance so I could also accept a call that contains

status=MultiFlags.Complete

but can't find anything relevant in PYBIND11 docs. what is the correct way to do this?

Vlad Keel
  • 372
  • 2
  • 13

1 Answers1

0

Found it.

py::cast throws py::cast_error when casting fails, so I can treat the two options with try-catch:

else if (key_name == "status")
{
    try
    {
        status = py::cast<std::vector<MultiFlags> >(kv.second);
    } catch (py::cast_error&)
    {
        status = { py::cast<MultiFlags>(kv.second) };
    }
}
Vlad Keel
  • 372
  • 2
  • 13