0

What is the difference between a variable that has been scoped using the global keyword in python vs. a globally defined variable?

From my tests there doesn't seem to be any difference. The only real difference I see is that semantically the global keyword can scope a variable to the global level where as globally defining a variable is just that, scoped globally.

My Test:

tmpDict = {}
class functions:
    def dictionary(self):
        global my_dict 
        my_dict= {}
        global keys_list 
        keys_list = []
        for i in range(3):
            my_dict.__setitem__(str(i),i)
            tmpDict.__setitem__(str(i),i)
            keys_list.append(str(i))
fun = functions()
fun.dictionary()
print(tmpDict)
print(my_dict)

Test Output: enter image description here

I guess what I'm trying to ask is, If they do the same thing (make a global variable) then why would you ever use the global keyword to do that?

  • 1
    If you have a global scoped variable outside, and if you want to mutate it inside a function scope, you have to use the global keyword - 1 use – Kris Feb 22 '22 at 14:38

1 Answers1

1

Nothing. The global statement does exactly one thing: it makes the following name(s) be treated as if they were in the global scope, rather than the local scope. The only reason you need a declaration for my_dict and not tmpDict is that you assign to the name my_dict in the local scope, which would make it a local variable without the global my_dict.

chepner
  • 497,756
  • 71
  • 530
  • 681