Circular import error for threading
when using importlib.util.LazyLoader
with a custom finder
#127116
Labels
threading
when using importlib.util.LazyLoader
with a custom finder
#127116
Bug report
Bug description:
When using a custom finder (on
sys.meta_path
) that wraps a module spec's loader withimportlib.util.LazyLoader
, the threading import withinimportlib.util.LazyLoader.exec_module
is attempted with the custom finder, causing a circular import error.Not sure if this is more of a feature request than a bug report, but the behavior was certainly surprising at first glance. Hopefully there's a way to better support this use case from within the stdlib without too much burden. Otherwise, users of LazyLoader in this manner would be forced to either a) maintain an exclusion list of modules that their finder ignores, potentially including all of threading's dependencies or b) always import threading before using such finders, which shouldn't be necessary, especially if threading isn't directly used by the user code.
Reproducer
Expected Output
No error.
Actual Output
Commentary
This is technically caused by this code:
cpython/Lib/importlib/util.py
Lines 256 to 260 in 9dabace
However, it is based on the fair assumptions that
LazyLoader
a) isn't critical to CPython startup, and b) won't be used in a circular fashion with a custom finder. However, there are use cases for such a finder (e.g. scientific-python/lazy-loader#121 (comment), one place this issue was discovered). While finders utilizing the lazy loader could work around this with an exclusion list of modules (e.g. mercurial's lazy loader does), I think users would find usingLazyLoader
easier with the finder-related import hooks if that wasn't necessary.Based on the commit history, a top-level import for
threading
breaksgevent
, so I'd rather not repeat that. I'm not very familiar withgevent
, but if using_thread.RLock
is fine inimportlib._bootstrap
for the module locks, then maybe that could be used inimportlib.util
as well?EDIT: Updated code snippet to be consistent with output; accidentally used a different import while testing. Still, same result.
CPython versions tested on:
3.12, 3.13
Operating systems tested on:
Linux, Windows
The text was updated successfully, but these errors were encountered: