简体   繁体   English

在 if 语句中赋值 Python

[英]Assign within if statement Python

Is there a simpler alternative than有没有比这更简单的选择

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

or要么

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?一种将赋值和if条件组合到一个语句中的语句?

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

But that's certainly not going to be more readable, or more Pythonic.但这肯定不会更具可读性,或者更像 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.有时更具可读性,但通常是净损失。


Another way to deal with this would be to change do_something_with to accept None and do nothing.解决这个问题的另一种方法是将do_something_with更改为接受None并且什么都不做。 This isn't as common in Python as it is in, say, Smalltalk or Swift, but it definitely has its place sometimes.这在 Python 中并不像在 Smalltalk 或 Swift 中那么常见,但有时它确实有它的位置。

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.很难理解为什么使用这样的玩具示例,但是如果您调用这些函数 70 次,将检查放在函数内部的一个地方,而不是 70 个地方,它被调用的任何地方,显然是一个胜利。 (Especially since you'd probably put it in 68 places and forget the other 2.) (特别是因为您可能会将它放在 68 个位置而忘记了其他 2 个。)


Last, but not least, in many cases the right answer is exceptions.最后但并非最不重要的一点是,在许多情况下,正确的答案是例外。 Your do_something_with probably already raises if you pass None .如果您通过None您的do_something_with可能已经提高了。 And you could surely change returns_value_or_none to returns_value_or_raises .而且您肯定可以将returns_value_or_none更改为returns_value_or_raises

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.但是在现实生活中的代码中,将整个代码块放在try / except通常是有意义的,并在最后一次处理所有错误。 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.如果您期望None是一个频繁且完全合理的响应,并且只想跳过一个步骤而不是中止整个操作链,那么检查或传递None将比将您的代码乱扔垃圾更有意义try块。

For Python 3.8+, PEP 572 introduces Assignment Expressions对于 Python 3.8+, PEP 572引入了赋值表达式

This allows assigning to variables within an expression using the notation NAME := expr .这允许使用符号NAME := expr在表达式中分配变量。 It can be used within if statements, for example:它可以在 if 语句中使用,例如:

if (match := pattern.search(data)) is not None:
    # Do something with match

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM