Skip to content

Instantly share code, notes, and snippets.

@blluv
Created June 12, 2022 15:11
Show Gist options
  • Save blluv/fb4018d1dfe6ce4f7bf5c8bea726c12d to your computer and use it in GitHub Desktop.
Save blluv/fb4018d1dfe6ce4f7bf5c8bea726c12d to your computer and use it in GitHub Desktop.
check valid expr
import ast
def checkValid(expr: str):
try:
tree = ast.parse(expr)
except:
return False
if len(tree.body) != 1:
return False
if not isinstance(tree.body[0], ast.Expr):
return False
def check(expr: ast.Expr):
if isinstance(expr, (int, float)):
return True
if isinstance(expr, ast.Name):
return True
if isinstance(expr, ast.Constant):
return check(expr.value)
elif isinstance(expr, ast.BinOp):
return check(expr.left) and check(expr.right)
else:
return False
return check(tree.body[0].value)
assert checkValid("1") == True
assert checkValid("(1+2)*(x)") == True
assert checkValid('2**4') == True
assert checkValid('([]+1)') == False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment