[Tutor] Why define a function inside a function?

Steven D'Aprano steve at pearwood.info
Fri Jan 29 22:38:11 EST 2016


Oops, I screwed up!


On Sat, Jan 30, 2016 at 02:31:09PM +1100, Steven D'Aprano wrote:

> Complicated? Well, a bit. Here's a simpler demonstration of a closure:
> 
> 
> def factory(num):
>     """Factory function that returns a new function that adds 
>     num to whatever it is given."""
>     def adder(x):
>         return x + num


Of course that can't work, because I forgot to return the inner 
function.

def factory(num):
    def adder(x):
        return x + num
    return adder


will work better. Sorry for any confusion.



-- 
Steve


More information about the Tutor mailing list