TransWikia.com

How to include identical if block in multiple functions?

Stack Overflow Asked on November 16, 2021

I’m sorry to ask such a basic question, but what’s the Pythonic way to include the same if block that can conditionally return in multiple functions? Here’s my setup:

def a():
  if bool:
    return 'yeehaw'
  return 'a'

def b():
  if bool:
    return 'yeehaw'
  return 'b'

I’d like to factor the common conditional out of the two functions, but I’m not sure how to do so.

5 Answers

I ended up liking the decorator syntax, as the functions that include the duplicative conditional logic have a good deal else going on in them:

# `function` is the decorated function
# `args` & `kwargs` are the inputs to `function`
def yeehaw(function):
  def decorated(*args, **kwargs):
    if args[0] == 7: return 99 # boolean check
    return function(*args, **kwargs)
  return decorated
    
@yeehaw
def shark(x):
  return str(x)

shark(7)

Answered by duhaime on November 16, 2021

(note: my naming wasn't the best, consider that same_bool function might be better called identical_if_block(...) to follow your example And I am also assuming bool_ is a parameter, though it could work as a global. But not as bool which, like any function object, is always Truthy

>>> bool(bool)
True

)

Use a function, as long as it doesn't need to return falsies.

def same_bool(bool_):
    " works for any result except a Falsy"
    return "yeehaw" if bool_ else None

def a(bool_):
    res = same_bool(bool_)
    if res:
        return res
    return 'a'

def b(bool_, same_bool_func):
    #you can pass in your boolean chunk function
    res = same_bool_func(bool_)
    if res:
        return res
    return 'b'


print ("a(True):", a(True))
print ("a(False):", a(False))
print ("b(True, same_bool):", b(True,same_bool))
print ("b(False, same_bool):", b(False,same_bool))

output:

a(True): yeehaw
a(False): a
b(True, same_bool): yeehaw
b(False, same_bool): b

If you do need falsies, use a special guard value

   def same_bool(bool_):
        " works for any result"
        return False if bool_ else NotImplemented

   def a(bool_):
        res = same_bool(bool_)
        if res is not NotImplemented:
            return res
        return 'a'

You could also feed in "a" and "b" since they are constant results, but I assume that's only in your simplified example.

   def same_bool(bool_, val):
        return "yeehaw" if bool_ else val

   def a(bool_):
        return same_bool(bool_, "a")

Answered by JL Peyret on November 16, 2021

You could use a lambda that takes in a. bool and a default value to return if the condition is false:

check = lambda condition, default: 'yeehaw' if condition else default
def a():
     return check(condition, 'a')

def b():
     return check(condition, 'b')

Answered by Amal K on November 16, 2021

I am new to python but I think you can use a default argument to send a or b based on what is passed to the function.

def a(x='a'):
    if condition: #where condition can be True or False
        return 'yeehaw'
    return x

Answered by Joe Ferndz on November 16, 2021

Use a decorator or closure

def my_yeehaw(result):
  def yeehaw():
    if some_bool:
      return 'yeehaw'
    return result
  return yeehaw

a = my_yeehaw('a')
b = my_yeehaw('b')

Answered by rioV8 on November 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP