[英]How to check type of str that can be evaluated Python
有沒有一種方法可以檢查可以評估的字符串類型?
例:
y = 2
x = 2
z = "y + x"
eval(z)
因此可以評估變量z 。 很好,但是在那里,所以當我在z上調用isinstance時,它將返回函數而不是str。
或者,如果可以,我可以檢查是否可以評估某些內容?
您確定要在這里輸入字符串嗎?
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)
或者,如果您真的想被黑客入侵(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()
我想到的解決方案是:
def can_evaluate(string):
try:
eval(string)
return True
except SyntaxError:
return False
但是,如果可以評估字符串,則具有執行評估的副作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.