pybind / pybind/pybind11

[QUESTION] Possibility to return py::object from py::init method

Open
#2,984 3 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

Hi,

Currently it seems to be impossible to return py::object from an init function. I'm wondering why this restriction is in place, and whether it could be removed, especially in the case where the class is marked with py::dynamic_attr. I could imagine an extra case where the underlying C++ type is checked to be of the correct type, i.e. compatible pointer, holder, or value.

Consider the following code:

class Dummy{};
py::class_<Dummy>( mod, "Dummy", py::dynamic_attr() )
        //.def( py::init( []() -> Dummy {return Dummy();})) // OK
        .def( py::init( []() -> py::object {
            py::object dummy = py::cast(Dummy());
            setattr(dummy, "foo", py::int_(1));
            return dummy;
        })) // Does not compile
        ;

With error:
pybind11\detail\init.h(86,48): error C2338: pybind11::init(): init function must return a compatible pointer, holder, or value

The equivalent python code works without issue

class Dummy:
    def __init__(self):
        setattr(self, "foo", 1)

d = Dummy() # no errors here

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the init validation in pybind11/detail/init.h, especially the assertion requiring a compatible pointer, holder, or value, and compare it with the py::dynamic_attr example in the issue. Determine the supported behavior and type-safety requirements for returning py::object, then add focused coverage demonstrating the intended constructor behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
api, backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.