3

In python 2.7.5 on mac os-x, i can wrote following lines. My question is that the variable age1 is declared inside an inner block and hence should not be visible in the subsequent outer block. But python compiles and does not complain. If i comment the line age1 = 25, then python complains that the variable age1 is not declared.

In other languages like java/c++, variables declared within a scope (determined by {}) are not visible out side the scope. So my question is what is the purpose of scope in python as determined by indentation.

age = 41
if age >= 41:
 print(">=41")
 age1 = 25 #this is declared inside the scope of print and should not be visible outside
if age1 == 25:
 print("==25")
Jimm
  • 8,165
  • 16
  • 69
  • 118
  • 2
    [Have a look at this](http://stackoverflow.com/questions/2829528/whats-the-scope-of-a-python-variable-declared-in-an-if-statement) – mshsayem Dec 24 '13 at 05:06
  • The simple answer is that, unlike in those other languages, blocks in Python do not create scopes; only functions and classes do. So there is no "purpose" of scope in that sense. Indentation for most constructs only indicates block structure, not variable scope. – BrenBarn Dec 24 '13 at 05:39
  • Related post - [Short Description of the Scoping Rules?](https://stackoverflow.com/q/291978/465053) – RBT Jul 19 '18 at 07:29

1 Answers1

4

Following from this excellent answer, there are only four scopes in Python.

LEGB Rule.

L. Local. (Names assigned in any way within a function (def or lambda)), and not declared global in that function.

E. Enclosing function locals. (Name in the local scope of any and all enclosing functions (def or lambda), form inner to outer.

G. Global (module). Names assigned at the top-level of a module file, or declared global in a def within the file.

B. Built-in (Python). Names preassigned in the built-in names module : open,range,SyntaxError,...

As you can see, based on indentation/control block, python doesn't limit the visibility of the variables.

So, if that code is within a function, then the variable will be visible to all parts of the code within that function, after its creation.

If that code is within a module, then the variable will be visible to all parts of the module, after its creation.

When you try to access a variable, first the local scope will be searched, if not found then the closure scope will be searched, if not found then module scope will be searched, if not found builtin scope will be searched, and if not found error will be thrown.

Check this function now,

def func(x):
    if x == 0: y = 1
    print locals()

func(1)
func(0)

Output

{'x': 1}
{'y': 1, 'x': 0}

In the first case, y is not created and so it is not there in local scope. But in the second case, y is added to the local scope, so, it will be visible to all the code which share the local scope.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497