0

I am confused about the scope of python variables. How is this working

Consider the following example

i = 12
if i==12 :
    str = "is equal"
else:
    str = "NOT"
print str  //Prints is equal - recognized the string str

The variable str is only in the scope of if statement and its scope is lost at the else statement. Since there is no hoisting in python. I am confused how this example works.I read this post and it states that Variables are scoped in the Following order

1-L (local variables are given preference)

2-E (Enclosing variables)

3-G (Global variables)

4-B (Builtin)

My question is what is the difference between Enclosing variable and local variable ?

Community
  • 1
  • 1
James Franco
  • 4,516
  • 10
  • 38
  • 80

2 Answers2

4

The variable str is only in the scope of if statement and its scope is lost at the else statement.

Nope. Python is function scoped, not block scoped. Entering an if block doesn't create a new scope, so the str variable is still in scope for the print.

Enclosing variables are variables from functions enclosing a given function. They occur when you have closures:

def f():
    x = 3
    def g():
        print x  # enclosing variable
    g()
user2357112
  • 260,549
  • 28
  • 431
  • 505
1

Python doesn't have general block scope for, only function scope (with some additional weirdness for cases like class declarations). Any name assigned within a function will remain valid for the life of the function.

Enclosing scope applies when nesting function declarations, e.g.:

def foo(a):
    def bar(b):
        return a + b
    return bar

So in this case, foo(1)(2) will create a bar whose enclosing scope is a foo call with a == 1, then call bar(2), which will see a as 1.

Enclosing scope also applies to lambda functions; they can read variables available in the scope surrounding the point where lambda was used, so for something like this:

 val_to_key = {...}  # Some dictionary mapping values to sort key values
 mylist.sort(key=lambda x: val_to_key[x])

val_to_key is available; it wouldn't be in scope inside the sort function, but the lambda function binds the enclosing scope at declaration time and can therefore use val_to_key.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271