We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Reconsidering distutils replacement strategy
I first expressed concerns about the fact that `distutils` needs to be imported *after* `setuptools` in [this post](https://github.com/pypa/setuptools/pull/2143#issuecomment-637586551), and I did not realize that we had not adequately addressed this before the `distutils` adoption. I think we should re-consider the way this is done, to avoid any sort of requirement on the sort order.

Currently, when you `import setuptools`, [`distutils` is injected into `sys.modules`](https://github.com/pypa/setuptools/blob/37d81f4ce8f08c4baf44b6ff0f3f1bd3f6b2a127/setuptools/distutils_patch.py#L48-L61).

The problem here is that it requires importing `setuptools` before `distutils`, which most people will *not* be doing right now (by almost all common import sort orders, `distutils` comes first).

@jaraco [explains why it's done this way here](https://github.com/pypa/setuptools/issues/2230#issuecomment-657327796):

> I did consider another approach, where Setuptools could add a .pth file that would import setuptools.distutils_patch. Such an approach would always happen earlier and so would not be subject to the race that's happening here, but it would also happen whether or not setuptools was imported (on any invocation of Python in that environment).

I think one preferred solution would be for us to install a `distutils` package that would be imported before `distutils`. The problem is that in the standard `sys.path`, `site-packages` comes *after* the standard library. Since anything we do here will be a tremendous hack, I'm thinking that maybe the most surgical way to accomplish this is to do something like this:

1. Create a `setuptools._distutils/import_hack/distutils/__init__.py` (where there's no `__init__.py` in `import_hack`) that invokes `import setuptools.distutils_patch`.
2. Add a `.pth` file that injects `$SITEPACKAGES/setuptools/_import_hack/` into `sys.path` *before* the standard library.

Another option I think we should consider is stepping up the timetable on providing everything `distutils` provides directly from the `setuptools` namespace, [as I described here](https://github.com/pypa/setuptools/pull/2143#issuecomment-637586551):

> I personally would prefer it if we made the setuptools namespace the canonical namespace, and have distutils just import symbols from setuptools and possibly wrap them in deprecation warnings.

Right now, there are things that you *must* import from `distutils`, and so we can't say, "You can avoid an issue with the sort order by just not importing `distutils`". If we provide everything that `distutils` provides in the `setuptools` namespace, we can just say, "Just use the `setuptools` version and you won't have this problem."

Personally, I think we should do a combination of both — make it so importing `distutils` still works in whatever order you do it in *and* move everything to the canonical `setuptools` namespace. That will make it easier to actively deprecate direct use of `distutils`, and pave the way for us eventually removing the need for the `.pth` file (though the fastest road to not having the `.pth` file will be via removing `distutils` from the standard library).

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `_distutils_hack/__init__.py`
Content:
```
1 import sys
2 import os
3 import re
4 import importlib
5 import warnings
6 
7 
8 is_pypy = '__pypy__' in sys.builtin_module_names
9 
10 
11 def warn_distutils_present():
12     if 'distutils' not in sys.modules:
13         return
14     if is_pypy and sys.version_info < (3, 7):
15         # PyPy for 3.6 unconditionally imports distutils, so bypass the warning
16         # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
17         return
18     warnings.warn(
19         "Distutils was imported before Setuptools. This usage is discouraged "
20         "and may exhibit undesirable behaviors or errors. Please use "
21         "Setuptools' objects directly or at least import Setuptools first.")
22 
23 
24 def clear_distutils():
25     if 'distutils' not in sys.modules:
26         return
27     warnings.warn("Setuptools is replacing distutils.")
28     mods = [name for name in sys.modules if re.match(r'distutils\b', name)]
29     for name in mods:
30         del sys.modules[name]
31 
32 
33 def enabled():
34     """
35     Allow selection of distutils by environment variable.
36     """
37     which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib')
38     return which == 'local'
39 
40 
41 def ensure_local_distutils():
42     clear_distutils()
43     distutils = importlib.import_module('setuptools._distutils')
44     distutils.__name__ = 'distutils'
45     sys.modules['distutils'] = distutils
46 
47     # sanity check that submodules load as expected
48     core = importlib.import_module('distutils.core')
49     assert '_distutils' in core.__file__, core.__file__
50 
51 
52 def do_override():
53     """
54     Ensure that the local copy of distutils is preferred over stdlib.
55 
56     See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
57     for more motivation.
58     """
59     warn_distutils_present()
60     if enabled():
61         ensure_local_distutils()
62 
63 
64 class DistutilsMetaFinder:
65     def find_spec(self, fullname, path, target=None):
66         if path is not None or fullname != "distutils":
67             return None
68 
69         return self.get_distutils_spec()
70 
71     def get_distutils_spec(self):
72         import importlib.util
73 
74         class DistutilsLoader(importlib.util.abc.Loader):
75 
76             def create_module(self, spec):
77                 return importlib.import_module('._distutils', 'setuptools')
78 
79             def exec_module(self, module):
80                 pass
81 
82         return importlib.util.spec_from_loader('distutils', DistutilsLoader())
83 
84 
85 DISTUTILS_FINDER = DistutilsMetaFinder()
86 
87 
88 def add_shim():
89     sys.meta_path.insert(0, DISTUTILS_FINDER)
90 
91 
92 def remove_shim():
93     try:
94         sys.meta_path.remove(DISTUTILS_FINDER)
95     except ValueError:
96         pass
97
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/_distutils_hack/__init__.py b/_distutils_hack/__init__.py
--- a/_distutils_hack/__init__.py
+++ b/_distutils_hack/__init__.py
@@ -16,9 +16,12 @@
         # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
         return
     warnings.warn(
-        "Distutils was imported before Setuptools. This usage is discouraged "
-        "and may exhibit undesirable behaviors or errors. Please use "
-        "Setuptools' objects directly or at least import Setuptools first.")
+        "Distutils was imported before Setuptools, but importing Setuptools "
+        "also replaces the `distutils` module in `sys.modules`. This may lead "
+        "to undesirable behaviors or errors. To avoid these issues, avoid "
+        "using distutils directly, ensure that setuptools is installed in the "
+        "traditional way (e.g. not an editable install), and/or make sure that "
+        "setuptools is always imported before distutils.")
 
 
 def clear_distutils():
@@ -56,8 +59,8 @@
     See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
     for more motivation.
     """
-    warn_distutils_present()
     if enabled():
+        warn_distutils_present()
         ensure_local_distutils()

{"golden_diff": "diff --git a/_distutils_hack/__init__.py b/_distutils_hack/__init__.py\n--- a/_distutils_hack/__init__.py\n+++ b/_distutils_hack/__init__.py\n@@ -16,9 +16,12 @@\n         # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250\n         return\n     warnings.warn(\n-        \"Distutils was imported before Setuptools. This usage is discouraged \"\n-        \"and may exhibit undesirable behaviors or errors. Please use \"\n-        \"Setuptools' objects directly or at least import Setuptools first.\")\n+        \"Distutils was imported before Setuptools, but importing Setuptools \"\n+        \"also replaces the `distutils` module in `sys.modules`. This may lead \"\n+        \"to undesirable behaviors or errors. To avoid these issues, avoid \"\n+        \"using distutils directly, ensure that setuptools is installed in the \"\n+        \"traditional way (e.g. not an editable install), and/or make sure that \"\n+        \"setuptools is always imported before distutils.\")\n \n \n def clear_distutils():\n@@ -56,8 +59,8 @@\n     See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401\n     for more motivation.\n     \"\"\"\n-    warn_distutils_present()\n     if enabled():\n+        warn_distutils_present()\n         ensure_local_distutils()\n", "issue": "Reconsidering distutils replacement strategy\nI first expressed concerns about the fact that `distutils` needs to be imported *after* `setuptools` in [this post](https://github.com/pypa/setuptools/pull/2143#issuecomment-637586551), and I did not realize that we had not adequately addressed this before the `distutils` adoption. I think we should re-consider the way this is done, to avoid any sort of requirement on the sort order.\r\n\r\nCurrently, when you `import setuptools`, [`distutils` is injected into `sys.modules`](https://github.com/pypa/setuptools/blob/37d81f4ce8f08c4baf44b6ff0f3f1bd3f6b2a127/setuptools/distutils_patch.py#L48-L61).\r\n\r\nThe problem here is that it requires importing `setuptools` before `distutils`, which most people will *not* be doing right now (by almost all common import sort orders, `distutils` comes first).\r\n\r\n@jaraco [explains why it's done this way here](https://github.com/pypa/setuptools/issues/2230#issuecomment-657327796):\r\n\r\n> I did consider another approach, where Setuptools could add a .pth file that would import setuptools.distutils_patch. Such an approach would always happen earlier and so would not be subject to the race that's happening here, but it would also happen whether or not setuptools was imported (on any invocation of Python in that environment).\r\n\r\nI think one preferred solution would be for us to install a `distutils` package that would be imported before `distutils`. The problem is that in the standard `sys.path`, `site-packages` comes *after* the standard library. Since anything we do here will be a tremendous hack, I'm thinking that maybe the most surgical way to accomplish this is to do something like this:\r\n\r\n1. Create a `setuptools._distutils/import_hack/distutils/__init__.py` (where there's no `__init__.py` in `import_hack`) that invokes `import setuptools.distutils_patch`.\r\n2. Add a `.pth` file that injects `$SITEPACKAGES/setuptools/_import_hack/` into `sys.path` *before* the standard library.\r\n\r\nAnother option I think we should consider is stepping up the timetable on providing everything `distutils` provides directly from the `setuptools` namespace, [as I described here](https://github.com/pypa/setuptools/pull/2143#issuecomment-637586551):\r\n\r\n> I personally would prefer it if we made the setuptools namespace the canonical namespace, and have distutils just import symbols from setuptools and possibly wrap them in deprecation warnings.\r\n\r\nRight now, there are things that you *must* import from `distutils`, and so we can't say, \"You can avoid an issue with the sort order by just not importing `distutils`\". If we provide everything that `distutils` provides in the `setuptools` namespace, we can just say, \"Just use the `setuptools` version and you won't have this problem.\"\r\n\r\nPersonally, I think we should do a combination of both \u2014 make it so importing `distutils` still works in whatever order you do it in *and* move everything to the canonical `setuptools` namespace. That will make it easier to actively deprecate direct use of `distutils`, and pave the way for us eventually removing the need for the `.pth` file (though the fastest road to not having the `.pth` file will be via removing `distutils` from the standard library).\n", "before_files": [{"content": "import sys\nimport os\nimport re\nimport importlib\nimport warnings\n\n\nis_pypy = '__pypy__' in sys.builtin_module_names\n\n\ndef warn_distutils_present():\n    if 'distutils' not in sys.modules:\n        return\n    if is_pypy and sys.version_info < (3, 7):\n        # PyPy for 3.6 unconditionally imports distutils, so bypass the warning\n        # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250\n        return\n    warnings.warn(\n        \"Distutils was imported before Setuptools. This usage is discouraged \"\n        \"and may exhibit undesirable behaviors or errors. Please use \"\n        \"Setuptools' objects directly or at least import Setuptools first.\")\n\n\ndef clear_distutils():\n    if 'distutils' not in sys.modules:\n        return\n    warnings.warn(\"Setuptools is replacing distutils.\")\n    mods = [name for name in sys.modules if re.match(r'distutils\\b', name)]\n    for name in mods:\n        del sys.modules[name]\n\n\ndef enabled():\n    \"\"\"\n    Allow selection of distutils by environment variable.\n    \"\"\"\n    which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib')\n    return which == 'local'\n\n\ndef ensure_local_distutils():\n    clear_distutils()\n    distutils = importlib.import_module('setuptools._distutils')\n    distutils.__name__ = 'distutils'\n    sys.modules['distutils'] = distutils\n\n    # sanity check that submodules load as expected\n    core = importlib.import_module('distutils.core')\n    assert '_distutils' in core.__file__, core.__file__\n\n\ndef do_override():\n    \"\"\"\n    Ensure that the local copy of distutils is preferred over stdlib.\n\n    See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401\n    for more motivation.\n    \"\"\"\n    warn_distutils_present()\n    if enabled():\n        ensure_local_distutils()\n\n\nclass DistutilsMetaFinder:\n    def find_spec(self, fullname, path, target=None):\n        if path is not None or fullname != \"distutils\":\n            return None\n\n        return self.get_distutils_spec()\n\n    def get_distutils_spec(self):\n        import importlib.util\n\n        class DistutilsLoader(importlib.util.abc.Loader):\n\n            def create_module(self, spec):\n                return importlib.import_module('._distutils', 'setuptools')\n\n            def exec_module(self, module):\n                pass\n\n        return importlib.util.spec_from_loader('distutils', DistutilsLoader())\n\n\nDISTUTILS_FINDER = DistutilsMetaFinder()\n\n\ndef add_shim():\n    sys.meta_path.insert(0, DISTUTILS_FINDER)\n\n\ndef remove_shim():\n    try:\n        sys.meta_path.remove(DISTUTILS_FINDER)\n    except ValueError:\n        pass\n", "path": "_distutils_hack/__init__.py"}], "after_files": [{"content": "import sys\nimport os\nimport re\nimport importlib\nimport warnings\n\n\nis_pypy = '__pypy__' in sys.builtin_module_names\n\n\ndef warn_distutils_present():\n    if 'distutils' not in sys.modules:\n        return\n    if is_pypy and sys.version_info < (3, 7):\n        # PyPy for 3.6 unconditionally imports distutils, so bypass the warning\n        # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250\n        return\n    warnings.warn(\n        \"Distutils was imported before Setuptools, but importing Setuptools \"\n        \"also replaces the `distutils` module in `sys.modules`. This may lead \"\n        \"to undesirable behaviors or errors. To avoid these issues, avoid \"\n        \"using distutils directly, ensure that setuptools is installed in the \"\n        \"traditional way (e.g. not an editable install), and/or make sure that \"\n        \"setuptools is always imported before distutils.\")\n\n\ndef clear_distutils():\n    if 'distutils' not in sys.modules:\n        return\n    warnings.warn(\"Setuptools is replacing distutils.\")\n    mods = [name for name in sys.modules if re.match(r'distutils\\b', name)]\n    for name in mods:\n        del sys.modules[name]\n\n\ndef enabled():\n    \"\"\"\n    Allow selection of distutils by environment variable.\n    \"\"\"\n    which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'stdlib')\n    return which == 'local'\n\n\ndef ensure_local_distutils():\n    clear_distutils()\n    distutils = importlib.import_module('setuptools._distutils')\n    distutils.__name__ = 'distutils'\n    sys.modules['distutils'] = distutils\n\n    # sanity check that submodules load as expected\n    core = importlib.import_module('distutils.core')\n    assert '_distutils' in core.__file__, core.__file__\n\n\ndef do_override():\n    \"\"\"\n    Ensure that the local copy of distutils is preferred over stdlib.\n\n    See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401\n    for more motivation.\n    \"\"\"\n    if enabled():\n        warn_distutils_present()\n        ensure_local_distutils()\n\n\nclass DistutilsMetaFinder:\n    def find_spec(self, fullname, path, target=None):\n        if path is not None or fullname != \"distutils\":\n            return None\n\n        return self.get_distutils_spec()\n\n    def get_distutils_spec(self):\n        import importlib.util\n\n        class DistutilsLoader(importlib.util.abc.Loader):\n\n            def create_module(self, spec):\n                return importlib.import_module('._distutils', 'setuptools')\n\n            def exec_module(self, module):\n                pass\n\n        return importlib.util.spec_from_loader('distutils', DistutilsLoader())\n\n\nDISTUTILS_FINDER = DistutilsMetaFinder()\n\n\ndef add_shim():\n    sys.meta_path.insert(0, DISTUTILS_FINDER)\n\n\ndef remove_shim():\n    try:\n        sys.meta_path.remove(DISTUTILS_FINDER)\n    except ValueError:\n        pass\n", "path": "_distutils_hack/__init__.py"}]}