Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if let syntax in Python

Tags:

python

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?

like image 521
Emptyless Avatar asked Jun 13 '17 12:06

Emptyless


People also ask

What does == mean in Python?

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 !=

What are the three ways of using IF statement in Python?

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.

Why is my IF-ELSE statement not working Python?

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 : .


2 Answers

you can use the ":=" operator:

if varB := getVariableByName(Variables.varB):
    pass
like image 121
luisbunuel Avatar answered Nov 01 '22 16:11

luisbunuel


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
like image 20
Nablezen Avatar answered Nov 01 '22 17:11

Nablezen