fork download
  1. import tokenize
  2. from io import BytesIO
  3. from collections import deque
  4. code_string = r"""
  5. class Bar(object):
  6. def __init__(self):
  7. a = \
  8. 1
  9. b = 2
  10. """.strip()
  11. file = BytesIO(code_string.encode())
  12. tokens = deque(tokenize.tokenize(file.readline))
  13. lines = []
  14. while tokens:
  15. token = tokens.popleft()
  16. if token.type == tokenize.NAME and token.string == 'def':
  17. start_line, start_column = token.start
  18. end_line, _ = token.end
  19. enclosures = 0
  20. while tokens:
  21. token = tokens.popleft()
  22. if token.type == tokenize.NL: # ignore empty lines
  23. continue
  24. if token.type == tokenize.OP and token.string in '([{':
  25. enclosures += 1
  26. _, column = token.start
  27. if column <= start_column and token.type != tokenize.INDENT and not enclosures:
  28. tokens.appendleft(token)
  29. break
  30. if token.type == tokenize.OP and token.string in ')]}':
  31. enclosures -= 1
  32. end_line, _ = token.end
  33. lines.append((start_line, end_line))
  34. print(lines)
Success #stdin #stdout 0.02s 27768KB
stdin
Standard input is empty
stdout
[(2, 3)]