有没有办法检查能够评估的字符串的类型?
示例:
y = 2
x = 2
z = "y + x"
eval(z)
可以评估变量 z 。这很好,但是当我在z上调用isinstance时它会返回功能而不是str。
或者,如果可能,我可以检查是否可以 评估
。答案 0 :(得分:3)
你确定要在这里找到一个字符串吗?
y = 2
x = 2
z = lambda: y + x
print z()
if callable(z):
print "z is a function"
否则,最简单的方法是尝试运行它:
z = "y + x"
try:
eval(z)
print "z was runnable (And we ran it)"
except Exception:
print "Nope, z is not a string that we can run"
如果您不想实际运行它,可以预编译它:
z = 'x + y'
try:
z = compile(z + '\n', '<expression for z>', 'eval')
except SyntaxError:
raise Exception("Could not process z")
# later
eval(z)
或者,如果你真的觉得自己是hacky(python 3):
z = 'x + y'
try:
z_code = compile(z + '\n', '<expression for z>', 'eval')
z = lambda: None
z.__code__ = z_code # swap out the contents of our empty function with some new code
except SyntaxError:
raise Exception("Could not process z")
# later - it's now actually a function!
assert type(z) == types.FunctionType
z()
答案 1 :(得分:3)
我想到的是否可以评估字符串的解决方案是:
def can_evaluate(string):
try:
eval(string)
return True
except SyntaxError:
return False
但是,如果可以评估字符串,则会产生执行评估的副作用。