Either should be fine but I would probably do:
def foobar():
msg='bar'
if foo:
msg='foo'
return msg
Answer from thagorn on Stack OverflowEither 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'
So I've written a few things that work pretty well (including some django apps) , but trying to start to get into trying to be more efficient, or do things "more correctly". I often have a script that passes variables around and they get called through various functions etc. One of the things I often run across is when trying to use a variable later on, or something that's not called until later, is "variable used before being initialized" or something to that effect. So at the beginning of my programs I always have a list of variables just initialized empty, so they can be used later.
e.g.:a=''b=''c=''
etc...
Not a huge deal, but I feel like when I am at the point where I might have now 20 of those in a list at the beginning of a script, there's a better or more pythonic way that should be done? But I'm not sure what that might be. What's a better way to initialize multiple variables through a program or script?
Python: Initialize variable in expression of if condition - Stack Overflow
python - Variable initialization inside if statement - Stack Overflow
Define variable within elif statement
Python: Initialize a variable into if - Stack Overflow
Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.
(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)
Yes, they're in the same "local scope", and actually code like this is common in Python:
if condition:
x = 'something'
else:
x = 'something else'
use(x)
Note that x isn't declared or initialized before the condition, like it would be in C or Java, for example.
In other words, Python does not have block-level scopes. Be careful, though, with examples such as
if False:
x = 3
print(x)
which would clearly raise a NameError exception.
Python also has a very useful if syntax pattern which you can use here
message = get_other_message() if optional_var else get_message()
Or if you want to compare strictly with None
message = get_other_message() if optional_var is not None else get_message()
Unlike with example 1) you posted this doesn't call get_message() unnecessarily.
In general second approach is better and more generic because it doesn't involve calling get_message unconditionally. Which may be ok if that function is not resource incentive but consider a search function
def search(engine):
results = get_from_google()
if engine == 'bing':
results = get_from_bing()
obviously this is not good, i can't think of such bad scenario for second case, so basically a approach which goes thru all options and finally does the default is best e.g.
def search(engine):
if engine == 'bing':
results = get_from_bing()
else:
results = get_from_google()