Skip to content

fix: functional returning a pointer policy - #1043

Draft
henryiii wants to merge 11 commits into
pybind:masterfrom
henryiii:functional
Draft

henryiii wants to merge 11 commits into
pybind:masterfrom
henryiii:functional

Conversation

@henryiii

@henryiii henryiii commented Aug 30, 2017 •

Copy link
Copy Markdown
Collaborator

🤖 AI text below 🤖

Fixes #1041. Fixes #1072.

py::cast() resolves automatic and automatic_reference to copy/move/take_ownership/reference before it calls the caster. For an lvalue std::function, that gave copy to the functional caster, which passed it to the wrapped function as the policy for its return value. A std::function<T *()> with a non-copyable T then failed with return_value_policy = copy, but type T is non-copyable!.

This PR adds the trait detail::cast_forwards_automatic_policy<T>. py::cast() does not resolve the automatic policies when the trait is true. functional.h sets it for std::function, so the wrapped function resolves the policy for its return value, as it does on the function-return path. The trait is also true for a class template that has a std::function template argument (std::pair, std::vector, std::reference_wrapper, ...) and for std::array.

In a cast of a pointer to a std::function, the policy applies to the std::function object. With take_ownership, the caster deletes that object and now gives the wrapped function automatic. Before, the wrapped function also got take_ownership, so Python deleted each object that it returned.

Behavior change: py::cast(fn) of an lvalue std::function<T *()> gave Python a copy of the returned object. Python now gets a reference that it does not own, as with py::cast(ptr). This differs from py::cpp_function(fn), which has the default policy automatic and gives Python the ownership. The docs have a note about this.

All other types keep the current py::cast() behavior. For example, py::cast(vec) on an lvalue std::vector<T *> still copies each element.

The new tests in test_callbacks check ownership. The top-level cast test fails on master, and the container and pointer tests fail without the last commit.

Suggested changelog entry:

  • py::cast() of a std::function (also in a container) now forwards the automatic return value policies to the wrapped function, so a std::function that returns a pointer to a non-copyable type can be cast. A std::function that returns a raw pointer now gives Python a non-owning reference where it gave a copy before.
  • py::cast() of a pointer to a std::function with take_ownership no longer gives take_ownership to the wrapped function.

📚 Documentation preview 📚: https://pybind11--1043.org.readthedocs.build/

@henryiii

Copy link
Copy Markdown
Collaborator Author

Feel free to close this (or I will) if the decision is that forwarding on function creation is correct (it very well may be).

@wjakob

wjakob commented Aug 30, 2017

Copy link
Copy Markdown
Member

I don't think this is the best way to address the underlying issue, since it imposes a fixed policy -- instead, we should fix the logic that forwards the return value policy to the std::function caster (see my comment on #1041)

@henryiii

Copy link
Copy Markdown
Collaborator Author

Sounds good. The tests in the PR are possibly still useful as a basis to see if the forwarding behavior is fixed.

@henryiii henryiii changed the title Functional returning a pointer fix WIP: Functional returning a pointer policy Aug 30, 2017
@henryiii
henryiii force-pushed the functional branch 2 times, most recently from 715d03c to 7aa38af Compare August 31, 2017 01:36
@henryiii

henryiii commented Aug 31, 2017 •

Copy link
Copy Markdown
Collaborator Author

I tracked down the policy calls and it seems to be making a decision to copy at the end if you keep automatic, as well. So if you simply comment out these four lines:

if (policy == return_value_policy::automatic)
policy = std::is_pointer<T>::value ? return_value_policy::take_ownership : return_value_policy::copy;
else if (policy == return_value_policy::automatic_reference)
policy = std::is_pointer<T>::value ? return_value_policy::reference : return_value_policy::copy;

Automatic gets passed down the chain and the tests I've added pass along with all the others.

The place where automatic goes to copy is here:

if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference)
policy = return_value_policy::copy;

Is there a reason for those initial lines (1607-1610)?

@dean0x7d

dean0x7d commented Sep 9, 2017

Copy link
Copy Markdown
Member

