Reputation: 13
Just a beginner question about local and global scope in python
X = 100
#is X a global variable?.We defined it outside the function scope
def foo():
print(X)
return X
#it prints 100 and even returns it
def foo():
X = X + 10
#local error
#UnboundLocalError: local variable 'X' referenced before assignment
def foo():
global X
# if X is a global variable why specify again?
X = X + 10
return X
Upvotes: 0
Views: 613
Reputation: 1265
global
and nonlocal
are very strange things when I was a beginner.
Just think about it: why do we need them in Python?
It is because we don't need var
, let
and such similar things to declare variables.
Think about Javascript
, it is dynamic script language too and very alike to python, but it needs var
or let
or const
to declare variables.
The most important thing of declaring variables is to determine scope.
So, in Python, our variables have implicit default scope: current scope where they are defined, and if we want to change scope of some variables, we need use global
or nonlocal
explicitly .
All names on the left side of =
mean to define variables.
Before executing code of some certain scope, Python will pre-compute all local variables
, which are those on the left side of =
. This is why you got UnboundLocalError: local variable 'X' referenced before assignment
in:
def foo():
X = X + 10
So, if we look up those names not in defined current scope, just
follow the rules of scope chain: up, up, up and until built_in
.
Remember: scope of any name on the left side of =
is default current scope, and you have to assign it(bind something to it) before referring it.
Upvotes: 1
Reputation: 516
from the python website:
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
this means that you can access a global variable inside a function without a global
keyword. if you want to change it though, you must use the global
keyword beforehand.
Upvotes: 2
Reputation: 1272
To modify global copy of a variable you need the to use the global
keyword, but you don't need global
if you are only accessing that.
Upvotes: 3