Skip to content

[BUG] Confusing weakref constructor copy the object instead of creating a weakref #2536

@moralex1

Description

@moralex1

My colleague and I stumbled on a very confusing part of the API. When calling pybind11::weakref with a single argument that is of type py::object as such:


py::object WRONGcreateWeakRef(py::object object)
{
        return py::weakref(object);
}

Here is a correct way to call it:

py::object GOODcreateWeakRef(py::object object)
{
        return py::weakref(static_cast<py::handle>(object));
}

This is caused by the fact that the weakref constructor is explicit and the copy constructor is called instead. The result is that no weakref is created. This is very confusing. The copy constructor should allow only to copy weakref. May be by using a private copy constructor that takes an object and an public copy constructor that takes a weakref.

After some discussion on gitter, it seems that #2349 will solve this issue by raising a TypeError. However, the API would be still awkward.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions