When you state that a variable is global, it does not create it for you (if it doesn't already exist). What does the global statement actually do to the variable? It obviously doesn't merely modify it since it does not have to exist for it to be modified. Once this goes out of scope, can
def foo():
global cat, dog
dog = 1
foo()
print('dog' in globals()) # => True
print(dog) # => 1
print('cat' in globals()) # => False
print(cat) # => NameError
This also raises an error (not surprising):
def foo():
global cat, dog
dog = 1
def bar():
cat = 2
foo()
bar()
print(dog)
print(cat) # => NameError
So obviously the global modifier only works within the scope of the function being executed. Is this, in any way, caused by the garbage collector? Is there some phantom globalizer object that waits for the creation of an object with the given name and gets cleared up upon the end of the function?
globaljust doesn't create the variable. If you check"cat" in globals()inside thefoo(), it will answer false.