You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[mypyc] Set dunder attrs when adding module to sys.modules (python#21275)
Recently there was a change to add native modules to `sys.modules`
before they are executed to be able to detect circular imports. This
introduced a regression when the module is a package that imports
objects from other files within the package, eg. `from pkg.file import
something` inside `pkg/__init__.py`. Such imports result in an exception
`ModuleNotFoundError: No module named 'pkg.file'; 'pkg' is not a
package.`, for example when trying to upgrade mypy in
[black](https://github.com/psf/black/actions/runs/23933086642/job/69803937853?pr=5071).
This error is raised because Python expects the parent module of `file`
to have the `__path__` attribute set when [resolving the
import](https://github.com/python/cpython/blob/main/Lib/importlib/_bootstrap.py#L1226)
but we don't set this attribute before adding the `pkg` module to
`sys.modules`.
So use existing functions to set relevant dunder attributes (`__path__`
for packages and `__file__`, `__spec__`, and `__package__` for all)
before registering the module in `sys.modules`.
Don't skip compilation for `__init__.py` files in separate compilation
mode to make this possible to test.
Use `Py_CLEAR` instead of `Py_DECREF` on the import object on failure in
`CPyImport_ImportNative` as the import object might be freed when
deleting it from `sys.modules`. This triggered an assertion when running
tests with a debug build of cpython.
0 commit comments