Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use global variables in python functions? [duplicate]

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

like image 679
stgeorge Avatar asked May 31 '13 20:05

stgeorge


2 Answers

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.
like image 155
Sukrit Kalra Avatar answered Oct 07 '22 22:10

Sukrit Kalra


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.

like image 34
korylprince Avatar answered Oct 07 '22 22:10

korylprince