Removing those policy translations from py::cast() does seem reasonable to me and it looks like it doesn't affect the tests in any way. AFAIK all the casters which need policies already know how to translate policies internally because other to-Python conversions (which don't do through py::cast()) don't have these extra policy checks.

The only questions is if there are any casters or situations that do require the policy translations made in py::cast(), but that are not currently covered by the test suite. @wjakob Is there a special reason for those 4 lines in py::cast()? If they can be removed, it would propagate the automatic policy to the casters which seems desirable.

(Although, I wouldn't recommend to make this change for v2.2.1. Better for v2.3 so it can sit in master for a while and we can see if there are any issues with it.)

@dean0x7d dean0x7d mentioned this pull request Sep 10, 2017
@henryiii henryiii changed the title WIP: Functional returning a pointer policy Functional returning a pointer policy Sep 10, 2017
@henryiii

henryiii commented Apr 4, 2018

Copy link
Copy Markdown
Collaborator Author

Does this need to be merged to master so it can sit in master for a while? I've rebased on current master.

@henryiii

Copy link
Copy Markdown
Collaborator Author

Could this be useful in 2.3.0?

Comment thread include/pybind11/cast.h Resolved
Comment thread tests/test_callbacks.cpp Resolved
Comment thread tests/test_callbacks.py Resolved
@henryiii henryiii closed this Sep 23, 2021
@henryiii henryiii reopened this Sep 23, 2021
@henryiii henryiii changed the title Functional returning a pointer policy fix!: functional returning a pointer policy Nov 12, 2026
@rwgk

rwgk commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

— codex on behalf of Ralf —

Preserve ownership for existing py::cast(..., automatic) calls. Deferring normalization changes what happens when an lvalue std::vector<Item *> is cast with explicit return_value_policy::automatic. Before this change, the lvalue policy copies the pointees. The forwarded automatic now reaches each raw-pointer caster and transfers ownership. With a vector containing unique_owner.get(), destroying the resulting Python list destroyed the source object on this head, leaving the C++ owner dangling. The base preserved the C++-owned object. I reproduced the difference on with-GIL and free-threaded CPython 3.15.2. Can the deferred policy be scoped to the callable case so existing py::cast ownership semantics are preserved? Policy forwarding · Container element forwarding · Earlier policy discussion

Ralf has yet to review these findings.

@henryiii

Copy link
Copy Markdown
Collaborator Author

🤖 AI text below 🤖

@rwgk The finding is correct. I reproduced it: on 9501ae7, py::cast(vec, return_value_policy::automatic) on an lvalue std::vector<T *> gave Python ownership of the pointees, and automatic_reference gave references. On master, both copy.

Fixed in 48a4635:

  • py::cast() resolves the automatic policies again, as on master.
  • New trait detail::cast_forwards_automatic_policy<T> (default false). functional.h sets it to true for std::function, so only that caster gets the unresolved policy.
  • New regression test test_cast_lvalue_ptr_vector_copies in test_stl. It failed before the fix and passes now.

The PR description is updated. Other casters have no behavior change now, so the ! in the title is possibly not necessary.

@henryiii henryiii changed the title fix!: functional returning a pointer policy fix: functional returning a pointer policy Nov 21, 2026
henryiii and others added 7 commits November 22, 2026 09:44
Assisted-by: ClaudeCode:claude-fable-5-2
py::cast() resolves the automatic policies again, so nested casters
(for example an lvalue std::vector<T *>) keep the copy semantics.
Only the std::function caster gets the unresolved policy.

Assisted-by: ClaudeCode:claude-fable-5-2
Assisted-by: ClaudeCode:claude-opus-5-5
Assisted-by: ClaudeCode:claude-fable-5-2
@rwgk

rwgk commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

codex GPT-6.2-Sol ultra (I'll add a commit with the suggested fix):

I’d hold approval. The revision fixes the earlier vector regression and lets a directly cast std::function return a pointer to a non-copyable object. I verified both behaviors. Clang-Tidy and the previously failing MSVC 2022/Python 3.9 job passed. The focused callbacks and STL suites had 73 passes and one skip on each local CPython build. CI · Clang-Tidy

The new trait uses intrinsic_t<T>, which strips the pointer from std::function*. As a result, py::cast(ptr, return_value_policy::automatic) skips the conversion to take_ownership that used to delete the heap-allocated std::function wrapper. I confirmed that the wrapper stays alive after Python drops the callable. Using remove_cvref_t<T> for the trait lookup fixes the leak in the repro and preserves both intended behaviors. I’d make that one-line change and add a wrapper-lifetime assertion. Policy dispatch

Match the policy-forwarding trait through cv/ref qualifiers only. A raw pointer to a callable wrapper still needs automatic policy normalization to take ownership of that wrapper.

@rwgk rwgk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving, mostly based on a codex GPT-6.2-Sol ultra, after adding commit 86aea9b.

I'm leaving the final review and merging to @henryiii.

@henryiii henryiii self-assigned this Nov 23, 2026
py::cast() now forwards the automatic policies for a std::function in a
container. A pointer cast with take_ownership deletes the std::function
and gives the callable the automatic policy. Tests now check ownership,
and the docs describe the policy rules.

Assisted-by: ClaudeCode:claude-fable-5-2
@henryiii

Copy link
Copy Markdown
Collaborator Author

🤖 AI text below 🤖

A review of this branch found the problems below. The last commit fixes them.

Behavior change (documented, not changed). py::cast(fn) of an lvalue std::function<T *()> gave the callable the copy policy before this PR. It now gives automatic_reference, so Python gets a reference that it does not own, where it got a copy before. This also applies to obj.attr("x") = fn. The C++ object must stay alive while Python uses the reference. docs/advanced/cast/functional.rst now has a note about this, and the changelog entry includes it.

Pointer casts gave take_ownership to the callable. py::cast(new std::function<T &()>(...), py::return_value_policy::automatic) resolved the policy to take_ownership. The caster deleted the std::function correctly, but it also gave take_ownership to the callable, so Python called delete on each object that the callable returned. The std::function caster now has its own pointer overloads. With take_ownership, it deletes the std::function and gives the callable automatic.

The fix did not apply in containers. The trait matched only a top-level std::function. py::cast() of a std::pair, std::tuple, std::vector, std::optional, std::variant or std::reference_wrapper that holds a std::function still resolved the policy to copy or move, which gave the original error. cast_forwards_automatic_policy is now true for each class template that has such a type as a template argument, and for std::array.

Tests asserted nothing. The tests now check the result type and count destructor calls to check ownership. New cases cover an rvalue cast, a capturing lambda, an explicit automatic policy, a std::pair, std::ref, and an owned pointer. The std::pair, std::ref and owned pointer cases fail without the fix.

Comment in functional.h. The comment now says that the trait applies to value and reference casts only.

Known limits:

  • An explicit reference policy in a pointer cast still goes to the callable. Thus py::cast(&fn) gives the callable reference, and py::cast(fn) gives it automatic_reference. These differ only for a T & return.
  • A bound function that returns a std::function * with the default policy does not delete the std::function, as on master. A change there can make existing code delete a static object.
  • A custom caster for a class template that has a std::function template argument now gets automatic or automatic_reference from py::cast(), where it got copy or move before.

py::cpp_function has the default policy automatic, not
automatic_reference.

Assisted-by: ClaudeCode:claude-fable-5-2
@henryiii

Copy link
Copy Markdown
Collaborator Author

🤖 AI text below 🤖

Correction. The docs note and the PR description said that the new behavior agrees with py::cpp_function. That was wrong. py::cpp_function has the default policy automatic, so Python takes ownership of a raw pointer return. The last commit corrects the docs note, and the description is updated.

One inconsistency stays on this branch: m.attr("f") = fn gives Python a non-owning reference, and m.attr("f") = py::cpp_function(fn) gives Python the ownership.

Comparison with master

This comes from an inspection of the casters. The cases were not all run on master.

Same on both

  • m.def(...) with std::function arguments or a std::function return value. This is the most common use, and it does not go through py::cast().
  • A callable that returns int, std::string, py::object, a smart pointer, or a class by value. The policy has no effect there.
  • py::cast(fn) of an lvalue with a T & return. Python gets a copy.

Different

Code Master This branch
py::cast(fn) or m.attr("f") = fn, T * return Python gets a copy of *ptr. Error if T is not copyable (the issue). Python gets a non-owning reference.
py::cast(std::move(fn)) or m.attr("f") = std::function<...>(...), T * or T & return Each call moves from the C++ object. Error if T is not movable. T *: non-owning reference. T &: copy.
The same in a std::pair, std::vector, std::optional or std::ref As the two rows above As the two rows above
py::cast(new std::function<T &()>(...), take_ownership) Python deletes each object that the callable returns. Python gets a copy.
Callable returns std::vector<T *>, lvalue py::cast(fn) Each element is copied. Each element is a non-owning reference.

Assessment

  • The rvalue rows are bugs on master: a call silently moves from a C++ object. This branch is correct there.
  • The pointer cast row is also a bug on master, and this branch is correct.
  • The first row is a trade-off. The copy on master was safe for lifetime, but it hid mutations and failed for types that are not copyable. This branch agrees with py::cast(ptr), which also gives a non-owning reference. But Python can now hold a dangling reference if the C++ object is destroyed first. Code that relied on the copy will see aliasing after the update.

@henryiii

Copy link
Copy Markdown
Collaborator Author

As you might gather from the AI comparison, I still think this is a nice improvement and is better than master, it also can make a difference in some cases where someone was relying on a copy (not ideal if you returned a pointer, but still could happen). So I'd be okay to wait till the next minor release or even 4.0 if you'd prefer. Since it didn't change a single test of ours, I'd also be okay with it now.

@rwgk

rwgk commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

I'd say let's hold off with this change for now.

From a codex conversation, where I also asked codex to analyze what we did in pybind11clif:

I’d hold #1043. Henry’s follow-up improves the tests and fixes the case where taking ownership of a std::function* also made Python delete a C++ object returned by reference. I found two regressions in the new commits.

  1. A callable can change ownership of an unrelated element in the same container. For an lvalue std::pair<Widget*, std::function<int()>>, master copies the Widget. On the PR head, the callable makes the whole pair forward the unresolved policy. The default now borrows the original Widget, and explicit automatic makes Python delete it even though C++ still owns it. I reproduced both outcomes. The new pair test uses an int alongside the callable, so it misses the ownership change. Policy selection · Pair element conversion
  2. An owning cast of a mutable std::function* now copies the callable. The new overload routes through const std::function*. With a target that throws on copy, master moved the wrapper and succeeded. The PR throws and leaves the heap wrapper allocated. I’d preserve the move and use RAII for the wrapper being consumed. Pointer overloads

Yes, pybind11clif explicitly handled raw pointer returns. For bound C++ classes, _clif_automatic borrowed T*, kept the parent alive when one was supplied, and copied const T*. The class caster made that choice. functional.h forwarded the supplied policy pack to the callable. I verified that an ordinary lvalue py::cast(fn) still copied the pointee in pybind11clif, while explicitly passing _clif_automatic borrowed a mutable pointee. CLIF pointer rules · Callable policy forwarding

The useful precedent is per-element policy selection. I verified that a CLIF policy pack could copy the ordinary pointer in a pair and borrow the callable’s result in the same conversion. I’d drop the blanket container trait from #1043, keep the direct callable fix and repair the owned-wrapper path, then handle nested callables separately. Henry’s release-timing question still matters for the intended change from copy to borrow. Also, the new owned-wrapper overload passes automatic to the callable, which still takes ownership of a raw pointer to a bound class. Its new T& test correctly demonstrates a copy for that case. CLIF per-element conversion · Ownership probes and results

@henryiii

Copy link
Copy Markdown
Collaborator Author

Okay, I'll put it no draft until we are ready for 3.3 or 4.0.

@henryiii
henryiii marked this pull request as draft November 23, 2026 14:59

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Inconsistent default return_value_policy for positional and named arguments function<Type*(void)> will attempt to copy Type on return

4 participants