Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about Python variable scope

Tags:

python

scope

I came across some code which kind of puzzled me. Here's a minimal example which shows this:

# of course, the ... are not part of the actual code
some_var = {"key1":"value1" ... "keyN":"valueN"}

def some_func():
   v = some_var["key1"]

The code works, but the fact that I can access some_var directly confuses me. The last time I had to write some Python code, I remember having to write some_func like this:

def some_func():
   global some_var
   v = some_var["key1"]

I am using Python 2.7.1 on a Windows 7 PC. Did something change in the 2.7 release that allows for this?

like image 396
Geo Avatar asked Mar 03 '11 17:03

Geo


People also ask

What are the scopes of variables in Python?

The scope of a variable refers to the places that you can see or access a variable. The variable a is therefore said to be local to the function. Put another way, the variable a has local scope. Conversely the variable my_var has global scope.

Does Python care about scope?

Then, Python looks at all enclosing scopes of outer functions from the innermost scope to the outermost scope. If no match is found, then Python looks at the global and built-in scopes. If it can't find the name, then you'll get an error.

Why scope should be used for variable in Python?

In programming languages, variables need to be defined before using them. These variables can only be accessed in the area where they are defined, this is called scope. You can think of this as a block where you can access variables.

Do Python variables go out of scope?

There is actually no block scope in python. Variables may be local (inside of a function) or global (same for the whole scope of the program).


1 Answers

No, you just can't reassign some_var in a local scope. Consider the following:

some_var = {}
def some_func():
    # some_var[5] = 6
    some_var = {1:2}
    some_var[3] = 4
some_func()
print (repr(some_var)) # {}

You'll see the assignment in some_func actually creates a local variable which shadows the global one. Therefore, uncommenting the line would result in an UnboundLocalError - you can't access variables before they're defined.

like image 143
phihag Avatar answered Nov 05 '22 11:11

phihag