0

why is the scope different for int and list in Python? Below is my example

#!/usr/bin/python

class Foo:
    def method(self):
        l = []
        i = 0
        def method1():
            l.append(1)
            i =  i + 1 <<<<<< Throws exception
        method1()
    Foo().method()

In the above example, I can access the list l inside my method1 function but not the integer i. Any possible explanation?

I referred to the below link, but it had no explanation about the above scenario.

Short description of the scoping rules?

Tonechas
  • 13,398
  • 16
  • 46
  • 80
night_hawk
  • 101
  • 1
  • 6
  • 2
    Because you're assigning to `i` (but not to `l`) inside `method1`. If you assign to a variable in a function, the variable is local to the function unless you specify otherwise. – khelwood Apr 30 '20 at 07:59
  • Yup, any variable that is assigned inside a function is local by default. – user2390182 Apr 30 '20 at 08:00

1 Answers1

0

As @khelwood already answered in comment section it's assignment thing. You refer to list, but assign an int. If you refer to int it will also work as list:

class Foo:
    def method(self):
        l = []
        i = 0
        def method1():
            l.append(1)
            m = i + 1
            print(m)
        method1()
Foo().method()
Maks
  • 1,527
  • 1
  • 13
  • 16