How to tell if a string contains valid Python code

Use ast.parse:

import ast
def is_valid_python(code):
   try:
       ast.parse(code)
   except SyntaxError:
       return False
   return True

>>> is_valid_python('1 // 2')
True
>>> is_valid_python('1 /// 2')
False

Leave a Comment