Is there an overhead when nesting functions in Python?

前端 未结 6 1813
终归单人心
终归单人心 2020-12-04 23:28

In Python, if I have a child function within a parent function, is the child function \"initialised\" (created) every time the parent function is called? Is there any overhe

6条回答
  •  甜味超标
    2020-12-04 23:53

    Yes, a new object would be created each time. It's likely not an issue unless you have it in a tight loop. Profiling will tell you if it's a problem.

    In [80]: def foo():
       ....:     def bar():
       ....:         pass
       ....:     return bar
       ....: 
    
    In [81]: id(foo())
    Out[81]: 29654024
    
    In [82]: id(foo())
    Out[82]: 29651384
    

提交回复
热议问题