Skip to content
Advertisement

Using an if statement for terminating (return) the function for null conditionals, when is it best to introduce a variable? [closed]

I have an excel file with multiple tags in the format of key-value pairs. I want to perform some tasks using the value of each tag only when a key has a value. When is it best to introduce a variable for storing the value? In advance or right after the check of the value that actually exists, and won’t exit the function immediately, thus there is a meaning to reserve space for that? Note, that this function will run hundreds of times scanning multiple tags in that file.

def getValue(file):
   if (file.myValue == ""):
      return "Empty string"
   myVal = file.myValue
   # now do stuff using the variable `myVal` that I have just declared/initialised
   # ...

OR

def getValue(file):
   myVal = file.myValue
   if (myVal == ""):
      return "Empty string"

   # do stuff using the variable `myVal` I have already declared/initialized in advance
   # ...

Advertisement

Answer

In Python >= 3.8, you can use a named assignment to avoid that pattern:

def getValue(file):
    if (myVal := file.myValue) == "":
        return "Empty string"
    # do stuff with myVal

Otherwise I’d do the assignment first:

def getValue(file):
    myVal = file.myValue
    if myVal == "":
        return "Empty string"

It may not make a difference in terms of performance (minute, if anything), but it reduces code length with no cost to readability.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement