在Python中,如果函数的值不是None,是否有一种干净的方法来返回该值?

发布于 2024-10-29 19:33:53 字数 217 浏览 0 评论 0原文

我发现自己编写了很多类似于以下内容的代码:

ans = call_function()
if ans:
    return ans

...

是否有一种干净的方法可以使其成为 1 或 2 衬垫?这种范式的一个“例子”可能是

if x as call_function():
    return x

I find myself writing a lot of code that resembles the following:

ans = call_function()
if ans:
    return ans

...

Is there a clean way to make this a 1 or 2 liner? An "example" of such a paradigm might be

if x as call_function():
    return x

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

欲拥i 2024-11-05 19:33:53

似乎只要 ans 不是 None,您就可以根据您隐含的用法返回它。

if ans is not None:
    return ans

It seems that as long as ans is not None, you can just return it, based on your implied usage.

if ans is not None:
    return ans
荆棘i 2024-11-05 19:33:53

我不确定您在 if 之后做什么,但也许您正在执行以下操作:

ans = call_function()
if ans:
    return ans
else:
    return default

在这种情况下,您可以简单地执行以下操作:

return call_function() or default

I'm not sure what you're doing after your if, but perhaps you're doing the following:

ans = call_function()
if ans:
    return ans
else:
    return default

In which case it you can simply do:

return call_function() or default
蘸点软妹酱 2024-11-05 19:33:53

将 if 语句后面的代码重构为另一个函数可能是有意义的。有一种(并非不明智的)思想流派强调让每个函数做一件非常具体的事情。

在这种情况下,您可以编写如下内容:

ans = call_function()
return ans if ans is not None else following_code()

或者,如果您确实正在测试真值(而不是专门测试 not None):

return call_function() or following_code()

not None 中在这种情况下,您仍然可以通过编写如下函数来避免分配给临时变量 ans:

def fallback(test_value, routine, *args, **kwargs):
    return test_value if test_value is not None else routine(*args, **kwargs)

然后像这样使用它:

return fallback(call_function(), following_code,
                arg_to_following_code, following_code_kwarg=keywordarg_value)

如果您非常频繁地执行此类操作,这可能会很有用,但是一般来说,它只会让你的代码更难阅读,因为人们不会熟悉你的 fallback 函数。您的问题中使用的原始形式很庞大,但它具有人们习惯看到的易于识别的形状。它还以一种非常谨慎的方式做事,每行一个逻辑操作,就像 Python 中的规范一样。

另一方面,最好删除无关的局部变量,因为这些变量可能会因拼写错误或范围混淆而导致错误。

It may make sense to refactor the code which would follow your if statement into another function. There is a (not unwise) school of thought which emphasizes making each function do one very specific thing.

In this case, you could write something like this:

ans = call_function()
return ans if ans is not None else following_code()

or, if you are really testing for a truthy value (rather than specifically testing for not None):

return call_function() or following_code()

In the not None case, you can still avoid assigning to the temp variable ans by writing a function like this:

def fallback(test_value, routine, *args, **kwargs):
    return test_value if test_value is not None else routine(*args, **kwargs)

and then using it like this:

return fallback(call_function(), following_code,
                arg_to_following_code, following_code_kwarg=keywordarg_value)

This might be useful if you're doing this sort of thing very frequently, but in general it will just make your code a bit harder to read, because people will not be familiar with your fallback function. The original form used in your question is bulky, but it has a readily recognizable shape that people will be used to seeing. It also does things in a very measured fashion, one logical action per line, as is the norm in Python.

On the other hand, it can be good to cut out extraneous local variables, since these can lead to bugs due to typos or confusion about scope.

眼眸印温柔 2024-11-05 19:33:53

想要在语句中嵌入分配可能是我们看到Python的更常见的功能请求之一。问题在于,此类嵌入式作业建议通常仅适用于您要存储的非常有限的情况,您要检查的条件是相同的(例如,您的示例属于该陷阱,并且将是如果您需要检查更具体的条件,例如,如果ANS不是没有:)。

如果额外的行确实冒犯了您,则 can 如果语句向单线语句()(如果ANS:返回ANS)。不过,很多人讨厌这种风格。

但是,我质疑您的基本前提:“我想知道此功能是否返回有意义的东西,如果是这样,那也是此功能的结果,否则我会倒下并以其他方式计算我的结果” t足够的理由使用适当的局部变量。

知道另一个功能是否已经完成了这份工作,这对我来说听起来很重要。

Wanting to embed assignments in if statements is probably one of the more common feature requests we see for Python. The problem is that such embedded assignment proposals typically only work for the very limited cases where the value you want to store and the condition you want to check are identical (e.g. your example falls into that trap and would be useless if you instead needed to check a more specific condition like if ans is not None:).

If the extra line really offends you, you can collapse the if statement to a one-liner (if ans: return ans). A lot of people hate that style, though.

However, I question your basic premise that "I want to know if this function returns something meaningful, and if it is, then that is the result of this function as well, otherwise I will fall back and calculate my result some other way" isn't sufficient justification for using a properly scoped local variable.

Knowing whether or not another function has finished the job for you sounds pretty damn important to me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文