Global Variables Can Be Read from a Local Scope [Python]
Consider the following program:
- def spam():
- print(eggs)
- eggs = 42
- spam()
- print(eggs)
Since there is no parameter named eggs or any code that assigns eggs a value in the spam() function, when eggs is used in spam(), Python considers it a reference to the global variable eggs. This is why 42 is printed when the previous program is run.
Local and Global Variables with the Same Name To simplify your life, avoid using local variables that have the same name as a global variable or another local variable. But technically, it’s perfectly legal to do so in Python. To see what happens, type the following code into the file editor and save it as sameName.py:
- def spam():
- eggs = 'spam local'
- print(eggs) # prints 'spam local'
- def bacon():
- eggs = 'bacon local'
- print(eggs) # prints 'bacon local'
- spam()
- print(eggs) # prints 'bacon local'
- eggs = 'global'
- bacon()
- print(eggs) # prints 'global'
bacon localspam localbacon localglobal
There are actually three different variables in this program, but confusingly they are all named eggs. The variables are as follows:
- A variable named eggs that exists in a local scope when spam() is called.
- A variable named eggs that exists in a local scope when bacon() is called.
- A variable named eggs that exists in the global scope.
Since these three separate variables all have the same name, it can be confusing to keep track of which one is being used at any given time. This is why you should avoid using the same variable name in different scopes.
0 Response to "Global Variables Can Be Read from a Local Scope [Python]"
Post a Comment