Skip to contents

This function checks whether a character string is syntactically valid Python code. It never runs the code: it asks a Python interpreter to parse it with the ast module, with a 10-second timeout and with the OPENAI_API_KEY environment variable removed from the child process. Code that parses but would fail at run time (e.g., a misspelled function name or a missing import) counts as valid.

Usage

is_python(code)

Arguments

code

A character string containing code to be checked for Python code validity. A character vector with more than one element is treated as the lines of one script (one element per line). Windows (CRLF) line endings are accepted.

Value

TRUE if code parses as Python code, FALSE if it does not, and NA if it could not be checked (no Python interpreter found, the interpreter could not be started, or the check timed out). Non-character input, NA elements and empty or blank strings return FALSE.

Details

The interpreter is the first of python3, python and py (the Windows Python launcher) that is on the PATH and can run Python: each candidate is tried once with -c "import ast", and one that cannot run it, such as the Microsoft Store alias that Windows puts on the PATH in place of Python, is skipped. The choice is made once per session, except that a candidate that did not answer within 10 seconds (a slow first start) is tried again on the next call. Without a working interpreter, is_python() warns (once per session) and returns NA.

Examples

# \donttest{
# Needs a Python interpreter; without one, a warning and NA
# Valid Python code
is_python("print('Hello, World!')")
#> [1] TRUE

# Invalid Python code (missing colon)
is_python("if x > 0\n    print(x)")
#> [1] FALSE
# }