I am familar in c/c++ amd new to python and I am wondering what is the need for nested functions in python. Can anyone give a live example where we use nested functions. Thanks in advance.
Asked
Active
Viewed 94 times
2 Answers
4
Your question is too broad, and is therefore likely to be closed, but two examples are Decorators and Closures.
3
When you want to use helper functions (and you don't want to supply arguments), especially with threads:
import Tkinter as tk
import thread
def main():
root = tk.Tk()
progress_var = tk.StringVar(root)
progress_var.set('')
progress = tk.Label(root, textvariable = progress_var)
progress.pack()
def thread_helper(): # this can access the local variables in main()
total = 10000000
for i in xrange(1, total + 1):
progress_var.set('Progress: {}%'.format(100 * float(i)/total))
thread.start_new_thread(thread_helper, ())
root.mainloop()
What this essentially does is show the progress of the for
loop in a window. After the root.mainloop()
, no processes will run, so I need to use a thread to actually initiate the for
loop, and update the progress display.
The thread requires a function to be called, and it is much easier to just define a helper function (which is nested and only used once) rather than create a new function and pass it various arguments.

Rushy Panchal
- 16,979
- 16
- 61
- 94