20

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

0

7 Answers 7

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.
Sign up to request clarification or add additional context in comments.

4 Comments

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?
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 testFunc3does. But, if you want to assign something to a global variable, you need to declare it global in the function like testFunc2 does.
@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.
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.
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.

Comments

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!

Comments

1

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

Comments

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

Comments

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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.