我正在寻找代码来检查代表函数头部的字符串在语法上是否正确。
下面是我的字符串示例:
'''+'def __init__(self,{arg})'.format(arg = ','.join(i for i in someListOranArgPassedIn), )+''':
如果此函数定义为
def __init__(self,,...a,,//b):
并且违反了语法规则,我可以添加什么来引发异常?
发布于 2014-05-10 03:27:01
使用here中的函数。
import ast
def is_valid_python(code):
try:
ast.parse(code)
except SyntaxError:
return False
return True
test_args = lambda args: "def init(self, {arg}):\n\tpass".format(arg = ",".join(args))
print is_valid_python(test_args(["a", "b"]))
print is_valid_python(test_args(["", "...a", "", "//b"]))
https://stackoverflow.com/questions/23576681
复制