Assign inside an if statement to 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 that combines assignment and if conditionally into one statement?

+1
source share
1 answer

Often, what you have is the best option.


You can always create a new area to bind a value to a variable:

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

But this, of course, will not be more readable or more Pythonic.


If you want to keep 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 a net loss.


Another way to handle this is to change do_something_with to accept None and do nothing. This is not as common in Python as it is, say, Smalltalk or Swift, but sometimes it has its place.

It’s hard to understand why with a similar toy example, but if you call these functions 70 times, placing a check in one place, inside a function, and not in 70 places, wherever he called is obvious to win. (Especially since you probably put it in 68 places and forget the other 2.)


Finally, but not least, in many cases, the correct answer is exceptions. Your do_something_with is probably already rising if you pass None . And you can confidently change returns_value_or_none to returns_value_or_raises .

Again, in this toy example, it will look more like more code. But in real code, it is often advisable to put an entire block of code inside try / except and handle all errors at the end. Or even let exceptions seep to a higher level, which is easier to handle.

Of course, this is not appropriate in every case; if you expect None be a frequent and reasonable answer, and just want to skip one step rather than interrupt the whole chain of operations, checking or going through None will make much more sense than clogging your code with small try blocks.

+2
source

Source: https://habr.com/ru/post/1260482/


All Articles