In javascript, foo = x || "default" is often coded. If x = null, foo = "default".
In python, is foo = x or "default" correct?
In javascript, foo = x || "default" is often coded. If x = null, foo = "default".
In python, is foo = x or "default" correct?
Your code as written will produce the behavior you describe, but I would suggest the following, which is the Python canonical form of a ternary expression
>>> x = None
>>> foo = x if x else 'default'
>>> foo
'default'
If you are familiar with C++, you can read the above as if it were the below ternary expression
foo = x ? x : "default";
Yes, it works. From documentation -
The expression
x and yfirst evaluatesx; ifxisfalse, its value is returned; otherwise,yis evaluated and the resulting value is returned.The expression
x or yfirst evaluatesx; if x istrue, its value is returned; otherwise,yis evaluated and the resulting value is returned.(Note that neither
andnororrestrict the value and type they return toFalseandTrue, but rather return the last evaluated argument. This is sometimes useful, e.g., ifsis a string that should be replaced by a default value if it is empty, the expressions or 'foo'yields the desired value.
(Emphasis mine)
Please note when you do -
foo = x or "default"
if x is None or empty string, in both cases "default" would be the return value of the expression - x or "default" .
It is 'correct'/valid code (as long as x is defined), but bear in mind that foo will be set to "default" for any falsy value such as 0, "", [] or {}.
If you only want to use the default value if x is not None, you can use:
foo = x if x is not None else "default"
This is demonstrated below.
x = 0
print(x if x is not None else "default") # prints 0
print(x or "default") # prints default
If you are defining a function, you will probably just want to use default parameters.
Again, demonstrated below:
def myfunc(x="default"):
print(x)
myfunc() # prints default
myfunc("custom value") # prints custom value
If by "correct", you mean "does it work?", then yes, it is correct. It works fine and will work as you expect it to. Note, however, that if x is something like False, 0, None, or "", foo will also be set to default due to the way boolean logic works in Python.
If by "correct", you mean "is it correct conventions?", then yes, I would also say it is correct. This is a common pattern that I have seen many developers use throughout several projects. It is also given as an example in the Python documentation.
The code works fine if x is already defined, else you will get an error.
Correct usage:
>>> x= None
>>> foo = x or "default"
>>> foo
'default'
Error case :
>>> foo = x or "default"
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
foo = x or "default"
NameError: name 'x' is not defined