20

How do I set a global variable inside of a python function?

Kara
  • 6,115
  • 16
  • 50
  • 57
stgeorge
  • 483
  • 3
  • 7
  • 16

7 Answers7

26

To use global variables inside a function, you need to do global <varName> inside the function, like so.

testVar = 0

def testFunc():
    global testVar
    testVar += 1

print testVar
testFunc()
print testVar

gives the output

>>> 
0
1

Keep in mind, that you only need to declare them global inside the function if you want to do assignments / change them. global is not needed for printing and accessing.

You can do,

def testFunc2():
    print testVar

without declaring it global as we did in the first function and it'll still give the value all right.

Using a list as an example, you cannot assign a list without declaring it global but you can call it's methods and change the list. Like follows.

testVar = []
def testFunc1():
    testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.

def testFunc2():
    global testVar
    testVar = [2] # Will change the global variable.

def testFunc3():
    testVar.append(2) # Will change the global variable.
Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71
  • Hi Sukrit. Thank you for the reply. I am confused about that last part ("Using a list as an example, you cannot assign a list without declaring it global but you can call it's methods and change the list. Like follows.") and it's third part. Isn't using a list method mean that you are changing a variable that is out of the function scope, and further more you did not "assign" it to be global in the scope of the function? How can that be possible? – stgeorge May 31 '13 at 20:30
  • That was just an extra part, if you wanted to work around with using `list` as a global variable, it is one of the things you can keep in mind, you could call methods of a global variable in a function without ever declaring it `global`, like `testFunc3`does. But, if you want to assign something to a `global` variable, you need to declare it `global` in the function like `testFunc2` does. – Sukrit Kalra May 31 '13 at 20:34
  • @stgeorge - Yes, it is in fact changing the list, and you are right in what you say, that is why I put this example in the answer, so you can be aware of it. As to why this was allowed, I'm not quite sure. – Sukrit Kalra May 31 '13 at 20:36
  • Cheers. I come from a JS background so this is an interesting concept to me. What I do not understand is why `global foo` and the expression are on 2 different lines? How come `global foo = input()` not valid? This is what landed me on this question. – Memj Jun 24 '17 at 12:54
2

Consider the following code:

a = 1

def f():
    # uses global because it hasn't been rebound
    print 'f: ',a

def g():
    # variable is rebound so global a isn't touched
    a = 2
    print 'g: ',a

def h():
    # specify that the a we want is the global variable
    global a
    a = 3
    print 'h: ',a

print 'global: ',a
f()
print 'global: ',a
g()
print 'global: ',a
h()
print 'global: ',a

Output:

global:  1
f:  1
global:  1
g:  2
global:  1
h:  3
global:  3

Basically you use a global variable when you need every function to access the same variable (object). This isn't always the best way though.

korylprince
  • 2,969
  • 1
  • 18
  • 27
2

A global can be accessed by any function, but it can only be modified if you explicitly declare it with the 'global' keyword inside the function. Take, for example, a function that implements a counter. You could do it with global variables like this:

count = 0

def funct():
    global count
    count += 1
    return count

print funct() # prints 1
a = funct() # a = 2
print funct() # prints 3
print a # prints 2

print count # prints 3

Now, this is all fine and good, but it is generally not a good idea to use global variables for anything except constants. You could have an alternate implementation using closures, which would avoid polluting the namespace and be much cleaner:

def initCounter():
    count = 0
    def incrementCounter():
        count += 1
        return count

    #notice how you're returning the function with no parentheses 
    #so you return a function instead of a value
    return incrementCounter 

myFunct = initCounter()
print myFunct() # prints 1
a = myFunct() # a = 2
print myFunct() # prints 3
print a # prints 2

print count # raises an error! 
            # So you can use count for something else if needed!
James
  • 2,635
  • 5
  • 23
  • 30
1

Explicit declaration by using global <variable name> inside a function should help

vladfau
  • 1,003
  • 11
  • 22
1

In the example below we have a variable c defined outside of any other function. In foo we also declare a c, increment it, and print it out. You can see that repeatedly calling foo() will yield the same result over and over again, because the c in foo is local in scope to the function.

In bar, however, the keyword global is added before c. Now the variable c references any variable c defined in the global scope (ie. our c = 1 instance defined before the functions). Calling bar repeatedly updates the global c instead of one scoped locally.

>>> c = 1
>>> def foo():
...     c = 0
...     c += 1
...     print c
...
>>> def bar():
...     global c
...     c += 1
...     print c
...
>>> foo()
1
>>> foo()
1
>>> foo()
1
>>> bar()
2
>>> bar()
3
sberry
  • 128,281
  • 18
  • 138
  • 165
0

A normal variable is only usable inside of a function, a global variable can be called for outside the function, but don't use this if you don't need to, it can create errors and big programming companies consider this a rookie thing to do.

Fox
  • 1
  • 4
0

I've grappled with the same question / misunderstood what I wanted for a few days, and I think what you may be trying to accomplish is have a function output a result, that can be used after the function finishes running.

The way you can accomplish above is by using return "some result", and then assigning that to a variable after a function. Here's an example below:

#function
def test_f(x):
    y = x + 2
    return y

#execute function, and assign result as another variable
var = test_f(3)
#can use the output of test_f()!
print var      #returns 5
print var + 3  #returns 8
FlyingZebra1
  • 1,285
  • 1
  • 18
  • 28