How to use shadowing with global variables?

258 views Asked by At

I have notes from class but I am unsure what is actually happening. Other than adding to confusion, what purpose does shadowing allow on to do? I thought the because globalString is a string type it cannot be modified? How do I access the original value? What is an instance of what in memory terms?

globalList = [1,2,3]
globalString = "global"     # can't be modified because it's a string

def updateGlobalString():
    global globalString     # Does line this do anything?
    globalString = "new"

print(globalString)
>>> "global"
updateGlobalString()
>>> "new"

def updateGlobalList():
    globalList.append(4)

print(globalList)
>>> [1,2,3]
updateGlobalList()
print(globalList)
>>> [1,2,3,4]

If python Lists are mutable how does this example change the equation when compared to strings? And just to clarify, are any of these values actual Global?

Thank you.

2

There are 2 answers

0
tox123 On

Global means that variable is going to occur in the global space. So that 1st function deletes the old string in global namespace and replaces it with a new one. However, a list is mutable and as a direct result can be changed outside of the global scope.

0
Daniel Roseman On

Shadowing isn't a technique or a tool, it's something that is simply a consequence of Python's scoping rules.

I'm confused by your question about whether any of the variables are global. Anything declared at module level is global. The global keyword, when used in a non-global scope, allows you to rebind the name to a different object and have that rebinding take effect in the global scope too: otherwise you would simply be defining a new variable in the local scope (which would indeed be shadowing the original variable).