What is the correct return value policy for a def_rw
accessor to an nb::ndarray
member variable?
#1101
mikeroberts3000
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello there, I have a quick silly question about return value policies. In particular, I'm curious about the correct return value policy to use in the following situation. Suppose I have a C++ container class that defines an
nb::ndarray
member variable.Suppose I use nanobind to define a
make_container
method at module scope in a Python extension module. Suppose this method: (1) creates a newContainer
object on the stack; (2) allocates some heap memory; (3) creates a newnb::ndarray
object on the stack using the heap-allocated memory for its internal storage; (4) assigns the stack-allocatednb::ndarray
to the stack-allocatedContainer
object'sarray
member variable; and (5) returns theContainer
object.In Python code, suppose I want to call
make_container
and access the returned NumPy array as follows.If I don't explicitly set a return value policy when calling
def_rw(...)
, I get the following error when attempting to accesscontainer.array
in the Python code above.In contrast, if I set
nb::rv_policy::reference
as the return value policy (as shown in the code snippet above), then this Python code behaves exactly as expected. When usingnb::rv_policy::reference
, the deletion callback for thenb::ndarray
gets called immediately after I assignarray = None
, but not before, which is exactly what I would expect. I verified the exact order of operations using print statements that I have omitted from the code above for brevity.This result has led to some confusion on my side though.
nb::rv_policy::reference
the correct policy to use in this type of situation, or does it just happen to work correctly in this specific case?nb::rv_policy::reference_internal
the correct policy to use? The documentation suggests this policy should be used when accessing member fields, so I would have guessed that it should be used here.nb::rv_policy::reference
, does assigningarray = container.array
increment some kind of reference count on thenb::ndarray&
reference returned by thedef_rw(...)
accessor? I'm assuming the accessor returns a reference but it wasn't totally clear to me if this is the case. When usingnb::rv_policy::reference
, how does Python know to wait untilarray = None
before calling the deletion callback for thenb::ndarray
?Beta Was this translation helpful? Give feedback.
All reactions