0

Can someone please explain how python assigned the value below to y. I understand how the function works but I do not understand how the function call a(10) assigns its value y.

def outside(x):
    def inside(y):
        return x ** y
    return inside

a = outside(2)

a(10) 
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
scopa
  • 513
  • 2
  • 8
  • 17

2 Answers2

3

In this code a() is effectively an alias for inside(), with the value of x fixed at 2.

Thus a(10) is essentially inside(10), i.e. the value of y is 10.

Since x is 2 and y is 10, a(10) returns 2 ** 10 (1024).

This type of construct is used extensively in Python decorators. I'd recommend Understanding Python Decorators in 12 Easy Steps! as a nice introduction. Among other things it explains how Python functions are first-class objects and can be assigned to variables, passed as arguments to other functions etc.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • He called his function `inside` not `inner` – Duncan Jan 03 '15 at 12:02
  • Thanks I understand that y is being assigned the value 10. I am not clear on how python accepts a() as an alias. – scopa Jan 03 '15 at 12:07
  • @scopa: Have a read of the decorator tutorial I've linked to in the answer. Perhaps it'll answer some question. – NPE Jan 03 '15 at 12:08
1

What happens, step by step:

  1. You're calling the outside function with x = 2.
  2. outside returns the function inside defined in the context of x being 2.
  3. So now, a contains the function: def inside(y): return 2 ** y
  4. 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
>>>
BartoszKP
  • 34,786
  • 15
  • 102
  • 130