python / python/cpython

Circular import error for `threading` when using `importlib.util.LazyLoader` with a custom finder

Đang mở
#127,116 0 bình luận 1 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

topic-importlib type-bug
Ngôn ngữ chính
Python
Star
77.2k
Fork
35.9k
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

Bug report

Bug description:

When using a custom finder (on sys.meta_path) that wraps a module spec's loader with importlib.util.LazyLoader, the threading import within importlib.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
import importlib.util
import sys

class LazyFinder:
    """A module spec finder that wraps a spec's loader, if it exists, with LazyLoader."""

    @classmethod
    def find_spec(cls, fullname: str, path=None, target=None, /):
        for finder in sys.meta_path:
            if finder is not cls:
                spec = finder.find_spec(fullname, path, target)
                if spec is not None:
                    break
        else:
            raise ModuleNotFoundError(...)

        if spec.loader is not None:
            spec.loader = importlib.util.LazyLoader(spec.loader)

        return spec


class LazyFinderContext:
    """Temporarily "lazify" some types of import statements in the runtime context."""
    
    def __enter__(self):
        if LazyFinder not in sys.meta_path:
            sys.meta_path.insert(0, LazyFinder)

    def __exit__(self, *exc_info):
        try:
            sys.meta_path.remove(LazyFinder)
        except ValueError:
            pass

with LazyFinderContext():
    import inspect
Expected Output

No error.

Actual Output
> python scratch.py
Traceback (most recent call last):
  File "/home/thanos/projects/personal/pycc/scratch.py", line 40, in <module>
    import inspect
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib.util>", line 257, in exec_module
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib.util>", line 267, in exec_module
AttributeError: partially initialized module 'threading' has no attribute 'RLock' (most likely due to a circular import)
Commentary

This is technically caused by this code:
https://github.com/python/cpython/blob/9dabace39d118ec7a204b6970f8a3f475a11522c/Lib/importlib/util.py#L256-L260

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. https://github.com/scientific-python/lazy-loader/pull/121#issuecomment-2457961532, 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 using LazyLoader easier with the finder-related import hooks if that wasn't necessary.

Based on the commit history, a top-level import for threading breaks gevent, so I'd rather not repeat that. I'm not very familiar with gevent, but if using _thread.RLock is fine in importlib._bootstrap for the module locks, then maybe that could be used in importlib.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

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu bằng cách chạy trình tái hiện được cung cấp với finder tùy chỉnh và kiểm tra Lib/importlib/util.py, đặc biệt là LazyLoader.exec_module và các dòng được liên kết xung quanh 256-260. So sánh hành vi trên Python 3.12 và 3.13; được xem là hoàn tất khi trình tái hiện import inspect mà không gặp AttributeError do import vòng, đồng thời vẫn giữ nguyên các ràng buộc khởi động đã nêu.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
backend, tooling
Loại issue
Lỗi
Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
35/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.