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?
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With