Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a string contains valid Python code

If I have a string of Python code, how do I tell if it is valid, i.e., if entered at the Python prompt, it would raise a SyntaxError or not? I thought that using compiler.parse would work, but apparently that module has been removed in Python 3. Is there a way to do it that also works in Python 3. Obviously, I don't want to execute the code, just check its syntax.

like image 394
asmeurer Avatar asked Aug 07 '12 22:08

asmeurer


People also ask

How do I check if a string contains something in Python?

Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .

Is a valid string in Python?

Python String isidentifier() MethodA string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.

How do you see if a character is in a string Python?

Using in operator The Pythonic, fast way to check for the specific character in a string uses the in operator. It returns True if the character is found in the string and False otherwise. ch = '. '


1 Answers

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
like image 115
phihag Avatar answered Oct 01 '22 12:10

phihag