0

Is it a good practice to wrap some lines from a function in an inner function, just to avoid repetition with if/else branching?

The general idea is all those lines bar() will be needed multiple times in foo().

In summary my question is: would be good idea to wrap lines in inner function when that inner function only applies to that particular case and wont be used anywhere else even if the code is not trivial inside, what would be other approach if not the case and code will not make much sense declared in separate function?

The duplicate question does not fully encompass all complexity around when to wrap lines in inner functions.

Example:

def foo(arg1, arg2, arg3):

    def bar():
        foo_bar = arg1
        # line of code 1
        # line of code 2
        # line of code 3
        if arg2:
            # line of code 1
            # line of code 2
            # line of code 3
            # line of code 4

    if condition:
        bar()
    elif second_condition:
        if third_condition:
            bar()
Vitaliy Terziev
  • 6,429
  • 3
  • 17
  • 25

0 Answers0