Coming from Swift I'm having a bit of a hard time working with .None type of Python. I have a few functions which might return None
if the object I'm looking for is not found in the array.
Then I have to nest my code as follows:
varA = self.getVariableByName(Variables.varA)
if varA is None:
varB = self.getVariableByName(Variables.varB)
varC = self.getVariableByName(Variables.varC)
if varB is not None and varC is not None:
# Do something with varB and varC
In Swift I used to be able to bind the variables in the if statement
let f = getVariableByName
if f(Variables.varA) == nil, let varB = f(Variables.varB), let varC = f(Variables.varC) {
// Do something with varB and varC
}
What is a more 'pythonic' way of dealing with None
?
The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and !=
In Python, we can use if , if-else, if-elif-else , or switch statements for controlling the program execution. Loops are another way to control execution flow.
If the if-statement is True , the code section under the else clause does not run. The keyword else needs to be on its own line and be at the same indentation level as the if keyword that the else corresponds to. The keyword else needs to be followed by a colon : .
you can use the ":=" operator:
if varB := getVariableByName(Variables.varB):
pass
I believe the nicest way to handle this case is exception handling.
E.g. make self.getVariableByName
raise an Exception if the element is not found. Then you could do:
try:
varA = self.getVariableByName(Variables.varA)
except RuntimeError:
varB = self.getVariableByName(Variables.varB)
varC = self.getVariableByName(Variables.varC)
# do something with varB and varC
to get the equivalent of your Swift example.
If you cannot/do not want to change self.getVariableByName
, the best you can do is:
f = self.getVariableByName
if f(Variables.varA):
varB, varC = f(Variables.varB), f(Variables.varC)
if not (varB is None or varC is None):
# do something with varB and varC
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