Support PYTHON_LAZY_IMPORTS=all (Python 3.15)

Merged
MB
2d ago
+141-7

Summary

After migrating my Django project to Python 3.15 I opted to run it with PYTHON_LAZY_IMPORTS=all, turning lazy imports globally for all dependencies. Everything worked fine out of the box except httpx, httpx2 and truststore (which is fixed in git master).

Easy way to reproduce:

$ PYTHON_LAZY_IMPORTS=all python -c 'import httpcore2 ; dir(httpcore2)'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import httpcore2 ; dir(httpcore2)
ImportError: lazy import of 'httpcore2' raised an exception during resolution

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
    import httpcore2 ; dir(httpcore2)
                           ^^^^^^^^^
  File "/home/ja/httpx2/src/httpcore2/httpcore2/__init__.py", line 141, in <module>
    setattr(__locals[__name], "__module__", "httpcore2")  # noqa
    ~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'lazy_import' object has no attribute '__module__' and no __dict__ for setting new attributes. Did you mean '.__reduce__' instead of '.__module__'?

The proposed solution here is unglamorous, but 1:1 compatible with the existing httpcore behavior. Alternative options:

  1. do isinstance checks for types.LazyImportType and don't overwrite __module__ if true
  2. remove __module__ overwrites completely, as they are purely for aesthetic purposes, if I understand this code correctly (eg. it provides nicer looking type names in tracebacks)

Checklist

  • I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
  • I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
  • I've updated the documentation accordingly.