[Tutor] Why define a function inside a function?

Ryan Smith ryan at allwegot.net
Sat Jan 30 10:54:18 EST 2016


Thank you to both you and Ben for taking the time and answering my
question! The detailed explanation of the example code I provided
really helped and made things clear. As did the explanations about
closures and a simplified example. I definitely have a lot to learn,
but this was very educational nonetheless.





On Fri, Jan 29, 2016 at 10:38 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list