We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[BUG] Issue with local distutils override, duplicate module entries
### setuptools version

60.5.0

### Python version

3.9.9

### OS

macOS

### Additional environment information

edit(jaraco): ~~I explicitly state that I DO NOT AGREE with being forced to agree with the PSF Code of Conduct to submit this issue. I ticked the box just because I cannot continue otherwise. I hope this requirement for issue submission is an oversight. If not, please close this issue and ignore my report.~~

### Description

There are issues with the local `distutils` override leading to duplicated `distutils.log` module entries in `sys.modules`. As a side effect, the verbose flag (`-v`) to `setup.py` does not work (i.e passing `-v` DOES NOT increase verbosity).

### Expected behavior

1. After `import setuptools`, there should be no entries in `sys.modules` referring to `setuptools._distutils`.
2. Running `python setup.py -vv <command>` should increase verbosity.

### How to Reproduce

Run the following Python code:

```python
import setuptools
import sys
for k in sys.modules.keys():
    if 'distutils.log' in k:
        print(k)
```

### Output

```console
setuptools._distutils.log
distutils.log
```

Obviously, the first entry is bogus and should not be printed.

Adding `print(log)` after the `from distutils import log` import statement in `setuptools/_distutils/dist.py` will help with debugging the problem. You should get the bogus `setuptools._distutils.log` module.

I believe this module duplication issue happens with other distutils submodules, you can check with:

```python
import setuptools
import sys
for k in sys.modules.keys():
    if '_distutils' in k:
        print(k)
```

which produces

```console
_distutils_hack
setuptools._distutils
setuptools._distutils.log
setuptools._distutils.dir_util
setuptools._distutils.file_util
setuptools._distutils.archive_util
_distutils_hack.override
```

### Code of Conduct

- [X] I agree to follow the PSF Code of Conduct

