Python 仅当值的类型为时,用于赋值的语法糖
我正在寻找此python代码的语法糖版本:Python 仅当值的类型为时,用于赋值的语法糖,python,python-3.x,syntactic-sugar,Python,Python 3.x,Syntactic Sugar,我正在寻找此python代码的语法糖版本: 如果isinstance(外部_函数(x),str): y=外部_函数(x) 其他: y=其他_函数(x) 我发现调用外部函数两次是多余的。但在赋值给y之前,我首先需要检查external_函数是否返回正确的值类型(即str)。有更优雅的方法吗?您可以先计算外部函数(x)并将其分配给y,如果y不是字符串,则计算其他函数(x)并将其分配给y: y = external_function(x) if not isinstance(y, str):
如果isinstance(外部_函数(x),str):
y=外部_函数(x)
其他:
y=其他_函数(x)
我发现调用外部函数两次是多余的。但在赋值给y之前,我首先需要检查external_函数是否返回正确的值类型(即str)。有更优雅的方法吗?您可以先计算
外部函数(x)
并将其分配给y
,如果y
不是字符串,则计算其他函数(x)
并将其分配给y
:
y = external_function(x)
if not isinstance(y, str):
y = other_function(x)
您还可以将上述内容作为三元条件写入:
y = external_function(x)
y = y if isinstance(y, str) else other_function(x)
您对外部函数(x)求值两次,您可以这样防止:
y = external_function(x)
if not isinstance(y, str):
y = other_function(x)
如果你想要语法糖,你必须自己写,我不知道有什么内置的东西比这更容易
给你:
def function_chooser(fn_normal, fn_emergency, expected_type):
def internal(x):
try:
result = fn_normal(x)
if not isinstance(result, expected_type):
return fn_emergency(x)
return result
except:
return fn_emergency(x)
return internal
x = 10
# auto_func is now a funcion that calls external_function and
# falls back to internal_function if it doesn't return a string
# or throws an error
auto_func = function_chooser(external_function, internal_function, str)
# It can be use just as any function, as it is one.
print(auto_func(x))
嗯。。。只要
y=external\u函数(x)
如果它不是一个字符串,如果不是实例(y,str):y=other\u函数(x)
?但是如果调用external\u函数失败怎么办?有没有办法不用试试就默认使用其他函数:除了@AbdelJaidi没有,没有。