We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Add official CPython 3.11 support
The beta / feature freeze is slated to land Friday May 6th: https://peps.python.org/pep-0664/
It would be good to get CI shards set up for 3.11 shortly thereafter to set the stage for blessing 3.11 the day the Python folks do.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pex/result.py`
Content:
```
1 # Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
2 # Licensed under the Apache License, Version 2.0 (see LICENSE).
3 
4 from __future__ import absolute_import, print_function
5 
6 import sys
7 
8 from pex.typing import TYPE_CHECKING
9 
10 if TYPE_CHECKING:
11     from typing import Any, Callable, TypeVar, Union
12 
13     import attr  # vendor:skip
14 
15     _T = TypeVar("_T")
16 else:
17     from pex.third_party import attr
18 
19 
20 @attr.s(frozen=True)
21 class Result(object):
22     exit_code = attr.ib()  # type: int
23     _message = attr.ib(default="")  # type: str
24 
25     @property
26     def is_error(self):
27         # type: () -> bool
28         return self.exit_code != 0
29 
30     def maybe_display(self):
31         # type: () -> None
32         if not self._message:
33             return
34         print(self._message, file=sys.stderr if self.is_error else sys.stdout)
35 
36     def __str__(self):
37         # type: () -> str
38         return self._message
39 
40 
41 class Ok(Result):
42     def __init__(self, message=""):
43         # type: (str) -> None
44         super(Ok, self).__init__(exit_code=0, message=message)
45 
46 
47 class Error(Result):
48     def __init__(
49         self,
50         message="",  # type: str
51         exit_code=1,  # type: int
52     ):
53         # type: (...) -> None
54         if exit_code == 0:
55             raise ValueError("An Error must have a non-zero exit code; given: {}".format(exit_code))
56         super(Error, self).__init__(exit_code=exit_code, message=message)
57 
58 
59 @attr.s(frozen=True)
60 class ResultError(Exception):
61     """Wraps an Error in an exception for use in short-circuiting via `try_` / `catch`."""
62 
63     error = attr.ib()  # type: Error
64 
65     def __str__(self):
66         # type: () -> str
67         return str(self.error)
68 
69 
70 def try_(result):
71     # type: (Union[_T, Error]) -> _T
72     """Return the result unless it's an `Error`.
73 
74     Paired with `catch` at a higher layer, this allows for ~checked exceptions without the line
75     noise of try / except handling.
76 
77     :param result: a result containing a successful value or else an error.
78     :return: the result if not an error.
79     :raise: :class:`ResultError` if the result is an error.
80     """
81     if isinstance(result, Error):
82         raise ResultError(error=result)
83     return result
84 
85 
86 def catch(
87     func,  # type: Callable[..., _T]
88     *args,  # type: Any
89     **kwargs  # type: Any
90 ):
91     # type: (...) -> Union[_T, Error]
92     """Execute the given function in a context that handles short-circuit error returns.
93 
94     :param func: The function to execute.
95     :param args: Any arguments to be passed to func.
96     :param kwargs: Any keyword arguments to be passed to func.
97     :return: The result of the function or an error if any error was returned in the call stack of
98              the function.
99     """
100     try:
101         return func(*args, **kwargs)
102     except ResultError as e:
103         return e.error
104
```

Path: `pex/interpreter_constraints.py`
Content:
```
1 # Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
2 # Licensed under the Apache License, Version 2.0 (see LICENSE).
3 
4 # A library of functions for filtering Python interpreters based on compatibility constraints
5 
6 from __future__ import absolute_import
7 
8 import itertools
9 
10 from pex.enum import Enum
11 from pex.interpreter import PythonInterpreter
12 from pex.orderedset import OrderedSet
13 from pex.third_party.packaging.specifiers import SpecifierSet
14 from pex.typing import TYPE_CHECKING
15 
16 if TYPE_CHECKING:
17     from typing import Iterable, Iterator, Optional, Tuple
18 
19     import attr  # vendor:skip
20 
21     from pex.interpreter import InterpreterIdentificationError
22 else:
23     from pex.third_party import attr
24 
25 
26 class UnsatisfiableInterpreterConstraintsError(Exception):
27     """Indicates interpreter constraints could not be satisfied."""
28 
29     def __init__(
30         self,
31         constraints,  # type: Iterable[str]
32         candidates,  # type: Iterable[PythonInterpreter]
33         failures,  # type: Iterable[InterpreterIdentificationError]
34         preamble=None,  # type: Optional[str]
35     ):
36         # type: (...) -> None
37         """
38         :param constraints: The constraints that could not be satisfied.
39         :param candidates: The python interpreters that were compared against the constraints.
40         :param failures: Descriptions of the python interpreters that were unidentifiable.
41         :param preamble: An optional preamble for the exception message.
42         """
43         self.constraints = tuple(constraints)
44         self.candidates = tuple(candidates)
45         self.failures = tuple(failures)
46         super(UnsatisfiableInterpreterConstraintsError, self).__init__(
47             self.create_message(preamble=preamble)
48         )
49 
50     def with_preamble(self, preamble):
51         # type: (str) -> UnsatisfiableInterpreterConstraintsError
52         return UnsatisfiableInterpreterConstraintsError(
53             self.constraints, self.candidates, self.failures, preamble=preamble
54         )
55 
56     def create_message(self, preamble=None):
57         # type: (Optional[str]) -> str
58         """Create a message describing  failure to find matching interpreters with an optional
59         preamble.
60 
61         :param preamble: An optional preamble to the message that will be displayed above it
62                              separated by an empty blank line.
63         :return: A descriptive message useable for display to an end user.
64         """
65         preamble = "{}\n\n".format(preamble) if preamble else ""
66 
67         failures_message = ""
68         if self.failures:
69             seen = set()
70             broken_interpreters = []
71             for python, error in self.failures:
72                 canonical_python = PythonInterpreter.canonicalize_path(python)
73                 if canonical_python not in seen:
74                     broken_interpreters.append((canonical_python, error))
75                     seen.add(canonical_python)
76 
77             failures_message = (
78                 "{}\n"
79                 "\n"
80                 "(See https://github.com/pantsbuild/pex/issues/1027 for a list of known breaks and "
81                 "workarounds.)"
82             ).format(
83                 "\n".join(
84                     "{index}.) {binary}:\n{error}".format(index=i, binary=python, error=error)
85                     for i, (python, error) in enumerate(broken_interpreters, start=1)
86                 )
87             )
88 
89         if not self.candidates:
90             if failures_message:
91                 return (
92                     "{preamble}"
93                     "Interpreters were found but they all appear to be broken:\n"
94                     "{failures}"
95                 ).format(preamble=preamble, failures=failures_message)
96             return "{}No interpreters could be found on the system.".format(preamble)
97 
98         binary_column_width = max(len(candidate.binary) for candidate in self.candidates)
99         interpreters_format = "{{index}}.) {{binary: >{}}} {{requirement}}".format(
100             binary_column_width
101         )
102 
103         qualifier = ""
104         if failures_message:
105             failures_message = "Skipped the following broken interpreters:\n{}".format(
106                 failures_message
107             )
108             qualifier = "working "
109 
110         constraints_message = ""
111         if self.constraints:
112             constraints_message = (
113                 "No {qualifier}interpreter compatible with the requested constraints was found:\n"
114                 "  {constraints}"
115             ).format(qualifier=qualifier, constraints="\n  ".join(self.constraints))
116 
117         problems = "\n\n".join(msg for msg in (failures_message, constraints_message) if msg)
118         if problems:
119             problems = "\n\n{}".format(problems)
120 
121         return (
122             "{preamble}"
123             "Examined the following {qualifier}interpreters:\n"
124             "{interpreters}"
125             "{problems}"
126         ).format(
127             preamble=preamble,
128             qualifier=qualifier,
129             interpreters="\n".join(
130                 interpreters_format.format(
131                     index=i, binary=candidate.binary, requirement=candidate.identity.requirement
132                 )
133                 for i, candidate in enumerate(self.candidates, start=1)
134             ),
135             problems=problems,
136         )
137 
138 
139 class Lifecycle(Enum["Lifecycle.Value"]):
140     class Value(Enum.Value):
141         pass
142 
143     DEV = Value("dev")
144     STABLE = Value("stable")
145     EOL = Value("eol")
146 
147 
148 # This value is based off of:
149 # 1. Past releases: https://www.python.org/downloads/ where the max patch level was achieved by
150 #    2.7.18.
151 # 2. The 3.9+ annual release cycle formalization: https://www.python.org/dev/peps/pep-0602/ where
152 #    the last bugfix release will be at a patch level of ~10 and then 3.5 years of security fixes
153 #    as needed before going to EOL at the 5-year mark.
154 DEFAULT_MAX_PATCH = 30
155 
156 
157 @attr.s(frozen=True)
158 class PythonVersion(object):
159     lifecycle = attr.ib()  # type: Lifecycle.Value
160     major = attr.ib()  # type: int
161     minor = attr.ib()  # type: int
162     patch = attr.ib()  # type: int
163 
164     def iter_compatible_versions(
165         self,
166         specifier_sets,  # type: Iterable[SpecifierSet]
167         max_patch=DEFAULT_MAX_PATCH,  # type: int
168     ):
169         # type: (...) -> Iterator[Tuple[int, int, int]]
170         last_patch = self.patch if self.lifecycle == Lifecycle.EOL else max_patch
171         for patch in range(last_patch + 1):
172             version = (self.major, self.minor, patch)
173             version_string = ".".join(map(str, version))
174             if not specifier_sets:
175                 yield version
176             else:
177                 for specifier_set in specifier_sets:
178                     if version_string in specifier_set:
179                         yield version
180                         break
181 
182 
183 # TODO(John Sirois): Integrate a `pyenv install -l` based lint / generate script for CI / local
184 # use that emits the current max patch for these versions so we automatically stay up to date
185 # mod dormancy in the project.
186 
187 COMPATIBLE_PYTHON_VERSIONS = (
188     PythonVersion(Lifecycle.EOL, 2, 7, 18),
189     # N.B.: Pex does not support the missing 3.x versions here.
190     PythonVersion(Lifecycle.EOL, 3, 5, 10),
191     PythonVersion(Lifecycle.EOL, 3, 6, 15),
192     PythonVersion(Lifecycle.STABLE, 3, 7, 12),
193     PythonVersion(Lifecycle.STABLE, 3, 8, 12),
194     PythonVersion(Lifecycle.STABLE, 3, 9, 10),
195     PythonVersion(Lifecycle.STABLE, 3, 10, 2),
196     PythonVersion(Lifecycle.DEV, 3, 11, 0),
197 )
198 
199 
200 def iter_compatible_versions(
201     requires_python,  # type: Iterable[str]
202     max_patch=DEFAULT_MAX_PATCH,  # type: int
203 ):
204     # type: (...) -> Iterator[Tuple[int, int, int]]
205 
206     specifier_sets = OrderedSet(SpecifierSet(req) for req in requires_python)
207     return itertools.chain.from_iterable(
208         python_version.iter_compatible_versions(specifier_sets, max_patch=max_patch)
209         for python_version in COMPATIBLE_PYTHON_VERSIONS
210     )
211
```
--- 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/pex/interpreter_constraints.py b/pex/interpreter_constraints.py
--- a/pex/interpreter_constraints.py
+++ b/pex/interpreter_constraints.py
@@ -189,10 +189,10 @@
     # N.B.: Pex does not support the missing 3.x versions here.
     PythonVersion(Lifecycle.EOL, 3, 5, 10),
     PythonVersion(Lifecycle.EOL, 3, 6, 15),
-    PythonVersion(Lifecycle.STABLE, 3, 7, 12),
-    PythonVersion(Lifecycle.STABLE, 3, 8, 12),
-    PythonVersion(Lifecycle.STABLE, 3, 9, 10),
-    PythonVersion(Lifecycle.STABLE, 3, 10, 2),
+    PythonVersion(Lifecycle.STABLE, 3, 7, 13),
+    PythonVersion(Lifecycle.STABLE, 3, 8, 13),
+    PythonVersion(Lifecycle.STABLE, 3, 9, 12),
+    PythonVersion(Lifecycle.STABLE, 3, 10, 4),
     PythonVersion(Lifecycle.DEV, 3, 11, 0),
 )
 
diff --git a/pex/result.py b/pex/result.py
--- a/pex/result.py
+++ b/pex/result.py
@@ -56,7 +56,9 @@
         super(Error, self).__init__(exit_code=exit_code, message=message)
 
 
-@attr.s(frozen=True)
+# Frozen exception types don't work under 3.11.0b1 which sets the `__traceback__` attribute after
+# construction in some cases.
+@attr.s
 class ResultError(Exception):
     """Wraps an Error in an exception for use in short-circuiting via `try_` / `catch`."""

{"golden_diff": "diff --git a/pex/interpreter_constraints.py b/pex/interpreter_constraints.py\n--- a/pex/interpreter_constraints.py\n+++ b/pex/interpreter_constraints.py\n@@ -189,10 +189,10 @@\n     # N.B.: Pex does not support the missing 3.x versions here.\n     PythonVersion(Lifecycle.EOL, 3, 5, 10),\n     PythonVersion(Lifecycle.EOL, 3, 6, 15),\n-    PythonVersion(Lifecycle.STABLE, 3, 7, 12),\n-    PythonVersion(Lifecycle.STABLE, 3, 8, 12),\n-    PythonVersion(Lifecycle.STABLE, 3, 9, 10),\n-    PythonVersion(Lifecycle.STABLE, 3, 10, 2),\n+    PythonVersion(Lifecycle.STABLE, 3, 7, 13),\n+    PythonVersion(Lifecycle.STABLE, 3, 8, 13),\n+    PythonVersion(Lifecycle.STABLE, 3, 9, 12),\n+    PythonVersion(Lifecycle.STABLE, 3, 10, 4),\n     PythonVersion(Lifecycle.DEV, 3, 11, 0),\n )\n \ndiff --git a/pex/result.py b/pex/result.py\n--- a/pex/result.py\n+++ b/pex/result.py\n@@ -56,7 +56,9 @@\n         super(Error, self).__init__(exit_code=exit_code, message=message)\n \n \n-@attr.s(frozen=True)\n+# Frozen exception types don't work under 3.11.0b1 which sets the `__traceback__` attribute after\n+# construction in some cases.\n+@attr.s\n class ResultError(Exception):\n     \"\"\"Wraps an Error in an exception for use in short-circuiting via `try_` / `catch`.\"\"\"\n", "issue": "Add official CPython 3.11 support\nThe beta / feature freeze is slated to land Friday May 6th: https://peps.python.org/pep-0664/\r\nIt would be good to get CI shards set up for 3.11 shortly thereafter to set the stage for blessing 3.11 the day the Python folks do.\n", "before_files": [{"content": "# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import absolute_import, print_function\n\nimport sys\n\nfrom pex.typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from typing import Any, Callable, TypeVar, Union\n\n    import attr  # vendor:skip\n\n    _T = TypeVar(\"_T\")\nelse:\n    from pex.third_party import attr\n\n\n@attr.s(frozen=True)\nclass Result(object):\n    exit_code = attr.ib()  # type: int\n    _message = attr.ib(default=\"\")  # type: str\n\n    @property\n    def is_error(self):\n        # type: () -> bool\n        return self.exit_code != 0\n\n    def maybe_display(self):\n        # type: () -> None\n        if not self._message:\n            return\n        print(self._message, file=sys.stderr if self.is_error else sys.stdout)\n\n    def __str__(self):\n        # type: () -> str\n        return self._message\n\n\nclass Ok(Result):\n    def __init__(self, message=\"\"):\n        # type: (str) -> None\n        super(Ok, self).__init__(exit_code=0, message=message)\n\n\nclass Error(Result):\n    def __init__(\n        self,\n        message=\"\",  # type: str\n        exit_code=1,  # type: int\n    ):\n        # type: (...) -> None\n        if exit_code == 0:\n            raise ValueError(\"An Error must have a non-zero exit code; given: {}\".format(exit_code))\n        super(Error, self).__init__(exit_code=exit_code, message=message)\n\n\n@attr.s(frozen=True)\nclass ResultError(Exception):\n    \"\"\"Wraps an Error in an exception for use in short-circuiting via `try_` / `catch`.\"\"\"\n\n    error = attr.ib()  # type: Error\n\n    def __str__(self):\n        # type: () -> str\n        return str(self.error)\n\n\ndef try_(result):\n    # type: (Union[_T, Error]) -> _T\n    \"\"\"Return the result unless it's an `Error`.\n\n    Paired with `catch` at a higher layer, this allows for ~checked exceptions without the line\n    noise of try / except handling.\n\n    :param result: a result containing a successful value or else an error.\n    :return: the result if not an error.\n    :raise: :class:`ResultError` if the result is an error.\n    \"\"\"\n    if isinstance(result, Error):\n        raise ResultError(error=result)\n    return result\n\n\ndef catch(\n    func,  # type: Callable[..., _T]\n    *args,  # type: Any\n    **kwargs  # type: Any\n):\n    # type: (...) -> Union[_T, Error]\n    \"\"\"Execute the given function in a context that handles short-circuit error returns.\n\n    :param func: The function to execute.\n    :param args: Any arguments to be passed to func.\n    :param kwargs: Any keyword arguments to be passed to func.\n    :return: The result of the function or an error if any error was returned in the call stack of\n             the function.\n    \"\"\"\n    try:\n        return func(*args, **kwargs)\n    except ResultError as e:\n        return e.error\n", "path": "pex/result.py"}, {"content": "# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\n# A library of functions for filtering Python interpreters based on compatibility constraints\n\nfrom __future__ import absolute_import\n\nimport itertools\n\nfrom pex.enum import Enum\nfrom pex.interpreter import PythonInterpreter\nfrom pex.orderedset import OrderedSet\nfrom pex.third_party.packaging.specifiers import SpecifierSet\nfrom pex.typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from typing import Iterable, Iterator, Optional, Tuple\n\n    import attr  # vendor:skip\n\n    from pex.interpreter import InterpreterIdentificationError\nelse:\n    from pex.third_party import attr\n\n\nclass UnsatisfiableInterpreterConstraintsError(Exception):\n    \"\"\"Indicates interpreter constraints could not be satisfied.\"\"\"\n\n    def __init__(\n        self,\n        constraints,  # type: Iterable[str]\n        candidates,  # type: Iterable[PythonInterpreter]\n        failures,  # type: Iterable[InterpreterIdentificationError]\n        preamble=None,  # type: Optional[str]\n    ):\n        # type: (...) -> None\n        \"\"\"\n        :param constraints: The constraints that could not be satisfied.\n        :param candidates: The python interpreters that were compared against the constraints.\n        :param failures: Descriptions of the python interpreters that were unidentifiable.\n        :param preamble: An optional preamble for the exception message.\n        \"\"\"\n        self.constraints = tuple(constraints)\n        self.candidates = tuple(candidates)\n        self.failures = tuple(failures)\n        super(UnsatisfiableInterpreterConstraintsError, self).__init__(\n            self.create_message(preamble=preamble)\n        )\n\n    def with_preamble(self, preamble):\n        # type: (str) -> UnsatisfiableInterpreterConstraintsError\n        return UnsatisfiableInterpreterConstraintsError(\n            self.constraints, self.candidates, self.failures, preamble=preamble\n        )\n\n    def create_message(self, preamble=None):\n        # type: (Optional[str]) -> str\n        \"\"\"Create a message describing  failure to find matching interpreters with an optional\n        preamble.\n\n        :param preamble: An optional preamble to the message that will be displayed above it\n                             separated by an empty blank line.\n        :return: A descriptive message useable for display to an end user.\n        \"\"\"\n        preamble = \"{}\\n\\n\".format(preamble) if preamble else \"\"\n\n        failures_message = \"\"\n        if self.failures:\n            seen = set()\n            broken_interpreters = []\n            for python, error in self.failures:\n                canonical_python = PythonInterpreter.canonicalize_path(python)\n                if canonical_python not in seen:\n                    broken_interpreters.append((canonical_python, error))\n                    seen.add(canonical_python)\n\n            failures_message = (\n                \"{}\\n\"\n                \"\\n\"\n                \"(See https://github.com/pantsbuild/pex/issues/1027 for a list of known breaks and \"\n                \"workarounds.)\"\n            ).format(\n                \"\\n\".join(\n                    \"{index}.) {binary}:\\n{error}\".format(index=i, binary=python, error=error)\n                    for i, (python, error) in enumerate(broken_interpreters, start=1)\n                )\n            )\n\n        if not self.candidates:\n            if failures_message:\n                return (\n                    \"{preamble}\"\n                    \"Interpreters were found but they all appear to be broken:\\n\"\n                    \"{failures}\"\n                ).format(preamble=preamble, failures=failures_message)\n            return \"{}No interpreters could be found on the system.\".format(preamble)\n\n        binary_column_width = max(len(candidate.binary) for candidate in self.candidates)\n        interpreters_format = \"{{index}}.) {{binary: >{}}} {{requirement}}\".format(\n            binary_column_width\n        )\n\n        qualifier = \"\"\n        if failures_message:\n            failures_message = \"Skipped the following broken interpreters:\\n{}\".format(\n                failures_message\n            )\n            qualifier = \"working \"\n\n        constraints_message = \"\"\n        if self.constraints:\n            constraints_message = (\n                \"No {qualifier}interpreter compatible with the requested constraints was found:\\n\"\n                \"  {constraints}\"\n            ).format(qualifier=qualifier, constraints=\"\\n  \".join(self.constraints))\n\n        problems = \"\\n\\n\".join(msg for msg in (failures_message, constraints_message) if msg)\n        if problems:\n            problems = \"\\n\\n{}\".format(problems)\n\n        return (\n            \"{preamble}\"\n            \"Examined the following {qualifier}interpreters:\\n\"\n            \"{interpreters}\"\n            \"{problems}\"\n        ).format(\n            preamble=preamble,\n            qualifier=qualifier,\n            interpreters=\"\\n\".join(\n                interpreters_format.format(\n                    index=i, binary=candidate.binary, requirement=candidate.identity.requirement\n                )\n                for i, candidate in enumerate(self.candidates, start=1)\n            ),\n            problems=problems,\n        )\n\n\nclass Lifecycle(Enum[\"Lifecycle.Value\"]):\n    class Value(Enum.Value):\n        pass\n\n    DEV = Value(\"dev\")\n    STABLE = Value(\"stable\")\n    EOL = Value(\"eol\")\n\n\n# This value is based off of:\n# 1. Past releases: https://www.python.org/downloads/ where the max patch level was achieved by\n#    2.7.18.\n# 2. The 3.9+ annual release cycle formalization: https://www.python.org/dev/peps/pep-0602/ where\n#    the last bugfix release will be at a patch level of ~10 and then 3.5 years of security fixes\n#    as needed before going to EOL at the 5-year mark.\nDEFAULT_MAX_PATCH = 30\n\n\n@attr.s(frozen=True)\nclass PythonVersion(object):\n    lifecycle = attr.ib()  # type: Lifecycle.Value\n    major = attr.ib()  # type: int\n    minor = attr.ib()  # type: int\n    patch = attr.ib()  # type: int\n\n    def iter_compatible_versions(\n        self,\n        specifier_sets,  # type: Iterable[SpecifierSet]\n        max_patch=DEFAULT_MAX_PATCH,  # type: int\n    ):\n        # type: (...) -> Iterator[Tuple[int, int, int]]\n        last_patch = self.patch if self.lifecycle == Lifecycle.EOL else max_patch\n        for patch in range(last_patch + 1):\n            version = (self.major, self.minor, patch)\n            version_string = \".\".join(map(str, version))\n            if not specifier_sets:\n                yield version\n            else:\n                for specifier_set in specifier_sets:\n                    if version_string in specifier_set:\n                        yield version\n                        break\n\n\n# TODO(John Sirois): Integrate a `pyenv install -l` based lint / generate script for CI / local\n# use that emits the current max patch for these versions so we automatically stay up to date\n# mod dormancy in the project.\n\nCOMPATIBLE_PYTHON_VERSIONS = (\n    PythonVersion(Lifecycle.EOL, 2, 7, 18),\n    # N.B.: Pex does not support the missing 3.x versions here.\n    PythonVersion(Lifecycle.EOL, 3, 5, 10),\n    PythonVersion(Lifecycle.EOL, 3, 6, 15),\n    PythonVersion(Lifecycle.STABLE, 3, 7, 12),\n    PythonVersion(Lifecycle.STABLE, 3, 8, 12),\n    PythonVersion(Lifecycle.STABLE, 3, 9, 10),\n    PythonVersion(Lifecycle.STABLE, 3, 10, 2),\n    PythonVersion(Lifecycle.DEV, 3, 11, 0),\n)\n\n\ndef iter_compatible_versions(\n    requires_python,  # type: Iterable[str]\n    max_patch=DEFAULT_MAX_PATCH,  # type: int\n):\n    # type: (...) -> Iterator[Tuple[int, int, int]]\n\n    specifier_sets = OrderedSet(SpecifierSet(req) for req in requires_python)\n    return itertools.chain.from_iterable(\n        python_version.iter_compatible_versions(specifier_sets, max_patch=max_patch)\n        for python_version in COMPATIBLE_PYTHON_VERSIONS\n    )\n", "path": "pex/interpreter_constraints.py"}], "after_files": [{"content": "# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import absolute_import, print_function\n\nimport sys\n\nfrom pex.typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from typing import Any, Callable, TypeVar, Union\n\n    import attr  # vendor:skip\n\n    _T = TypeVar(\"_T\")\nelse:\n    from pex.third_party import attr\n\n\n@attr.s(frozen=True)\nclass Result(object):\n    exit_code = attr.ib()  # type: int\n    _message = attr.ib(default=\"\")  # type: str\n\n    @property\n    def is_error(self):\n        # type: () -> bool\n        return self.exit_code != 0\n\n    def maybe_display(self):\n        # type: () -> None\n        if not self._message:\n            return\n        print(self._message, file=sys.stderr if self.is_error else sys.stdout)\n\n    def __str__(self):\n        # type: () -> str\n        return self._message\n\n\nclass Ok(Result):\n    def __init__(self, message=\"\"):\n        # type: (str) -> None\n        super(Ok, self).__init__(exit_code=0, message=message)\n\n\nclass Error(Result):\n    def __init__(\n        self,\n        message=\"\",  # type: str\n        exit_code=1,  # type: int\n    ):\n        # type: (...) -> None\n        if exit_code == 0:\n            raise ValueError(\"An Error must have a non-zero exit code; given: {}\".format(exit_code))\n        super(Error, self).__init__(exit_code=exit_code, message=message)\n\n\n# Frozen exception types don't work under 3.11.0b1 which sets the `__traceback__` attribute after\n# construction in some cases.\n@attr.s\nclass ResultError(Exception):\n    \"\"\"Wraps an Error in an exception for use in short-circuiting via `try_` / `catch`.\"\"\"\n\n    error = attr.ib()  # type: Error\n\n    def __str__(self):\n        # type: () -> str\n        return str(self.error)\n\n\ndef try_(result):\n    # type: (Union[_T, Error]) -> _T\n    \"\"\"Return the result unless it's an `Error`.\n\n    Paired with `catch` at a higher layer, this allows for ~checked exceptions without the line\n    noise of try / except handling.\n\n    :param result: a result containing a successful value or else an error.\n    :return: the result if not an error.\n    :raise: :class:`ResultError` if the result is an error.\n    \"\"\"\n    if isinstance(result, Error):\n        raise ResultError(error=result)\n    return result\n\n\ndef catch(\n    func,  # type: Callable[..., _T]\n    *args,  # type: Any\n    **kwargs  # type: Any\n):\n    # type: (...) -> Union[_T, Error]\n    \"\"\"Execute the given function in a context that handles short-circuit error returns.\n\n    :param func: The function to execute.\n    :param args: Any arguments to be passed to func.\n    :param kwargs: Any keyword arguments to be passed to func.\n    :return: The result of the function or an error if any error was returned in the call stack of\n             the function.\n    \"\"\"\n    try:\n        return func(*args, **kwargs)\n    except ResultError as e:\n        return e.error\n", "path": "pex/result.py"}, {"content": "# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\n# A library of functions for filtering Python interpreters based on compatibility constraints\n\nfrom __future__ import absolute_import\n\nimport itertools\n\nfrom pex.enum import Enum\nfrom pex.interpreter import PythonInterpreter\nfrom pex.orderedset import OrderedSet\nfrom pex.third_party.packaging.specifiers import SpecifierSet\nfrom pex.typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from typing import Iterable, Iterator, Optional, Tuple\n\n    import attr  # vendor:skip\n\n    from pex.interpreter import InterpreterIdentificationError\nelse:\n    from pex.third_party import attr\n\n\nclass UnsatisfiableInterpreterConstraintsError(Exception):\n    \"\"\"Indicates interpreter constraints could not be satisfied.\"\"\"\n\n    def __init__(\n        self,\n        constraints,  # type: Iterable[str]\n        candidates,  # type: Iterable[PythonInterpreter]\n        failures,  # type: Iterable[InterpreterIdentificationError]\n        preamble=None,  # type: Optional[str]\n    ):\n        # type: (...) -> None\n        \"\"\"\n        :param constraints: The constraints that could not be satisfied.\n        :param candidates: The python interpreters that were compared against the constraints.\n        :param failures: Descriptions of the python interpreters that were unidentifiable.\n        :param preamble: An optional preamble for the exception message.\n        \"\"\"\n        self.constraints = tuple(constraints)\n        self.candidates = tuple(candidates)\n        self.failures = tuple(failures)\n        super(UnsatisfiableInterpreterConstraintsError, self).__init__(\n            self.create_message(preamble=preamble)\n        )\n\n    def with_preamble(self, preamble):\n        # type: (str) -> UnsatisfiableInterpreterConstraintsError\n        return UnsatisfiableInterpreterConstraintsError(\n            self.constraints, self.candidates, self.failures, preamble=preamble\n        )\n\n    def create_message(self, preamble=None):\n        # type: (Optional[str]) -> str\n        \"\"\"Create a message describing  failure to find matching interpreters with an optional\n        preamble.\n\n        :param preamble: An optional preamble to the message that will be displayed above it\n                             separated by an empty blank line.\n        :return: A descriptive message useable for display to an end user.\n        \"\"\"\n        preamble = \"{}\\n\\n\".format(preamble) if preamble else \"\"\n\n        failures_message = \"\"\n        if self.failures:\n            seen = set()\n            broken_interpreters = []\n            for python, error in self.failures:\n                canonical_python = PythonInterpreter.canonicalize_path(python)\n                if canonical_python not in seen:\n                    broken_interpreters.append((canonical_python, error))\n                    seen.add(canonical_python)\n\n            failures_message = (\n                \"{}\\n\"\n                \"\\n\"\n                \"(See https://github.com/pantsbuild/pex/issues/1027 for a list of known breaks and \"\n                \"workarounds.)\"\n            ).format(\n                \"\\n\".join(\n                    \"{index}.) {binary}:\\n{error}\".format(index=i, binary=python, error=error)\n                    for i, (python, error) in enumerate(broken_interpreters, start=1)\n                )\n            )\n\n        if not self.candidates:\n            if failures_message:\n                return (\n                    \"{preamble}\"\n                    \"Interpreters were found but they all appear to be broken:\\n\"\n                    \"{failures}\"\n                ).format(preamble=preamble, failures=failures_message)\n            return \"{}No interpreters could be found on the system.\".format(preamble)\n\n        binary_column_width = max(len(candidate.binary) for candidate in self.candidates)\n        interpreters_format = \"{{index}}.) {{binary: >{}}} {{requirement}}\".format(\n            binary_column_width\n        )\n\n        qualifier = \"\"\n        if failures_message:\n            failures_message = \"Skipped the following broken interpreters:\\n{}\".format(\n                failures_message\n            )\n            qualifier = \"working \"\n\n        constraints_message = \"\"\n        if self.constraints:\n            constraints_message = (\n                \"No {qualifier}interpreter compatible with the requested constraints was found:\\n\"\n                \"  {constraints}\"\n            ).format(qualifier=qualifier, constraints=\"\\n  \".join(self.constraints))\n\n        problems = \"\\n\\n\".join(msg for msg in (failures_message, constraints_message) if msg)\n        if problems:\n            problems = \"\\n\\n{}\".format(problems)\n\n        return (\n            \"{preamble}\"\n            \"Examined the following {qualifier}interpreters:\\n\"\n            \"{interpreters}\"\n            \"{problems}\"\n        ).format(\n            preamble=preamble,\n            qualifier=qualifier,\n            interpreters=\"\\n\".join(\n                interpreters_format.format(\n                    index=i, binary=candidate.binary, requirement=candidate.identity.requirement\n                )\n                for i, candidate in enumerate(self.candidates, start=1)\n            ),\n            problems=problems,\n        )\n\n\nclass Lifecycle(Enum[\"Lifecycle.Value\"]):\n    class Value(Enum.Value):\n        pass\n\n    DEV = Value(\"dev\")\n    STABLE = Value(\"stable\")\n    EOL = Value(\"eol\")\n\n\n# This value is based off of:\n# 1. Past releases: https://www.python.org/downloads/ where the max patch level was achieved by\n#    2.7.18.\n# 2. The 3.9+ annual release cycle formalization: https://www.python.org/dev/peps/pep-0602/ where\n#    the last bugfix release will be at a patch level of ~10 and then 3.5 years of security fixes\n#    as needed before going to EOL at the 5-year mark.\nDEFAULT_MAX_PATCH = 30\n\n\n@attr.s(frozen=True)\nclass PythonVersion(object):\n    lifecycle = attr.ib()  # type: Lifecycle.Value\n    major = attr.ib()  # type: int\n    minor = attr.ib()  # type: int\n    patch = attr.ib()  # type: int\n\n    def iter_compatible_versions(\n        self,\n        specifier_sets,  # type: Iterable[SpecifierSet]\n        max_patch=DEFAULT_MAX_PATCH,  # type: int\n    ):\n        # type: (...) -> Iterator[Tuple[int, int, int]]\n        last_patch = self.patch if self.lifecycle == Lifecycle.EOL else max_patch\n        for patch in range(last_patch + 1):\n            version = (self.major, self.minor, patch)\n            version_string = \".\".join(map(str, version))\n            if not specifier_sets:\n                yield version\n            else:\n                for specifier_set in specifier_sets:\n                    if version_string in specifier_set:\n                        yield version\n                        break\n\n\n# TODO(John Sirois): Integrate a `pyenv install -l` based lint / generate script for CI / local\n# use that emits the current max patch for these versions so we automatically stay up to date\n# mod dormancy in the project.\n\nCOMPATIBLE_PYTHON_VERSIONS = (\n    PythonVersion(Lifecycle.EOL, 2, 7, 18),\n    # N.B.: Pex does not support the missing 3.x versions here.\n    PythonVersion(Lifecycle.EOL, 3, 5, 10),\n    PythonVersion(Lifecycle.EOL, 3, 6, 15),\n    PythonVersion(Lifecycle.STABLE, 3, 7, 13),\n    PythonVersion(Lifecycle.STABLE, 3, 8, 13),\n    PythonVersion(Lifecycle.STABLE, 3, 9, 12),\n    PythonVersion(Lifecycle.STABLE, 3, 10, 4),\n    PythonVersion(Lifecycle.DEV, 3, 11, 0),\n)\n\n\ndef iter_compatible_versions(\n    requires_python,  # type: Iterable[str]\n    max_patch=DEFAULT_MAX_PATCH,  # type: int\n):\n    # type: (...) -> Iterator[Tuple[int, int, int]]\n\n    specifier_sets = OrderedSet(SpecifierSet(req) for req in requires_python)\n    return itertools.chain.from_iterable(\n        python_version.iter_compatible_versions(specifier_sets, max_patch=max_patch)\n        for python_version in COMPATIBLE_PYTHON_VERSIONS\n    )\n", "path": "pex/interpreter_constraints.py"}]}