Recommended way to initialize a variable in if block

I have the following code (minus some other operations):

def foobar(): msg=None if foo: msg='foo' else: msg='bar' return msg 

What is the next best practice for the msg variable?

 def foobar(): if foo: msg='foo' else: msg='bar' return msg 

I know that I could simplify the above functions for ternary expressions, however there are operations in every if-else block.

+6
source share
7 answers

Either should be fine, but I would probably do:

 def foobar(): msg='bar' if foo: msg='foo' return msg 
+5
source

Just for completeness, here are a few single-line if / else block alternatives:

 msg = 'foo' if foo else 'bar' msg = foo and 'foo' or 'bar' msg = ('bar', 'foo')[bool(foo)] 

The first one is by far the clearest, if you don't like the single line font, I would suggest using your second method or thagorn's answer. A call to bool() is only necessary in the latter case, if foo no longer bool (or 0/1).

Obviously, in your example function, you can simply return this immediately without even using the msg variable:

 def foobar(): return 'foo' if foo else 'bar' 
+4
source

In Python, there is no particular advantage to initializing over conditional, as in the first example. You just need to make sure the variable is initialized before it returns. This assumes (based on your examples) that you are using the "single exit" paradigm. In some cases, in Python, this works, but in other cases, you get cleaner code, leaving early when possible.

 def earlyReturn(mycheck): if not mycheck: return 'You forgot something.' # code here if the test passes without needing an extra level of indentation. 
+3
source

I understand that some things have not been taken into account, but if you really do not need to manipulate msg, I think you could just return the intended content without requiring a variable; return 'foo'

+2
source

I would definitely say that later is better. There is no recommendation for Python to initialize variables. Therefore, it should be avoided if it does not add something to the code as a fallback value, or makes the code more readable, which in this case does not work.

Edit: by fallback, I mean the same thing that thagorn and mikebabcock suggested.

+1
source

If what you showed is everything related to msg, then initializing it does nothing for you, and the second solution is better.

0
source

If this is all logic, why not do:

 def foobar(): msg='bar' if foo: msg='foo' return msg 
0
source

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


All Articles