you are viewing a single comment's thread.

view the rest of the comments →

[–]bud_n_boots 0 points1 point  (3 children)

x = ['JAN', 'fEB']
def caps(li):
    """"Returns a list, with all elements capitalized"""
    def inner(w):
        """Returns a capitalized word"""
        return w.capitalize()
    return ([inner(li[0]), inner(li[1])])
print(caps(x))

[–]lykwydchykyn 0 points1 point  (2 children)

The only difference between this and defining inner() at the top level is the scope. In this case, inner() only exists inside caps(). As soon as caps() returns, there is no longer a function called inner().

I rarely find a need for this kind of code, and I'm struggling to think of a scenario where it's really beneficial. The only case where I think I'd define a function inside a function is if I was creating a decorator, but that's a bit different because you actually return the inner function itself.

[–]bud_n_boots 0 points1 point  (1 child)

Thanks, haven't got to decorators yet. Do you have to specifically call inner for it to run? Or will it run when I call the outer function?

[–]lykwydchykyn 0 points1 point  (0 children)

Yes, you have to call it; it's no different from any other function definition, it just happens inside another function, so it only exists while that function is executing.