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.
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.
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.
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.
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.
Either should be fine but I would probably do:
def foobar():
msg='bar'
if foo:
msg='foo'
return msg
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With