Skip to content

Commit 44e9368

Browse files
danielcjacobsDaniel Jacobs
and
Daniel Jacobs
authored
Use PyConfig_InitPythonConfig instead of PyConfig_InitIsolatedConfig (#4473)
* Use PyConfig_InitPythonConfig instead of PyConfig_InitIsolatedConfig * add unit test for default python configuration --------- Co-authored-by: Daniel Jacobs <[email protected]>
1 parent c71e3af commit 44e9368

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

include/pybind11/embed.h

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -198,9 +198,10 @@ inline void initialize_interpreter(bool init_signal_handlers = true,
198198
init_signal_handlers, argc, argv, add_program_dir_to_path);
199199
#else
200200
PyConfig config;
201-
PyConfig_InitIsolatedConfig(&config);
202-
config.isolated = 0;
203-
config.use_environment = 1;
201+
PyConfig_InitPythonConfig(&config);
202+
// See PR #4473 for background
203+
config.parse_argv = 0;
204+
204205
config.install_signal_handlers = init_signal_handlers ? 1 : 0;
205206
initialize_interpreter(&config, argc, argv, add_program_dir_to_path);
206207
#endif

tests/test_embed/test_interpreter.cpp

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ TEST_CASE("Custom PyConfig") {
184184
py::initialize_interpreter();
185185
}
186186

187-
TEST_CASE("Custom PyConfig with argv") {
187+
TEST_CASE("scoped_interpreter with PyConfig_InitIsolatedConfig and argv") {
188188
py::finalize_interpreter();
189189
{
190190
PyConfig config;
@@ -199,6 +199,26 @@ TEST_CASE("Custom PyConfig with argv") {
199199
}
200200
py::initialize_interpreter();
201201
}
202+
203+
TEST_CASE("scoped_interpreter with PyConfig_InitPythonConfig and argv") {
204+
py::finalize_interpreter();
205+
{
206+
PyConfig config;
207+
PyConfig_InitPythonConfig(&config);
208+
209+
// `initialize_interpreter() overrides the default value for config.parse_argv (`1`) by
210+
// changing it to `0`. This test exercises `scoped_interpreter` with the default config.
211+
char *argv[] = {strdup("a.out"), strdup("arg1")};
212+
py::scoped_interpreter argv_scope(&config, 2, argv);
213+
std::free(argv[0]);
214+
std::free(argv[1]);
215+
auto module = py::module::import("test_interpreter");
216+
auto py_widget = module.attr("DerivedWidget")("The question");
217+
const auto &cpp_widget = py_widget.cast<const Widget &>();
218+
REQUIRE(cpp_widget.argv0() == "arg1");
219+
}
220+
py::initialize_interpreter();
221+
}
202222
#endif
203223

204224
TEST_CASE("Add program dir to path pre-PyConfig") {

0 commit comments

Comments
 (0)