Skip to content

Commit ea1da77

Browse files
committed
Add a test for PyInterpreterRef_Main().
1 parent fa961e9 commit ea1da77

3 files changed

Lines changed: 35 additions & 0 deletions

File tree

Lib/test/test_embed.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1920,6 +1920,9 @@ def test_gilstate_after_finalization(self):
19201920
def test_thread_state_ensure(self):
19211921
self.run_embedded_interpreter("test_thread_state_ensure")
19221922

1923+
def test_main_interpreter_ref(self):
1924+
self.run_embedded_interpreter("test_main_interpreter_ref")
1925+
19231926

19241927
class MiscTests(EmbeddingTestsMixin, unittest.TestCase):
19251928
def test_unicode_id_init(self):

Programs/_testembed.c

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2400,6 +2400,31 @@ test_gilstate_after_finalization(void)
24002400
return PyThread_detach_thread(handle);
24012401
}
24022402

2403+
static int
2404+
test_main_interpreter_ref(void)
2405+
{
2406+
// It should not work before the runtime has started.
2407+
PyInterpreterRef ref;
2408+
int res = PyInterpreterRef_Main(&ref);
2409+
(void)res;
2410+
assert(res == -1);
2411+
2412+
_testembed_initialize();
2413+
2414+
// Main interpreter is initialized and ready.
2415+
res = PyInterpreterRef_Main(&ref);
2416+
assert(res == 0);
2417+
assert(PyInterpreterRef_AsInterpreter(ref) == PyInterpreterState_Main());
2418+
PyInterpreterRef_Close(ref);
2419+
2420+
Py_Finalize();
2421+
2422+
// Main interpreter is dead, we can no longer acquire references to it.
2423+
res = PyInterpreterRef_Main(&ref);
2424+
assert(res == -1);
2425+
return 0;
2426+
}
2427+
24032428
/* *********************************************************
24042429
* List of test cases and the function that implements it.
24052430
*
@@ -2491,6 +2516,7 @@ static struct TestCase TestCases[] = {
24912516
{"test_get_incomplete_frame", test_get_incomplete_frame},
24922517
{"test_thread_state_ensure", test_thread_state_ensure},
24932518
{"test_gilstate_after_finalization", test_gilstate_after_finalization},
2519+
{"test_main_interpreter_ref", test_main_interpreter_ref},
24942520
{NULL, NULL}
24952521
};
24962522

Python/pystate.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3305,6 +3305,12 @@ PyInterpreterRef_Main(PyInterpreterRef *strong_ptr)
33053305
assert(strong_ptr != NULL);
33063306
_PyRuntimeState *runtime = &_PyRuntime;
33073307
HEAD_LOCK(runtime);
3308+
if (runtime->initialized == 0) {
3309+
// Main interpreter is not initialized.
3310+
// This can be the case before Py_Initialize(), or after Py_Finalize().
3311+
HEAD_UNLOCK(runtime);
3312+
return -1;
3313+
}
33083314
int res = try_acquire_strong_ref(&runtime->_main_interpreter, strong_ptr);
33093315
HEAD_UNLOCK(runtime);
33103316

0 commit comments

Comments
 (0)