--- 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 # don't import any costly modules
2 import sys
3 import os
4 
5 
6 is_pypy = '__pypy__' in sys.builtin_module_names
7 
8 
9 def warn_distutils_present():
10     if 'distutils' not in sys.modules:
11         return
12     if is_pypy and sys.version_info < (3, 7):
13         # PyPy for 3.6 unconditionally imports distutils, so bypass the warning
14         # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
15         return
16     import warnings
17     warnings.warn(
18         "Distutils was imported before Setuptools, but importing Setuptools "
19         "also replaces the `distutils` module in `sys.modules`. This may lead "
20         "to undesirable behaviors or errors. To avoid these issues, avoid "
21         "using distutils directly, ensure that setuptools is installed in the "
22         "traditional way (e.g. not an editable install), and/or make sure "
23         "that setuptools is always imported before distutils.")
24 
25 
26 def clear_distutils():
27     if 'distutils' not in sys.modules:
28         return
29     import warnings
30     warnings.warn("Setuptools is replacing distutils.")
31     mods = [
32         name for name in sys.modules
33         if name == "distutils" or name.startswith("distutils.")
34     ]
35     for name in mods:
36         del sys.modules[name]
37 
38 
39 def enabled():
40     """
41     Allow selection of distutils by environment variable.
42     """
43     which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
44     return which == 'local'
45 
46 
47 def ensure_local_distutils():
48     import importlib
49     clear_distutils()
50 
51     # With the DistutilsMetaFinder in place,
52     # perform an import to cause distutils to be
53     # loaded from setuptools._distutils. Ref #2906.
54     with shim():
55         importlib.import_module('distutils')
56 
57     # check that submodules load as expected
58     core = importlib.import_module('distutils.core')
59     assert '_distutils' in core.__file__, core.__file__
60 
61 
62 def do_override():
63     """
64     Ensure that the local copy of distutils is preferred over stdlib.
65 
66     See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
67     for more motivation.
68     """
69     if enabled():
70         warn_distutils_present()
71         ensure_local_distutils()
72 
73 
74 class _TrivialRe:
75     def __init__(self, *patterns):
76         self._patterns = patterns
77 
78     def match(self, string):
79         return all(pat in string for pat in self._patterns)
80 
81 
82 class DistutilsMetaFinder:
83     def find_spec(self, fullname, path, target=None):
84         if path is not None:
85             return
86 
87         method_name = 'spec_for_{fullname}'.format(**locals())
88         method = getattr(self, method_name, lambda: None)
89         return method()
90 
91     def spec_for_distutils(self):
92         if self.is_cpython():
93             return
94 
95         import importlib
96         import importlib.abc
97         import importlib.util
98 
99         try:
100             mod = importlib.import_module('setuptools._distutils')
101         except Exception:
102             # There are a couple of cases where setuptools._distutils
103             # may not be present:
104             # - An older Setuptools without a local distutils is
105             #   taking precedence. Ref #2957.
106             # - Path manipulation during sitecustomize removes
107             #   setuptools from the path but only after the hook
108             #   has been loaded. Ref #2980.
109             # In either case, fall back to stdlib behavior.
110             return
111 
112         class DistutilsLoader(importlib.abc.Loader):
113 
114             def create_module(self, spec):
115                 return mod
116 
117             def exec_module(self, module):
118                 pass
119 
120         return importlib.util.spec_from_loader(
121             'distutils', DistutilsLoader(), origin=mod.__file__
122         )
123 
124     @staticmethod
125     def is_cpython():
126         """
127         Suppress supplying distutils for CPython (build and tests).
128         Ref #2965 and #3007.
129         """
130         return os.path.isfile('pybuilddir.txt')
131 
132     def spec_for_pip(self):
133         """
134         Ensure stdlib distutils when running under pip.
135         See pypa/pip#8761 for rationale.
136         """
137         if self.pip_imported_during_build():
138             return
139         clear_distutils()
140         self.spec_for_distutils = lambda: None
141 
142     @classmethod
143     def pip_imported_during_build(cls):
144         """
145         Detect if pip is being imported in a build script. Ref #2355.
146         """
147         import traceback
148         return any(
149             cls.frame_file_is_setup(frame)
150             for frame, line in traceback.walk_stack(None)
151         )
152 
153     @staticmethod
154     def frame_file_is_setup(frame):
155         """
156         Return True if the indicated frame suggests a setup.py file.
157         """
158         # some frames may not have __file__ (#2940)
159         return frame.f_globals.get('__file__', '').endswith('setup.py')
160 
161 
162 DISTUTILS_FINDER = DistutilsMetaFinder()
163 
164 
165 def add_shim():
166     DISTUTILS_FINDER in sys.meta_path or insert_shim()
167 
168 
169 class shim:
170     def __enter__(self):
171         insert_shim()
172 
173     def __exit__(self, exc, value, tb):
174         remove_shim()
175 
176 
177 def insert_shim():
178     sys.meta_path.insert(0, DISTUTILS_FINDER)
179 
180 
181 def remove_shim():
182     try:
183         sys.meta_path.remove(DISTUTILS_FINDER)
184     except ValueError:
185         pass
186
```
--- 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
@@ -57,6 +57,7 @@
     # check that submodules load as expected
     core = importlib.import_module('distutils.core')
     assert '_distutils' in core.__file__, core.__file__
+    assert 'setuptools._distutils.log' not in sys.modules
 
 
 def do_override():
@@ -112,6 +113,7 @@
         class DistutilsLoader(importlib.abc.Loader):
 
             def create_module(self, spec):
+                mod.__name__ = 'distutils'
                 return mod
 
             def exec_module(self, module):

{"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@@ -57,6 +57,7 @@\n     # check that submodules load as expected\n     core = importlib.import_module('distutils.core')\n     assert '_distutils' in core.__file__, core.__file__\n+    assert 'setuptools._distutils.log' not in sys.modules\n \n \n def do_override():\n@@ -112,6 +113,7 @@\n         class DistutilsLoader(importlib.abc.Loader):\n \n             def create_module(self, spec):\n+                mod.__name__ = 'distutils'\n                 return mod\n \n             def exec_module(self, module):\n", "issue": "[BUG] Issue with local distutils override, duplicate module entries\n### setuptools version\r\n\r\n60.5.0\r\n\r\n### Python version\r\n\r\n3.9.9\r\n\r\n### OS\r\n\r\nmacOS\r\n\r\n### Additional environment information\r\n\r\nedit(jaraco): ~~I explicitly state that I DO NOT AGREE with being forced to agree with the PSF Code of Conduct to submit this issue. I ticked the box just because I cannot continue otherwise. I hope this requirement for issue submission is an oversight. If not, please close this issue and ignore my report.~~\r\n\r\n### Description\r\n\r\nThere are issues with the local `distutils` override leading to duplicated `distutils.log` module entries in `sys.modules`. As a side effect, the verbose flag (`-v`) to `setup.py` does not work (i.e passing `-v` DOES NOT increase verbosity).\r\n\r\n### Expected behavior\r\n\r\n1. After `import setuptools`, there should be no entries in `sys.modules` referring to `setuptools._distutils`.\r\n2. Running `python setup.py -vv <command>` should increase verbosity.\r\n\r\n### How to Reproduce\r\n\r\nRun the following Python code:\r\n\r\n```python\r\nimport setuptools\r\nimport sys\r\nfor k in sys.modules.keys():\r\n    if 'distutils.log' in k:\r\n        print(k)\r\n```\r\n\r\n### Output\r\n\r\n```console\r\nsetuptools._distutils.log\r\ndistutils.log\r\n```\r\n\r\nObviously, the first entry is bogus and should not be printed.\r\n\r\nAdding `print(log)` after the `from distutils import log` import statement in `setuptools/_distutils/dist.py` will help with debugging the problem. You should get the bogus `setuptools._distutils.log` module.\r\n\r\nI believe this module duplication issue happens with other distutils submodules, you can check with:\r\n\r\n```python\r\nimport setuptools\r\nimport sys\r\nfor k in sys.modules.keys():\r\n    if '_distutils' in k:\r\n        print(k)\r\n```\r\n\r\nwhich produces\r\n\r\n```console\r\n_distutils_hack\r\nsetuptools._distutils\r\nsetuptools._distutils.log\r\nsetuptools._distutils.dir_util\r\nsetuptools._distutils.file_util\r\nsetuptools._distutils.archive_util\r\n_distutils_hack.override\r\n```\r\n\r\n### Code of Conduct\r\n\r\n- [X] I agree to follow the PSF Code of Conduct\n", "before_files": [{"content": "# don't import any costly modules\nimport sys\nimport os\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    import warnings\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 \"\n        \"that setuptools is always imported before distutils.\")\n\n\ndef clear_distutils():\n    if 'distutils' not in sys.modules:\n        return\n    import warnings\n    warnings.warn(\"Setuptools is replacing distutils.\")\n    mods = [\n        name for name in sys.modules\n        if name == \"distutils\" or name.startswith(\"distutils.\")\n    ]\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', 'local')\n    return which == 'local'\n\n\ndef ensure_local_distutils():\n    import importlib\n    clear_distutils()\n\n    # With the DistutilsMetaFinder in place,\n    # perform an import to cause distutils to be\n    # loaded from setuptools._distutils. Ref #2906.\n    with shim():\n        importlib.import_module('distutils')\n\n    # 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 _TrivialRe:\n    def __init__(self, *patterns):\n        self._patterns = patterns\n\n    def match(self, string):\n        return all(pat in string for pat in self._patterns)\n\n\nclass DistutilsMetaFinder:\n    def find_spec(self, fullname, path, target=None):\n        if path is not None:\n            return\n\n        method_name = 'spec_for_{fullname}'.format(**locals())\n        method = getattr(self, method_name, lambda: None)\n        return method()\n\n    def spec_for_distutils(self):\n        if self.is_cpython():\n            return\n\n        import importlib\n        import importlib.abc\n        import importlib.util\n\n        try:\n            mod = importlib.import_module('setuptools._distutils')\n        except Exception:\n            # There are a couple of cases where setuptools._distutils\n            # may not be present:\n            # - An older Setuptools without a local distutils is\n            #   taking precedence. Ref #2957.\n            # - Path manipulation during sitecustomize removes\n            #   setuptools from the path but only after the hook\n            #   has been loaded. Ref #2980.\n            # In either case, fall back to stdlib behavior.\n            return\n\n        class DistutilsLoader(importlib.abc.Loader):\n\n            def create_module(self, spec):\n                return mod\n\n            def exec_module(self, module):\n                pass\n\n        return importlib.util.spec_from_loader(\n            'distutils', DistutilsLoader(), origin=mod.__file__\n        )\n\n    @staticmethod\n    def is_cpython():\n        \"\"\"\n        Suppress supplying distutils for CPython (build and tests).\n        Ref #2965 and #3007.\n        \"\"\"\n        return os.path.isfile('pybuilddir.txt')\n\n    def spec_for_pip(self):\n        \"\"\"\n        Ensure stdlib distutils when running under pip.\n        See pypa/pip#8761 for rationale.\n        \"\"\"\n        if self.pip_imported_during_build():\n            return\n        clear_distutils()\n        self.spec_for_distutils = lambda: None\n\n    @classmethod\n    def pip_imported_during_build(cls):\n        \"\"\"\n        Detect if pip is being imported in a build script. Ref #2355.\n        \"\"\"\n        import traceback\n        return any(\n            cls.frame_file_is_setup(frame)\n            for frame, line in traceback.walk_stack(None)\n        )\n\n    @staticmethod\n    def frame_file_is_setup(frame):\n        \"\"\"\n        Return True if the indicated frame suggests a setup.py file.\n        \"\"\"\n        # some frames may not have __file__ (#2940)\n        return frame.f_globals.get('__file__', '').endswith('setup.py')\n\n\nDISTUTILS_FINDER = DistutilsMetaFinder()\n\n\ndef add_shim():\n    DISTUTILS_FINDER in sys.meta_path or insert_shim()\n\n\nclass shim:\n    def __enter__(self):\n        insert_shim()\n\n    def __exit__(self, exc, value, tb):\n        remove_shim()\n\n\ndef insert_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": "# don't import any costly modules\nimport sys\nimport os\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    import warnings\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 \"\n        \"that setuptools is always imported before distutils.\")\n\n\ndef clear_distutils():\n    if 'distutils' not in sys.modules:\n        return\n    import warnings\n    warnings.warn(\"Setuptools is replacing distutils.\")\n    mods = [\n        name for name in sys.modules\n        if name == \"distutils\" or name.startswith(\"distutils.\")\n    ]\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', 'local')\n    return which == 'local'\n\n\ndef ensure_local_distutils():\n    import importlib\n    clear_distutils()\n\n    # With the DistutilsMetaFinder in place,\n    # perform an import to cause distutils to be\n    # loaded from setuptools._distutils. Ref #2906.\n    with shim():\n        importlib.import_module('distutils')\n\n    # check that submodules load as expected\n    core = importlib.import_module('distutils.core')\n    assert '_distutils' in core.__file__, core.__file__\n    assert 'setuptools._distutils.log' not in sys.modules\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 _TrivialRe:\n    def __init__(self, *patterns):\n        self._patterns = patterns\n\n    def match(self, string):\n        return all(pat in string for pat in self._patterns)\n\n\nclass DistutilsMetaFinder:\n    def find_spec(self, fullname, path, target=None):\n        if path is not None:\n            return\n\n        method_name = 'spec_for_{fullname}'.format(**locals())\n        method = getattr(self, method_name, lambda: None)\n        return method()\n\n    def spec_for_distutils(self):\n        if self.is_cpython():\n            return\n\n        import importlib\n        import importlib.abc\n        import importlib.util\n\n        try:\n            mod = importlib.import_module('setuptools._distutils')\n        except Exception:\n            # There are a couple of cases where setuptools._distutils\n            # may not be present:\n            # - An older Setuptools without a local distutils is\n            #   taking precedence. Ref #2957.\n            # - Path manipulation during sitecustomize removes\n            #   setuptools from the path but only after the hook\n            #   has been loaded. Ref #2980.\n            # In either case, fall back to stdlib behavior.\n            return\n\n        class DistutilsLoader(importlib.abc.Loader):\n\n            def create_module(self, spec):\n                mod.__name__ = 'distutils'\n                return mod\n\n            def exec_module(self, module):\n                pass\n\n        return importlib.util.spec_from_loader(\n            'distutils', DistutilsLoader(), origin=mod.__file__\n        )\n\n    @staticmethod\n    def is_cpython():\n        \"\"\"\n        Suppress supplying distutils for CPython (build and tests).\n        Ref #2965 and #3007.\n        \"\"\"\n        return os.path.isfile('pybuilddir.txt')\n\n    def spec_for_pip(self):\n        \"\"\"\n        Ensure stdlib distutils when running under pip.\n        See pypa/pip#8761 for rationale.\n        \"\"\"\n        if self.pip_imported_during_build():\n            return\n        clear_distutils()\n        self.spec_for_distutils = lambda: None\n\n    @classmethod\n    def pip_imported_during_build(cls):\n        \"\"\"\n        Detect if pip is being imported in a build script. Ref #2355.\n        \"\"\"\n        import traceback\n        return any(\n            cls.frame_file_is_setup(frame)\n            for frame, line in traceback.walk_stack(None)\n        )\n\n    @staticmethod\n    def frame_file_is_setup(frame):\n        \"\"\"\n        Return True if the indicated frame suggests a setup.py file.\n        \"\"\"\n        # some frames may not have __file__ (#2940)\n        return frame.f_globals.get('__file__', '').endswith('setup.py')\n\n\nDISTUTILS_FINDER = DistutilsMetaFinder()\n\n\ndef add_shim():\n    DISTUTILS_FINDER in sys.meta_path or insert_shim()\n\n\nclass shim:\n    def __enter__(self):\n        insert_shim()\n\n    def __exit__(self, exc, value, tb):\n        remove_shim()\n\n\ndef insert_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"}]}