__init__.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. r"""
  2. Parso is a Python parser that supports error recovery and round-trip parsing
  3. for different Python versions (in multiple Python versions). Parso is also able
  4. to list multiple syntax errors in your python file.
  5. Parso has been battle-tested by jedi_. It was pulled out of jedi to be useful
  6. for other projects as well.
  7. Parso consists of a small API to parse Python and analyse the syntax tree.
  8. .. _jedi: https://github.com/davidhalter/jedi
  9. A simple example:
  10. >>> import parso
  11. >>> module = parso.parse('hello + 1', version="3.9")
  12. >>> expr = module.children[0]
  13. >>> expr
  14. PythonNode(arith_expr, [<Name: hello@1,0>, <Operator: +>, <Number: 1>])
  15. >>> print(expr.get_code())
  16. hello + 1
  17. >>> name = expr.children[0]
  18. >>> name
  19. <Name: hello@1,0>
  20. >>> name.end_pos
  21. (1, 5)
  22. >>> expr.end_pos
  23. (1, 9)
  24. To list multiple issues:
  25. >>> grammar = parso.load_grammar()
  26. >>> module = grammar.parse('foo +\nbar\ncontinue')
  27. >>> error1, error2 = grammar.iter_errors(module)
  28. >>> error1.message
  29. 'SyntaxError: invalid syntax'
  30. >>> error2.message
  31. "SyntaxError: 'continue' not properly in loop"
  32. """
  33. from parso.parser import ParserSyntaxError
  34. from parso.grammar import Grammar, load_grammar
  35. from parso.utils import split_lines, python_bytes_to_unicode
  36. __version__ = '0.8.6'
  37. def parse(code=None, **kwargs):
  38. """
  39. A utility function to avoid loading grammars.
  40. Params are documented in :py:meth:`parso.Grammar.parse`.
  41. :param str version: The version used by :py:func:`parso.load_grammar`.
  42. """
  43. version = kwargs.pop('version', None)
  44. grammar = load_grammar(version=version)
  45. return grammar.parse(code, **kwargs)