【问题标题】:Syntactic sugar for only assign if value is of type仅当值是类型时才分配的语法糖
【发布时间】:2020-01-10 02:40:15
【问题描述】:

我正在寻找这个python代码的语法糖版本:

if isinstance(external_function(x), str):
    y = external_function(x)
else:
    y = other_function(x)

我发现调用 external_function 两次是多余的。但我首先需要检查 external_function 在分配给 y 之前是否返回正确的值类型(即 str)。有没有更优雅的方法来做到这一点?

【问题讨论】:

  • 嗯...只是y = external_function(x) 然后如果不是字符串,if not instance(y, str): y = other_function(x) ?

标签: python python-3.x syntactic-sugar


【解决方案1】:

您可以先评估external_function(x) 并将其分配给y,如果y 不是字符串,则评估other_function(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)

【讨论】:

  • 但是如果对external_function 的调用失败怎么办?有没有办法在没有try: except 的情况下默认为 other_function
  • @AbdelJaidi 不,没有。
【解决方案2】:

你评估external_function(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))

【讨论】:

    猜你喜欢
    • 2013-10-07
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    相关资源
    最近更新 更多