What is the benefit to define a function in a function in python?

后端 未结 3 838
名媛妹妹
名媛妹妹 2021-01-31 03:15

I encountered this piece of python code (pasted below) on effbot and I was wondering:

Why defining a function within a function?

import          


        
相关标签:
3条回答
  • 2021-01-31 03:43

    Often the main reason of such code is function closures. It is powerful thing that is applicable not only to Python. E.g. JavaScript gains a lot from them.

    Some points about closures in Python - closures-in-python.

    0 讨论(0)
  • 2021-01-31 03:48

    Why defining a function within a function?

    To keep it isolated. It's only used in this one place. Why define it more globally when it's used locally?

    0 讨论(0)
  • 2021-01-31 03:57

    It's just another way of breaking down a large function into smaller pieces without polluting the global namespace with another function name. Quite often the inner function isn't a stand-alone so doesn't rightfully belong in the global namespace.

    0 讨论(0)
提交回复
热议问题