Use global variables in functions

Keywords: Python

How do I create or use global variables in a function?

If you create a global variable in one function, how do you use it in another function? Do I need to store the global variable in the local variable of the function to which I need to access it?

#1 building

With parallel execution, global variables can cause unexpected results if you don't know what happened. This is an example of using global variables in multiprocessing. We can clearly see that each process works with its own copy of variables:

import multiprocessing
import os
import random
import sys
import time

def worker(new_value):
    old_value = get_value()
    set_value(random.randint(1, 99))
    print('pid=[{pid}] '
          'old_value=[{old_value:2}] '
          'new_value=[{new_value:2}] '
          'get_value=[{get_value:2}]'.format(
          pid=str(os.getpid()),
          old_value=old_value,
          new_value=new_value,
          get_value=get_value()))

def get_value():
    global global_variable
    return global_variable

def set_value(new_value):
    global global_variable
    global_variable = new_value

global_variable = -1

print('before set_value(), get_value() = [%s]' % get_value())
set_value(new_value=-2)
print('after  set_value(), get_value() = [%s]' % get_value())

processPool = multiprocessing.Pool(processes=5)
processPool.map(func=worker, iterable=range(15))

Output:

before set_value(), get_value() = [-1]
after  set_value(), get_value() = [-2]
pid=[53970] old_value=[-2] new_value=[ 0] get_value=[23]
pid=[53971] old_value=[-2] new_value=[ 1] get_value=[42]
pid=[53970] old_value=[23] new_value=[ 4] get_value=[50]
pid=[53970] old_value=[50] new_value=[ 6] get_value=[14]
pid=[53971] old_value=[42] new_value=[ 5] get_value=[31]
pid=[53972] old_value=[-2] new_value=[ 2] get_value=[44]
pid=[53973] old_value=[-2] new_value=[ 3] get_value=[94]
pid=[53970] old_value=[14] new_value=[ 7] get_value=[21]
pid=[53971] old_value=[31] new_value=[ 8] get_value=[34]
pid=[53972] old_value=[44] new_value=[ 9] get_value=[59]
pid=[53973] old_value=[94] new_value=[10] get_value=[87]
pid=[53970] old_value=[21] new_value=[11] get_value=[21]
pid=[53971] old_value=[34] new_value=[12] get_value=[82]
pid=[53972] old_value=[59] new_value=[13] get_value=[ 4]
pid=[53973] old_value=[87] new_value=[14] get_value=[70]

#2 building

As it turns out, the answer is always simple.

This is a small sample module with a simple way to display it in the main definition:

def five(enterAnumber,sumation):
    global helper
    helper  = enterAnumber + sumation

def isTheNumber():
    return helper

This is how to display it in the main definition:

import TestPy

def main():
    atest  = TestPy
    atest.five(5,8)
    print(atest.isTheNumber())

if __name__ == '__main__':
    main()

This is the simple code that will execute. I hope it will help you.

#3 building

In addition to the answers that already exist, make them even more confusing:

In Python, variables that are referenced only within functions are implicitly global. If a variable is assigned a new value anywhere in the body of the function, it is assumed to be local. If you assign a new value to a variable within a function, the variable is an implicit local variable, and you need to explicitly declare it as "global.".

Although at first it was a bit surprising, a moment's thought could explain that. On the one hand, global allocation of variables is required to prevent unexpected side effects. On the other hand, if global is required for all global references, you will always use global. You must declare each reference to a component of a built-in function or import module as a global reference. Such confusion would undermine the usefulness of the global declaration in identifying side effects.

Source: What are the rules for local and global variables in Python? .

#4 building

What you are saying is to use this method:

globvar = 5

def f():
    var = globvar
    print(var)

f()  # Prints 5

But a better way is to use global variables like this:

globavar = 5
def f():
    global globvar
    print(globvar)
f()   #prints 5

Both give the same output.

#5 building

You need to reference global variables in each function you want to use.

As follows:

var = "test"

def printGlobalText():
    global var #wWe are telling to explicitly use the global version
    var = "global from printGlobalText fun."
    print "var from printGlobalText: " + var

def printLocalText():
    #We are NOT telling to explicitly use the global version, so we are creating a local variable
    var = "local version from printLocalText fun"
    print "var from printLocalText: " + var

printGlobalText()
printLocalText()
"""
Output Result:
var from printGlobalText: global from printGlobalText fun.
var from printLocalText: local version from printLocalText
[Finished in 0.1s]
"""

Posted by sdaniels on Wed, 04 Dec 2019 23:04:29 -0800