在 if 语句中赋值 Python [英] Assign within if statement Python

查看:40
本文介绍了在 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))

将赋值和if条件组合成一个语句?

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))

但这肯定不会更具可读性,或者更具有 Python 风格.

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 更改为接受 None 并且什么都不做.这在 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.)

最后但并非最不重要的一点是,在许多情况下,正确的答案是例外.如果您通过 None,您的 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/except 中通常是有意义的,并在最后一次处理所有错误.或者甚至让异常渗透到更容易处理的更高级别.

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.

当然这并不适用于所有情况;如果您期望 None 是一个频繁且完全合理的响应,并且只想跳过一个步骤而不是中止整个操作链,请检查或通过 None比用小的 try 块乱扔代码更有意义.

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天全站免登陆