在if语句Python中分配 [英] Assign within if statement Python

查看:166
本文介绍了在if语句Python中分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有比

res = returns_value_or_none(arg)
if res:
    do_something_with(res)

if returns_value_or_none(arg):
    do_something_with(returns_value_or_none(arg))

一个将赋值和如果条件组合成一个语句的那个​​?

One which combines the assignment and if conditional into one statement?

推荐答案

通常,你所拥有的已经是最好的选择。

Often, what you have is already the best option.

你总是可以创建一个新的范围来绑定变量的值:

You can always create a new scope to bind the value to a variable:

(lambda res: do_something_with(res) if res else None)(returns_value_or_none(arg))

但这肯定不会更具可读性,或更多Pythonic。

But that's certainly not going to be more readable, or more Pythonic.

如果你只想保存一行,你可以这样做:

If you just want to save one line, you can do this:

res = returns_value_or_none(arg)
if res: do_something_with(res)

有时更具可读性,但通常它是一个净亏损。

This is sometimes more readable, but usually it's a net loss.

另一种处理此问题的方法是更改​​ do_something_with 接受并且什么也不做。这在Python中并不像在Smalltalk或Swift中那样普遍,但它有时肯定有它的位置。

Another way to deal with this would be to change do_something_with to accept None and do nothing. This isn't as common in Python as it is in, say, Smalltalk or Swift, but it definitely has its place sometimes.

很难看出为什么这样的玩具示例,但是如果你将这些功能调用70次,那么将支票放在功能内的一个地方,而不是在70个地方,无论在哪里,它都是一个明显的胜利。 (特别是因为你可能把它放在68个地方而忘记了其他2个。)

It's hard to see why with a toy example like this, but if you're calling these functions 70 times, putting the check in one place, inside the function, instead of in 70 places, everywhere it's called, is an obvious win. (Especially since you'd probably put it in 68 places and forget the other 2.)

最后但并非最不重要在许多情况下,正确答案是例外。如果你传递,你的 do_something_with 可能已经加注。你肯定可以将 returns_value_or_none 更改为 returns_value_or_raises

Last, but not least, in many cases the right answer is exceptions. Your do_something_with probably already raises if you pass None. And you could surely change returns_value_or_none to returns_value_or_raises.

再次,在这个玩具示例中,它看起来就像更多的代码。但在实际代码中,将整个代码块放在 try / 中除了之外,通常是有意义的,并在最后处理所有错误。或者甚至让异常渗透到更容易处理的更高级别。

Again, in this toy example, it'll just look like more code. But in real-life code, it often makes sense to put a whole block of code inside a try/except, and handle all the errors at once down at the end. Or even to let the exceptions percolate up to a higher level where they're easier to deal with.

当然,这并不适用于所有情况;如果您希望是一个经常且完全合理的响应,并且只想跳过一步而不是中止整个操作链,检查或通过比使用小尝试块乱丢你的代码更有意义。

Of course that isn't appropriate in every case; if you're expecting None to be a frequent and perfectly reasonable response, and just want to skip one step rather than abort the whole chain of operations, checking or passing through None is going to make a lot more sense than littering your code with small try blocks.

这篇关于在if语句Python中分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