MCPcopy Index your code
hub / github.com/python/mypy / trim_source_line

Function trim_source_line

mypy/util.py:198–227  ·  view source on GitHub ↗

Trim a line of source code to fit into max_len. Show 'min_width' characters on each side of 'col' (an error location). If either start or end is trimmed, this is indicated by adding '...' there. A typical result looks like this: ...some_variable = function_to_call(one_arg, other

(line: str, max_len: int, col: int, min_width: int)

Source from the content-addressed store, hash-verified

196
197
198def trim_source_line(line: str, max_len: int, col: int, min_width: int) -> tuple[str, int]:
199 """Trim a line of source code to fit into max_len.
200
201 Show 'min_width' characters on each side of 'col' (an error location). If either
202 start or end is trimmed, this is indicated by adding '...' there.
203 A typical result looks like this:
204 ...some_variable = function_to_call(one_arg, other_arg) or...
205
206 Return the trimmed string and the column offset to adjust error location.
207 """
208 if max_len < 2 * min_width + 1:
209 # In case the window is too tiny it is better to still show something.
210 max_len = 2 * min_width + 1
211
212 # Trivial case: line already fits in.
213 if len(line) <= max_len:
214 return line, 0
215
216 # If column is not too large so that there is still min_width after it,
217 # the line doesn't need to be trimmed at the start.
218 if col + min_width < max_len:
219 return line[:max_len] + "...", 0
220
221 # Otherwise, if the column is not too close to the end, trim both sides.
222 if col < len(line) - min_width - 1:
223 offset = col - max_len + min_width + 1
224 return "..." + line[offset : col + min_width + 1] + "...", offset - 3
225
226 # Finally, if the column is near the end, just trim the start.
227 return "..." + line[-max_len:], len(line) - max_len - 3
228
229
230def get_mypy_comments(source: str) -> list[tuple[int, str]]:

Callers 2

test_trim_sourceMethod · 0.90
fit_in_terminalMethod · 0.85

Calls 1

lenFunction · 0.85

Tested by 1

test_trim_sourceMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…