Format __repr__ for an `eval` result. Note: this can raise `KeyboardInterrupt` if either calling `__repr__`, `__pt_repr__` or formatting the output with "Black" takes to long and the user presses Control-C.
(
self,
result: object,
*,
reformat: bool,
highlight: bool,
line_length: int,
paginate: bool,
)
| 130 | ) |
| 131 | |
| 132 | def _format_result_output( |
| 133 | self, |
| 134 | result: object, |
| 135 | *, |
| 136 | reformat: bool, |
| 137 | highlight: bool, |
| 138 | line_length: int, |
| 139 | paginate: bool, |
| 140 | ) -> Generator[OneStyleAndTextTuple, None, None]: |
| 141 | """ |
| 142 | Format __repr__ for an `eval` result. |
| 143 | |
| 144 | Note: this can raise `KeyboardInterrupt` if either calling `__repr__`, |
| 145 | `__pt_repr__` or formatting the output with "Black" takes to long |
| 146 | and the user presses Control-C. |
| 147 | """ |
| 148 | # If __pt_repr__ is present, take this. This can return prompt_toolkit |
| 149 | # formatted text. |
| 150 | try: |
| 151 | if hasattr(result, "__pt_repr__"): |
| 152 | formatted_result_repr = to_formatted_text( |
| 153 | getattr(result, "__pt_repr__")() |
| 154 | ) |
| 155 | yield from formatted_result_repr |
| 156 | return |
| 157 | except (GeneratorExit, KeyboardInterrupt): |
| 158 | raise # Don't catch here. |
| 159 | except: |
| 160 | # For bad code, `__getattr__` can raise something that's not an |
| 161 | # `AttributeError`. This happens already when calling `hasattr()`. |
| 162 | pass |
| 163 | |
| 164 | # Call `__repr__` of given object first, to turn it in a string. |
| 165 | try: |
| 166 | result_repr = repr(result) |
| 167 | except KeyboardInterrupt: |
| 168 | raise # Don't catch here. |
| 169 | except BaseException as e: |
| 170 | # Calling repr failed. |
| 171 | self.display_exception(e, highlight=highlight, paginate=paginate) |
| 172 | return |
| 173 | |
| 174 | # Determine whether it's valid Python code. If not, |
| 175 | # reformatting/highlighting won't be applied. |
| 176 | if len(result_repr) < MAX_REFORMAT_SIZE: |
| 177 | try: |
| 178 | compile(result_repr, "", "eval") |
| 179 | except SyntaxError: |
| 180 | valid_python = False |
| 181 | else: |
| 182 | valid_python = True |
| 183 | else: |
| 184 | valid_python = False |
| 185 | |
| 186 | if valid_python and reformat: |
| 187 | # Inline import. Slightly speed up start-up time if black is |
| 188 | # not used. |
| 189 | try: |
no test coverage detected