I asked previously how the nested functions work, but unfortunately I still don’t quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?
Many thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your question made me curious, so I looked in some real-world code: the Python standard library. I found 67 examples of nested functions. Here are a few, with explanations.
One very simple reason to use a nested function is simply that the function you’re defining doesn’t need to be global, because only the enclosing function uses it. A typical example from Python’s quopri.py standard library module:
Here there was some common code within the
encodefunction, so the author simply factored it out into awritefunction.Another common use for nested functions is
re.sub. Here’s some code from the json/encode.py standard library module:Here
ESCAPEis a regular expression, andESCAPE.sub(replace, s)finds all matches ofESCAPEinsand replaces each one withreplace(match).In fact, any API, like
re.sub, that accepts a function as a parameter can lead to situations where nested functions are convenient. For example, in turtle.py there’s some silly demo code that does this:onclickexpects you to pass an event-handler function, so we define one and pass it in.