What happens, step by step:
- You're calling the
outside
function with x = 2
.
outside
returns the function inside
defined in the context of x
being 2
.
- So now,
a
contains the function: def inside(y): return 2 ** y
- You're calling
a(10)
, which is, recalling step 3, inside(10)
.
This feature is called Functions as First-Class Objects - it basically means that functions are like class instances, that can hold state, and can be passed in variables and arguments, just like anything else. Note the following example:
>>> def x():
... pass
...
>>> x
<function x at 0x02F91A30> # <-- function's address
>>> type(x)
<type 'function'>
>>>
>>> y = x
>>> type(y)
<type 'function'>
>>> y
<function x at 0x02F91A30> # <-- the same address
>>>