Is it considered bad style to assign values to variables like this?
x = "foobar" or None y = some_variable or None
In the above example, x gets the value 'foobar'.
The base case, x or y returns x if bool(x) evaluates True , else it evaluates y , (see the docs for reference). Therefore, a series of or expressions has the effect of returning the first item that evaluates True , or the last item.
The assignment operator, denoted by the “=” symbol, is the operator that is used to assign values to variables in Python. The line x=1 takes the known value, 1, and assigns that value to the variable with name “x”. After executing this line, this number will be stored into this variable.
1 Answer. Assignment operators: In Python, = is a simple assignment operator to assign values to variable. Let a = 5 and b = 10 assigns the value 5 to a and 10 to b these two assignment statement can also be given as a, b = 5, 10 that assigns the value 5 and 10 on the right to the variables a and b respectively.
|= on Booleans The Python |= operator when applied to two Boolean values A and B performs the logical OR operation A | B and assigns the result to the first operand A . As a result, operand A is False if both A and B are False and True otherwise. What is this?
No, it's a common practice. It's only considered bad style for expressions that are considerably longer than yours.
The primary danger of doing something like this is the possibility that (in the second case) some_variable
is False but not None (the integer 0
, for instance) and you don't want to end up with y
equal to None in that case.
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