pybind / pybind/pybind11

Lazy default argument construction

Open
#1,218 3 comments 0 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

Issue description

Having a non primitive default argument will cause its instantiation when loading the module using python import.
If the default argument's construction takes too long or performs some undesired action there is no way to avoid it (without changing my C++ code).
Is there a way to solve this issue? or work around it?

Reproducible example code

MyLib.dll:

    class SomeClass
    {
    public:
        SomeClass()
        {
            std::cout << "SomeClass" << std::endl;
        }
    };
    class MyClass
    {
    public:
        MyClass(SomeClass s = SomeClass())
        {
            std::cout << "MyClass" << std::endl;
        }
    };

MyLibWrapper.cpp:

    py::class_<SomeClass> SomeClass(m, "SomeClass");
    py::class_<MyClass> MyClass(m, "MyClass");
    MyClass.def(py::init<SomeClass>(), "s"_a = SomeClass());

In python, calling:

import MyLibWrapper

will print:

SomeClass

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 from the py::class_ registration and the MyClass.def(py::init(), "s"_a = SomeClass()) example, then reproduce the behavior with import MyLibWrapper. Determine whether pybind11 provides a lazy default or documented workaround, and verify that importing the module no longer constructs SomeClass unnecessarily.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, python
Domain
api, developer-experience
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.