[Tutor] Why define a function inside a function?

Ryan Smith ryan at allwegot.net
Fri Jan 29 16:29:14 EST 2016


Hi all,

I am new to programming and python and had a question. I hope I
articulate this well enough so here it goes... I was following along
on a thread on this mailing list discussing how to test file I/O
operations. In one of the suggested solutions the following code was
used:


def _open_as_stringio(self, filename):
        filelike = StringIO(self.filecontents[filename])
        real_close = filelike.close
        def wrapped_close():
            self.filecontents[filename] = filelike.getvalue()
            real_close()
        filelike.close = wrapped_close
        return filelike

In trying to understand the logic behind the code for my own
edification, I was wondering what is the reasoning of defining a
function in side another function (for lack of a better phrase)?


More information about the Tutor mailing list