Skip to content

setting properties in __init__ and nb::inst_set_state #664

Closed Answered by wjakob
wojdyr asked this question in Q&A
Discussion options

You must be logged in to vote

The Python instance isn't marked as properly initialized until the constructor finishes. That's important -- for example, what if one of the keyword arguments doesn't exist? Then the constructor will raise an exception, and the object should be invalid. But you just marked it as properly constructed. The following is safer and doesn't depend on implementation details (untested, may contain syntax errors).

.def(nb::init<Options>())
.def("__init__", [](Options* opt, nb::kwargs kwargs) {
  nb::object other = nb::type<Options>()();
  for (auto [key, value] : kwargs)
    other.attr(key) = nb::cast<bool>(value);
  new (opt) Options(nb::cast<const Options &>(other));
})

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@wojdyr
Comment options

Answer selected by wojdyr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants