Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended way to initialize variable in if block

Tags:

python

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

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

Is the following better practice for the msg variable?

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

I'm aware that I could simplify the above functions to ternary expressions, however there are operations in each if-else block that I've left out.

like image 909
Mark Costello Avatar asked Jan 19 '12 20:01

Mark Costello


People also ask

Can I initialize a variable in an if statement?

If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement.

Which is correct way of variable initialization?

When you declare a variable, you should also initialize it. Two types of variable initialization exist: explicit and implicit. Variables are explicitly initialized if they are assigned a value in the declaration statement. Implicit initialization occurs when variables are assigned a value during processing.

Is it good practice to initialize variables?

It is a good coding practice to initialize variables when you declare them. This will: Give cleaner code. Provide a single place to initialize variables.

Should you always initialize variables in C?

A variable must always be initialized before use. Normally, the compiler gives a warning if a variable is undefined. It is then sufficient to take care of such cases.


2 Answers

Either should be fine but I would probably do:

def foobar():
    msg='bar'
    if foo:
        msg='foo'
    return msg
like image 167
thagorn Avatar answered Oct 17 '22 00:10

thagorn


Just for completeness, here are some one-line alternatives to if/else blocks:

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

The first of those is definitely the most clear, if you don't like the one-liner I would suggest using your second method or thagorn's answer. The bool() call is only necessary in the last one if foo is not already a bool (or 0/1).

Obviously in your example function you could just return this immediately without even using a msg variable:

def foobar():
    return 'foo' if foo else 'bar'
like image 36
Andrew Clark Avatar answered Oct 17 '22 00:10

Andrew Clark