Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

gh-142417: Restore private _Py_InitializeMain() function#145472

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
vstinner merged 2 commits intopython:mainfromvstinner:revert_init_main
Mar 4, 2026
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 86 additions & 8 deletionsDoc/c-api/init_config.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2299,13 +2299,91 @@ Py_GetArgcArgv()

See also :c:member:`PyConfig.orig_argv` member.

Delaying main module execution
==============================

In some embedding use cases, it may be desirable to separate interpreter initialization
from the execution of the main module.
Multi-Phase Initialization Private Provisional API
==================================================

This separation can be achieved by setting ``PyConfig.run_command`` to the empty
string during initialization (to prevent the interpreter from dropping into the
interactive prompt), and then subsequently executing the desired main module
code using ``__main__.__dict__`` as the global namespace.
This section is a private provisional API introducing multi-phase
initialization, the core feature of :pep:`432`:

* "Core" initialization phase, "bare minimum Python":

* Builtin types;
* Builtin exceptions;
* Builtin and frozen modules;
* The :mod:`sys` module is only partially initialized
(ex: :data:`sys.path` doesn't exist yet).

* "Main" initialization phase, Python is fully initialized:

* Install and configure :mod:`importlib`;
* Apply the :ref:`Path Configuration <init-path-config>`;
* Install signal handlers;
* Finish :mod:`sys` module initialization (ex: create :data:`sys.stdout`
and :data:`sys.path`);
* Enable optional features like :mod:`faulthandler` and :mod:`tracemalloc`;
* Import the :mod:`site` module;
* etc.

Private provisional API:

.. c:member:: int PyConfig._init_main

If set to ``0``, :c:func:`Py_InitializeFromConfig` stops at the "Core"
initialization phase.

.. c:function:: PyStatus _Py_InitializeMain(void)

Move to the "Main" initialization phase, finish the Python initialization.

No module is imported during the "Core" phase and the ``importlib`` module is
not configured: the :ref:`Path Configuration <init-path-config>` is only
applied during the "Main" phase. It may allow to customize Python in Python to
override or tune the :ref:`Path Configuration <init-path-config>`, maybe
install a custom :data:`sys.meta_path` importer or an import hook, etc.

It may become possible to calculate the :ref:`Path Configuration
<init-path-config>` in Python, after the Core phase and before the Main phase,
which is one of the :pep:`432` motivation.

The "Core" phase is not properly defined: what should be and what should
not be available at this phase is not specified yet. The API is marked
as private and provisional: the API can be modified or even be removed
anytime until a proper public API is designed.

Example running Python code between "Core" and "Main" initialization
phases::

void init_python(void)
{
PyStatus status;

PyConfig config;
PyConfig_InitPythonConfig(&config);
config._init_main = 0;

/* ... customize 'config' configuration ... */

status = Py_InitializeFromConfig(&config);
PyConfig_Clear(&config);
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}

/* Use sys.stderr because sys.stdout is only created
by _Py_InitializeMain() */
int res = PyRun_SimpleString(
"import sys; "
"print('Run Python code before _Py_InitializeMain', "
"file=sys.stderr)");
if (res < 0) {
exit(1);
}

/* ... put more configuration code here ... */

status = _Py_InitializeMain();
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}
}
4 changes: 4 additions & 0 deletionsDoc/whatsnew/3.15.rst
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1664,6 +1664,10 @@ New features
* Add:c:func:`PyUnstable_SetImmortal` C-API function to mark objects as:term:`immortal`.
(Contributed by Kumar Aditya in:gh:`143300`.)

* Restore private provisional ``_Py_InitializeMain()`` function removed in
Python 3.14.
(Contributed by Victor Stinner in:gh:`142417`.)

Changed C APIs
--------------

Expand Down
3 changes: 3 additions & 0 deletionsInclude/cpython/pylifecycle.h
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -25,6 +25,9 @@ PyAPI_FUNC(PyStatus) Py_PreInitializeFromArgs(
PyAPI_FUNC(PyStatus)Py_InitializeFromConfig(
constPyConfig*config);

// Python 3.8 provisional API (PEP 587)
PyAPI_FUNC(PyStatus)_Py_InitializeMain(void);

PyAPI_FUNC(int)Py_RunMain(void);


Expand Down
18 changes: 18 additions & 0 deletionsLib/test/test_embed.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1319,6 +1319,24 @@ def test_init_run_main(self):
}
self.check_all_configs("test_init_run_main", config, api=API_PYTHON)

def test_init_main(self):
code = ('import _testinternalcapi, json; '
'print(json.dumps(_testinternalcapi.get_configs()))')
config = {
'argv': ['-c', 'arg2'],
'orig_argv': ['python3',
'-c', code,
'arg2'],
'program_name': './python3',
'run_command': code + '\n',
'parse_argv': True,
'_init_main': False,
'sys_path_0': '',
}
self.check_all_configs("test_init_main", config,
api=API_PYTHON,
stderr="Run Python code before _Py_InitializeMain")

def test_init_parse_argv(self):
config = {
'parse_argv': True,
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
Restore private provisional ``_Py_InitializeMain()`` function removed in
Python 3.14. Patch by Victor Stinner.
28 changes: 28 additions & 0 deletionsPrograms/_testembed.c
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1991,6 +1991,33 @@ static int test_init_run_main(void)
}


static int test_init_main(void)
{
PyConfig config;
PyConfig_InitPythonConfig(&config);

configure_init_main(&config);
config._init_main = 0;
init_from_config_clear(&config);

/* sys.stdout don't exist yet: it is created by _Py_InitializeMain() */
int res = PyRun_SimpleString(
"import sys; "
"print('Run Python code before _Py_InitializeMain', "
"file=sys.stderr)");
if (res < 0) {
exit(1);
}

PyStatus status = _Py_InitializeMain();
if (PyStatus_Exception(status)) {
Py_ExitStatusException(status);
}

return Py_RunMain();
}


static int test_run_main(void)
{
PyConfig config;
Expand DownExpand Up@@ -2649,6 +2676,7 @@ static struct TestCase TestCases[] = {
{"test_preinit_parse_argv", test_preinit_parse_argv},
{"test_preinit_dont_parse_argv", test_preinit_dont_parse_argv},
{"test_init_run_main", test_init_run_main},
{"test_init_main", test_init_main},
{"test_init_sys_add", test_init_sys_add},
{"test_init_setpath", test_init_setpath},
{"test_init_setpath_config", test_init_setpath_config},
Expand Down
12 changes: 12 additions & 0 deletionsPython/pylifecycle.c
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1530,6 +1530,18 @@ Py_Initialize(void)
}


PyStatus
_Py_InitializeMain(void)
{
PyStatusstatus=_PyRuntime_Initialize();
if (_PyStatus_EXCEPTION(status)) {
returnstatus;
}
PyThreadState*tstate=_PyThreadState_GET();
returnpyinit_main(tstate);
}


staticvoid
finalize_modules_delete_special(PyThreadState*tstate,intverbose)
{
Expand Down
Loading

[8]ページ先頭

©2009-2026 Movatter.jp