Is there an overhead when nesting functions in Python?

XåpplI'-I0llwlg'I  - picture XåpplI'-I0llwlg'I - · Oct 20, 2011 · Viewed 10.3k times · Source

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 overhead associated with nesting a function within another?

Answer

Raymond Hettinger picture Raymond Hettinger · Oct 20, 2011

The code object is pre-compiled so that part has no overhead. The function object gets built on every invocation -- it binds the function name to the code object, records default variables, etc.

Executive summary: It's not free.

>>> from dis import dis
>>> def foo():
        def bar():
                pass
        return bar

>>> dis(foo)
  2           0 LOAD_CONST               1 (<code object bar at 0x1017e2b30, file "<pyshell#5>", line 2>)
              3 MAKE_FUNCTION            0
              6 STORE_FAST               0 (bar)

  4           9 LOAD_FAST                0 (bar)
             12 RETURN_VALUE