MCPcopy Index your code
hub / github.com/prompt-toolkit/ptpython / PythonValidator

Class PythonValidator

src/ptpython/validator.py:13–62  ·  view source on GitHub ↗

Validation of Python input. :param get_compiler_flags: Callable that returns the currently active compiler flags.

Source from the content-addressed store, hash-verified

11
12
13class PythonValidator(Validator):
14 """
15 Validation of Python input.
16
17 :param get_compiler_flags: Callable that returns the currently
18 active compiler flags.
19 """
20
21 def __init__(self, get_compiler_flags: Callable[[], int] | None = None) -> None:
22 self.get_compiler_flags = get_compiler_flags
23
24 def validate(self, document: Document) -> None:
25 """
26 Check input for Python syntax errors.
27 """
28 text = unindent_code(document.text)
29
30 # When the input starts with Ctrl-Z, always accept. This means EOF in a
31 # Python REPL.
32 if text.startswith("\x1a"):
33 return
34
35 # When the input starts with an exclamation mark. Accept as shell
36 # command.
37 if text.lstrip().startswith("!"):
38 return
39
40 try:
41 if self.get_compiler_flags:
42 flags = self.get_compiler_flags()
43 else:
44 flags = 0
45
46 compile(text, "<input>", "exec", flags=flags, dont_inherit=True)
47 except SyntaxError as e:
48 # Note, the 'or 1' for offset is required because Python 2.7
49 # gives `None` as offset in case of '4=4' as input. (Looks like
50 # fixed in Python 3.)
51 # TODO: This is not correct if indentation was removed.
52 index = document.translate_row_col_to_index(
53 (e.lineno or 1) - 1, (e.offset or 1) - 1
54 )
55 raise ValidationError(index, f"Syntax Error: {e}")
56 except TypeError as e:
57 # e.g. "compile() expected string without null bytes"
58 raise ValidationError(0, str(e))
59 except ValueError as e:
60 # In Python 2, compiling "\x9" (an invalid escape sequence) raises
61 # ValueError instead of SyntaxError.
62 raise ValidationError(0, f"Syntax Error: {e}")

Callers 1

__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected