global name
name = "Robert"
def f():
print name
f()
print name
and the difference between
name = "Robert"
def f():
print name
f()
print name
How to differentiate between those two snippets
global name
name = "Robert"
def f():
print name
f()
print name
and the difference between
name = "Robert"
def f():
print name
f()
print name
How to differentiate between those two snippets
Variables declared outside functions or classes, are global (inside the module).
global
can be used inside a function/class to be able to modify that variable in the global scope.
There is no reason to use global in this case, and there is no difference between the two pieces of code.
The reason to use global is if you re-assign a variable within a function; but even then you need to use global within that function, not outside.
global
does not declare the variable to be global, it changes where a function looks up the name of a variable that is being assigned to.
Without global
, a local variable is created when it is first assigned a value.
With global
, the name is looked up globally. If it doesn't exist when you assign to it, it is created globally.
(This can be very confusing if you make a typo and accidentally create a new global variable.)
It has no effect in the global scope, because everything's global there.
In other words, your two pieces of code are equivalent.
Here's an example of what it does:
name = "foo"
def f():
name = "bar"
print "In f:", name
def g():
global name
name = "baz"
print "In g:", name
def h():
global mame
mame = "foobar"
print "In h:", mame
print "Globally:", name
f()
print "Globally:", name
g()
print "Globally:", name
h()
print "Globally", name
print "Globally", mame
Output:
Globally: foo
In f: bar
Globally: foo
In g: baz
Globally: baz
In h: foobar
Globally: baz
Globally: foobar