Function inside function - every time?

∥☆過路亽.° 提交于 2019-12-01 02:07:29

You can check the bytecode with the dis module:

>>> import dis
>>> def my_function():
...     def little_function():
...             print "Hello, World!"
...     
... 
>>> dis.dis(my_function)
  2           0 LOAD_CONST               1 (<code object little_function at 0xb74ef9f8, file "<stdin>", line 2>)
              3 MAKE_FUNCTION            0
              6 STORE_FAST               0 (little_function)
              9 LOAD_CONST               0 (None)
             12 RETURN_VALUE  

As you can see the code for the inner function is compiled only once. Every time you call my_function it is loaded and a new function object is created(in this sense the def little_function is executed every time my_function is called), but this doesn't add much overhead.

The code in the inner function is compiled only once, so there shouldn't be a significant runtime penalty.

Only inner's function closure gets updated each time the outer function is called. See here, for example, for more details about closures.

Here's a quick demonstration, examining the closure:

def f(x):
   a = []
   b = x + 1
   def g():
      print a, b
   return g

In [28]: y = f(5)

In [29]: y
Out[29]: <function __main__.g>

In [30]: y.func_closure
Out[30]: 
(<cell at 0x101c95948: list object at 0x101c3a3f8>,
 <cell at 0x101c958a0: int object at 0x100311aa0>)

In [31]: y.func_closure[1].cell_contents
Out[31]: 6
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!