mercredi 16 janvier 2019

Conditional Function Definition Best Practise

My coworker and I have been talking about some code that he wrote in a pull request. It involves defining a function within each branch of a conditional statement.

Original:
if is_something:
    def do_thing():
        return 'x'
else:
    def do_thing():
        return 'y'

while True:
    # other code here
    foo = do_thing()

My first thought was to shift the conditional into the function definition and use it like that, but that does mean the condition is needlessly evaluated for every loop. My second thought was to define two different functions (with different names), then in a conditional to assign the correct function to a variable which is then later called in the loop.

Option 2:
def thing_x():
    return 'x'

def thing_y():
    return 'y'

if is_something:
    thing_func = thing_x
else:
    thing_func = thing_y

while True:
    # other code here
    foo = thing_func()

I like this version better, but I can't articulate why I like this version better.

Is there any practical reason for one or the other, or is it just a "pick one" situation?

Aucun commentaire:

Enregistrer un commentaire