diff --git a/Lib/importlib/__init__.py b/Lib/importlib/__init__.py index a7d57561ead..760548ab942 100644 --- a/Lib/importlib/__init__.py +++ b/Lib/importlib/__init__.py @@ -59,6 +59,8 @@ from ._bootstrap import __import__ +from _imp import lazy_import + def invalidate_caches(): """Call the invalidate_caches() method on all meta path finders stored in diff --git a/Objects/lazyimportobject.c b/Objects/lazyimportobject.c index 973056d5ced..6754b238f52 100644 --- a/Objects/lazyimportobject.c +++ b/Objects/lazyimportobject.c @@ -1,6 +1,3 @@ -/* Copyright (c) Meta, Inc. and its affiliates. All Rights Reserved */ -/* File added for Lazy Imports */ - /* Lazy object implementation */ #include "Python.h" @@ -86,6 +83,24 @@ lazy_import_clear(PyLazyImportObject *m) return 0; } +static PyObject * +lazy_import_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + if (PyTuple_GET_SIZE(args) != 2 && PyTuple_GET_SIZE(args) != 3) { + PyErr_SetString(PyExc_ValueError, "lazy_import expected 2-3 arguments"); + return NULL; + } + + PyObject *builtins = PyTuple_GET_ITEM(args, 0); + PyObject *from = PyTuple_GET_ITEM(args, 1); + PyObject *attr = NULL; + if (PyTuple_GET_SIZE(args) == 3) { + attr = PyTuple_GET_ITEM(args, 2); + } + + return _PyLazyImport_New(builtins, from, attr); +} + PyObject * _PyLazyImport_GetName(PyObject *lazy_import) { @@ -132,6 +147,6 @@ PyTypeObject PyLazyImport_Type = { 0, /* tp_dictoffset */ 0, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ - PyType_GenericNew, /* tp_new */ + lazy_import_new, /* tp_new */ PyObject_GC_Del, /* tp_free */ }; diff --git a/Python/import.c b/Python/import.c index 52e428794e6..7a9ae1ef962 100644 --- a/Python/import.c +++ b/Python/import.c @@ -4980,6 +4980,11 @@ imp_module_exec(PyObject *module) return -1; } + if (PyModule_AddObjectRef(module, "lazy_import", + (PyObject *)&PyLazyImport_Type) < 0) { + return -1; + } + return 0; }