Home > Mobile >  What is the best way to implement this Python code
What is the best way to implement this Python code

Time:03-08

I have this simple code here:

def myFunction(a: my_enumA, b: my_enumB, c: my_enumC):
  
  if a:
    update_a = update_from_db_a(a=a)
  else:
    update_a = True
  
  if b:
    update_b = update_from_db_b(b=b)
  else:
    update_b = True
  
  if c:
    update_c = update_from_db_c(c=c)
  else:
    update_c = True
    
  if update_a and update_b and update_c:
    return True
  else:
    return False

I'm sure that a design patern exists for this but I don't know the name.

What is the best way Pythonic way to implement it ? Maybe with a design pattern?

CodePudding user response:

You could transform each of your first ifs into a single statement:

# If a is False, value is True
# If a is True, value is update_from_db_a(a=a)
update_a = not a or update_from_db_a(a=a)

Notice that if not a is True (a.k.a a is False) it won't execute the next part of the condition (it won't call update_from_db_a).

Also, your function will return True only if a condition is True, so you could re-write it like this:

# If condition is True, returns True
# If condition is False, returns False
return update_a and update_b and update_c

Resulting code:

def myFunction(a: my_enumA, b: my_enumB, c: my_enumC):
    update_a = not a or update_from_db_a(a=a)
    update_b = not b or update_from_db_b(b=b)
    update_c = not c or update_from_db_c(c=c)
    return update_a and update_b and update_c

CodePudding user response:

You can compress all conditions and pass them to all():

def myFunction(a: my_enumA, b: my_enumB, c: my_enumC):
    return all([
        not a or update_from_db_a(a=a),
        not b or update_from_db_b(b=b),
        not c or update_from_db_c(c=c)
    ])

Be sure to wrap them in an iterable, such as a list, tuple or set, and not in a generator. Otherwise all() will terminate on the first false condition.

  • Related