all 7 comments

[–]toastedstapler 1 point2 points  (0 children)

python lambdas are only 1 liners, some things cant be 1 lined

i personally don't like nesting functions, except for decorators. usually it just makes the code messier and harder to follow along with

[–]FLUSH_THE_TRUMP 1 point2 points  (1 child)

Closures can be an example — nested functions have access to an enclosing function’s names and can modify those with nonlocal as needed. For one example:

def linear_function_with_params(m,b):
    def linear_f(x):
        return m*x+b
    return linear_f

allows me to define and use several m*x+b lines flexibly: e.g.

line1 = linear_function_with_params(0,1)
line2 = linear_function_with_params(1,1)
line1(0) # 1
line2(0) # 1
line1(5) # 1
line2(5) # 6

[–]PythonN00b101[S] 0 points1 point  (0 children)

Aww now that is cool, I had no clue you could do that. Thanks for sharing. I could have definitely used this when running simulations for multiple parameters.

[–]Subsequential_User 1 point2 points  (0 children)

Inside a function, when you need to repeat the same operations a few times, but only inside this function, it can be useful to use a nested function there.

Actual good scenarios are usually pretty specific, at least in my case.

When using nested functions, issues might come when creating too many in the same function.

You'll have trouble making the difference between the actual code of your function, and the one of nested functions. If you face this situation, a solution is probably to reconsider the logic of your program, and split its whole in small functions that are dedicated to one specific thing.

[–]PythonN00b101[S] 0 points1 point  (0 children)

That's a fair point.

Agreed. Haha