4
flist = []

for i in range(3):
    def func(x): return x * i
    flist.append(func)

for f in flist:
    print(f(2))

The above code prints 4 4 4

I understand that this is python closure and late binding concept.

Under the hood - the function is an object. Since the last value of i gets assigned to every function, does this mean that in python the function is a mutable object and that the function's local variable are its attributes?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
variable
  • 8,262
  • 9
  • 95
  • 215
  • 4
    This is an excellent question but you seem to be using Python 2 and that’s probably a very bad idea: it’s no longer maintained and wholly superseded by Python 3. Unless you’re working inside a legacy project that’s tied to Python 2, there’s no reason to be using Python 2. – Konrad Rudolph Jun 11 '21 at 09:59
  • Arguments aren't attributes of a function -- that would mean recursive calls to a function wouldn't work (and neither would calls of the function from multiple threads). Arguments go on the stack (in cpython) and are accessed that way. – Paul Hankin Jun 11 '21 at 09:59
  • 4
    Nothing gets assigned to the function at all. When called, the function looks up variable `i` from the nearest applicable scope, and there's only one, and it contains `2` at that time. – deceze Jun 11 '21 at 10:00
  • 2
    @KonradRudolph - I have now changed the xrange to range. – variable Jun 11 '21 at 10:01
  • 3
    @an4s911 *"In the loop the function is defined thrice with values of `i` as `0`, `1` and at last `2`."* — This may just be misleading or plain wrong, but the function isn't defined with any value for `i`. The function is simply defined as "use value of `i`". That variable and its value is only looked up at calltime, it's not bound to the function in any way. You can do `def func(): return z`, where `z` doesn't exist, and it can still be defined just fine. You'll just get an error *at calltime*. – deceze Jun 11 '21 at 10:38
  • @deceze Oh, thanks. I will just delete it then. – an4s911 Jun 11 '21 at 11:28

0 Answers0