]>
Commit | Line | Data |
---|---|---|
53e6db90 DC |
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 | ||
6 | Parso has been battle-tested by jedi_. It was pulled out of jedi to be useful | |
7 | for other projects as well. | |
8 | ||
9 | Parso consists of a small API to parse Python and analyse the syntax tree. | |
10 | ||
11 | .. _jedi: https://github.com/davidhalter/jedi | |
12 | ||
13 | A simple example: | |
14 | ||
15 | >>> import parso | |
16 | >>> module = parso.parse('hello + 1', version="3.9") | |
17 | >>> expr = module.children[0] | |
18 | >>> expr | |
19 | PythonNode(arith_expr, [<Name: hello@1,0>, <Operator: +>, <Number: 1>]) | |
20 | >>> print(expr.get_code()) | |
21 | hello + 1 | |
22 | >>> name = expr.children[0] | |
23 | >>> name | |
24 | <Name: hello@1,0> | |
25 | >>> name.end_pos | |
26 | (1, 5) | |
27 | >>> expr.end_pos | |
28 | (1, 9) | |
29 | ||
30 | To list multiple issues: | |
31 | ||
32 | >>> grammar = parso.load_grammar() | |
33 | >>> module = grammar.parse('foo +\nbar\ncontinue') | |
34 | >>> error1, error2 = grammar.iter_errors(module) | |
35 | >>> error1.message | |
36 | 'SyntaxError: invalid syntax' | |
37 | >>> error2.message | |
38 | "SyntaxError: 'continue' not properly in loop" | |
39 | """ | |
40 | ||
41 | from parso.parser import ParserSyntaxError | |
42 | from parso.grammar import Grammar, load_grammar | |
43 | from parso.utils import split_lines, python_bytes_to_unicode | |
44 | ||
45 | ||
46 | __version__ = '0.8.3' | |
47 | ||
48 | ||
49 | def parse(code=None, **kwargs): | |
50 | """ | |
51 | A utility function to avoid loading grammars. | |
52 | Params are documented in :py:meth:`parso.Grammar.parse`. | |
53 | ||
54 | :param str version: The version used by :py:func:`parso.load_grammar`. | |
55 | """ | |
56 | version = kwargs.pop('version', None) | |
57 | grammar = load_grammar(version=version) | |
58 | return grammar.parse(code, **kwargs) |