MCPcopy Index your code
hub / github.com/python/cpython / get_source_segment

Function get_source_segment

Lib/ast.py:363–397  ·  view source on GitHub ↗

Get source code segment of the *source* that generated *node*. If some location information (`lineno`, `end_lineno`, `col_offset`, or `end_col_offset`) is missing, return None. If *padded* is `True`, the first line of a multi-line statement will be padded with spaces to match its o

(source, node, *, padded=False)

Source from the content-addressed store, hash-verified

361
362
363def get_source_segment(source, node, *, padded=False):
364 """Get source code segment of the *source* that generated *node*.
365
366 If some location information (`lineno`, `end_lineno`, `col_offset`,
367 or `end_col_offset`) is missing, return None.
368
369 If *padded* is `True`, the first line of a multi-line statement will
370 be padded with spaces to match its original position.
371 """
372 try:
373 if node.end_lineno is None or node.end_col_offset is None:
374 return None
375 lineno = node.lineno - 1
376 end_lineno = node.end_lineno - 1
377 col_offset = node.col_offset
378 end_col_offset = node.end_col_offset
379 except AttributeError:
380 return None
381
382 lines = _splitlines_no_ff(source, maxlines=end_lineno+1)
383 if end_lineno == lineno:
384 return lines[lineno].encode()[col_offset:end_col_offset].decode()
385
386 if padded:
387 padding = _pad_whitespace(lines[lineno].encode()[:col_offset].decode())
388 else:
389 padding = ''
390
391 first = padding + lines[lineno].encode()[col_offset:].decode()
392 last = lines[end_lineno].encode()[:end_col_offset].decode()
393 lines = lines[lineno+1:end_lineno]
394
395 lines.insert(0, first)
396 lines.append(last)
397 return ''.join(lines)
398
399
400def walk(node):

Callers

nothing calls this directly

Calls 7

_splitlines_no_ffFunction · 0.85
_pad_whitespaceFunction · 0.85
decodeMethod · 0.45
encodeMethod · 0.45
insertMethod · 0.45
appendMethod · 0.45
joinMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…