By user46646

2009-01-08 05:45:02 8 Comments

How can I create or use a global variable in a function?

If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?


@thomas 2020-05-24 21:41:53

Globals are fine - Except with Multiprocessing

Globals in connection with multiprocessing on different platforms/envrionments as Windows/Mac OS on the one side and Linux on the other are troublesome.

I will show you this with a simple example pointing out a problem which I run into some time ago.

If you want to understand, why things are different on Windows/MacOs and Linux you need to know that, the default mechanism to start a new process on ...

  • Windows/MacOs is 'spawn'
  • Linux is 'fork'

They are different in Memory allocation an initialisation ... (but I don't go into this here).

Let's have a look at the problem/example ...

import multiprocessing

counter = 0

def do(task_id):
    global counter
    counter +=1
    print(f'task {task_id}: counter = {counter}')

if __name__ == '__main__':

    pool = multiprocessing.Pool(processes=4)
    task_ids = list(range(4)), task_ids)


If you run this on Windows (And I suppose on MacOS too), you get the following output ...

task 0: counter = 1
task 1: counter = 2
task 2: counter = 3
task 3: counter = 4


If you run this on Linux, you get the following instead.

task 0: counter = 1
task 1: counter = 1
task 2: counter = 1
task 3: counter = 1

@Aaron Hall 2016-01-01 19:55:14

If I create a global variable in one function, how can I use that variable in another function?

We can create a global with the following function:

def create_global_variable():
    global global_variable # must declare it to be a global first
    # modifications are thus reflected on the module's global scope
    global_variable = 'Foo' 

Writing a function does not actually run its code. So we call the create_global_variable function:

>>> create_global_variable()

Using globals without modification

You can just use it, so long as you don't expect to change which object it points to:

For example,

def use_global_variable():
    return global_variable + '!!!'

and now we can use the global variable:

>>> use_global_variable()

Modification of the global variable from inside a function

To point the global variable at a different object, you are required to use the global keyword again:

def change_global_variable():
    global global_variable
    global_variable = 'Bar'

Note that after writing this function, the code actually changing it has still not run:

>>> use_global_variable()

So after calling the function:

>>> change_global_variable()

we can see that the global variable has been changed. The global_variable name now points to 'Bar':

>>> use_global_variable()

Note that "global" in Python is not truly global - it's only global to the module level. So it is only available to functions written in the modules in which it is global. Functions remember the module in which they are written, so when they are exported into other modules, they still look in the module in which they were created to find global variables.

Local variables with the same name

If you create a local variable with the same name, it will overshadow a global variable:

def use_local_with_same_name_as_global():
    # bad name for a local variable, though.
    global_variable = 'Baz' 
    return global_variable + '!!!'

>>> use_local_with_same_name_as_global()

But using that misnamed local variable does not change the global variable:

>>> use_global_variable()

Note that you should avoid using the local variables with the same names as globals unless you know precisely what you are doing and have a very good reason to do so. I have not yet encountered such a reason.

We get the same behavior in classes

A follow on comment asks:

what to do if I want to create a global variable inside a function inside a class and want to use that variable inside another function inside another class?

Here I demonstrate we get the same behavior in methods as we do in regular functions:

class Foo:
    def foo(self):
        global global_variable
        global_variable = 'Foo'

class Bar:
    def bar(self):
        return global_variable + '!!!'


And now:

>>> Bar().bar()

But I would suggest instead of using global variables you use class attributes, to avoid cluttering the module namespace. Also note we don't use self arguments here - these could be class methods (handy if mutating the class attribute from the usual cls argument) or static methods (no self or cls).

@anonmanx 2020-01-19 14:29:23

Cool, but what to do if I want to create a global variable inside a function inside a class and want to use that variable inside another function inside another class? Kinda stuck here

@Aaron Hall 2020-01-19 14:33:29

@anonmanx I don't know why you're stuck, it's the same behavior in a method as in a regular function. But I'll update my answer with your remark and some demo code, ok?

@anonmanx 2020-01-19 14:44:01

okay, got it. So I will have to explicitly call that function for using that global variable.

@Rafaël Dera 2017-09-05 14:59:14

I'm adding this as I haven't seen it in any of the other answers and it might be useful for someone struggling with something similar. The globals() function returns a mutable global symbol dictionary where you can "magically" make data available for the rest of your code. For example:

from pickle import load
def loaditem(name):
    with open(r"C:\pickle\file\location"+"\{}.dat".format(name), "rb") as openfile:
        globals()[name] = load(openfile)
    return True


from pickle import dump
def dumpfile(name):
    with open(name+".dat", "wb") as outfile:
        dump(globals()[name], outfile)
    return True

Will just let you dump/load variables out of and into the global namespace. Super convenient, no muss, no fuss. Pretty sure it's Python 3 only.

@Kiran Jonnalagadda 2019-05-08 04:53:40

globals() always returns globals available in the local context, so a mutation here may not reflect in another module.

@user5473311 2015-10-24 15:46:18

Following on and as an add on, use a file to contain all global variables all declared locally and then import as:


Stocksin = 300
Prices = []


import initval as iv

def getmystocks(): 
    iv.Stocksin = getstockcount()

def getmycharts():
    for ic in range(iv.Stocksin):

@olibre 2017-05-23 20:21:52

What is the advantage to move the global variables to another file? Is it just to group together the global variables in a tiny file? And why using the statement import ... as ...? Why not just import ...?

@olibre 2017-05-23 20:31:29

Ah... I have finally understood the advantage: No need to use the keyword global :-) => +1 :-) Please edit your answer to clarify these interrogations that other people may also have. Cheers

@gimel 2009-01-08 05:59:04

You may want to explore the notion of namespaces. In Python, the module is the natural place for global data:

Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname.

A specific use of global-in-a-module is described here - How do I share global variables across modules?, and for completeness the contents are shared here:

The canonical way to share information across modules within a single program is to create a special configuration module (often called config or cfg). Just import the configuration module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:


x = 0   # Default value of the 'x' configuration setting


import config
config.x = 1


import config
import mod
print config.x

@vladosaurus 2018-01-02 14:56:30

for a reason I don't like the config.x can I get rid of it? I came with x = lambda: config.x and then I have the new value in x(). for some reason, having a = config.x does not do the trick for me.

@jhylands 2018-12-07 12:15:34

@vladosaurus does from config import x solve that?

@user2876408 2013-10-13 16:07:41

As it turns out the answer is always simple.

Here is a small sample module with a simple way to show it in a main definition:

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

def isTheNumber():
    return helper

Here is how to show it in a main definition:

import TestPy

def main():
    atest  = TestPy

if __name__ == '__main__':

This simple code works just like that, and it will execute. I hope it helps.

@barlop 2013-10-19 18:55:15

thanks, i'm new to python, but know a bit of java. what you said worked for me. and writing global a<ENTER> within the class.. seems to make more sense to me than within a function writing 'global a'.. I notice you can't say global a=4

@swdev 2014-09-18 02:32:06

This is probably the simplest yet very useful python trick for me. I name this module global_vars, and initialize the data in init_global_vars, that being called in the startup script. Then, I simply create accessor method for each defined global var. I hope I can upvote this multiple times! Thanks Peter!

@jtlz2 2015-04-10 10:36:21

What if there are many many global variables and I don't want to have to list them one-by-one after a global statement?

@Sagar Mehta 2015-02-04 19:19:54

Try this:

def x1():
    global x
    x = 6

def x2():
    global x
    x = x+1
    print x

x = 5
x2()  # output --> 7

@gxyd 2014-12-04 06:27:43

What you are saying is to use the method like this:

globvar = 5

def f():
    var = globvar

f()  # Prints 5

But the better way is to use the global variable like this:

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

Both give the same output.

@llewellyn falco 2017-08-19 08:48:27

Reference the class namespace where you want the change to show up.

In this example, runner is using max from the file config. I want my test to change the value of max when runner is using it.


max = 15000


from main import config
def check_threads():
    return max < thread_count 


from main import runner                # <----- 1. add file
from main.runner import check_threads
class RunnerTest(unittest):
   def test_threads(self):
       runner.max = 0                  # <----- 2. set global 

@Martin Thoma 2017-04-07 18:52:13

In case you have a local variable with the same name, you might want to use the globals() function.

globals()['your_global_var'] = 42

@J S 2009-01-08 09:03:33

If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global. You don't have to use it in all cases (as someone here incorrectly claims) - if the name referenced in an expression cannot be found in local scope or scopes in the functions in which this function is defined, it is looked up among global variables.

However, if you assign to a new variable not declared as global in the function, it is implicitly declared as local, and it can overshadow any existing global variable with the same name.

Also, global variables are useful, contrary to some OOP zealots who claim otherwise - especially for smaller scripts, where OOP is overkill.

@Paul Uszak 2019-09-22 22:57:11

Absolutely re. zealots. Most Python users use it for scripting and create little functions to separate out small bits of code.

@Bohdan 2013-10-03 05:41:16

With parallel execution, global variables can cause unexpected results if you don't understand what is happening. Here is an example of using a global variable within multiprocessing. We can clearly see that each process works with its own copy of the variable:

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}] '

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())
print('after  set_value(), get_value() = [%s]' % get_value())

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


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]

@Paul Stephenson 2009-01-08 08:39:44

You can use a global variable in other functions by declaring it as global in each function that assigns to it:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

print_globvar()       # Prints 1

I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global keyword.

See other answers if you want to share a global variable across modules.

@Anthony 2012-12-22 23:22:02

It's extreme exaggeration to refer to globals as "so dangerous." Globals are perfectly fine in every language that has ever existed and ever will exist. They have their place. What you should have said is they can cause issues if you have no clue how to program.

@Fábio Santos 2013-01-22 15:41:05

I think they are fairly dangerous. However in python "global" variables are actually module-level, which solves a lot of issues.

@Nate C-K 2014-09-03 13:48:32

I disagree that the reason Python requires the global keyword is because globals are dangerous. Rather, it's because the language doesn't require you to explicitly declare variables and automatically assumes that a variable that you assign has function scope unless you tell it otherwise. The global keyword is the means that is provided to tell it otherwise.

@Lightness Races in Orbit 2017-11-06 15:03:14

@avgvstvs: And if you're implementing the same program without globals, you still have the same number of code paths. The argument you have made is not one against globals.

@avgvstvs 2017-11-06 15:10:10

@LightnessRacesinOrbit, no you will not. In this context, if you simply added a single boolean to one function in this scenario, then you have 2^4 + 2^3 + 2^3 (32) code paths as opposed to (2^3 + 2^3 + 2^3)^2 (576). And even if you added a fourth parameter to ALL functions, that's 48 code paths as opposed to 576.

@Lightness Races in Orbit 2017-11-06 16:00:32

@avgvstvs: No, because to get the same program semantics, you'd have to have that boolean be passed in by reference (so that changes once more affect all the other functions). The number of code paths is strictly the same (by definition, even) unless you change the program semantics, regardless of how you implement said program.

@avgvstvs 2017-11-06 18:38:49

@LightnessRacesinOrbit I'm not getting your point. If you remove a global variable, you remove the complicating factor in that now, arbitrary functions can no longer alter program state, at various points in execution--thus altering execution in a way that is otherwise imperceptible to other functions relying on that variable. You no longer have to keep track of, "Did f2() change state so now f3() might do something unexpected? The functions can now operate agnostic to external program state.

@Lightness Races in Orbit 2017-11-07 23:59:26

@avgvstvs: If you simply remove the global variable, then your program must have totally different semantics than the original one, so your like-for-like comparison of code path count is immediately rendered invalid. It's as simple as that.

@avgvstvs 2017-11-09 15:46:35

@LightnessRacesinOrbit yes, I AM advocating that you rewrite your programs to avoid global variables, and I disagree that the functional approach to programming is just as complex, especially considering the analysis above where I demonstrate that you can reduce complexity.

@avgvstvs 2017-11-09 15:49:13

My whole point was to demonstrate that global variables introduce unnecessary complexity, and that analysis still stands.

@forumulator 2017-12-24 08:45:50

@avgvstvs I agree with Lightness' point. Possible code paths are defined by the actual code that is written. So if any of the functions were actually interacting with the global variables, then to get an equivalent program without, you'd have to add a shared parameter to be passed to those functions to retain the semantics, which would result in just as many possible code paths.

@Bojan Markovic 2018-02-09 15:46:48

I'd really, really like to see a design where a, say, event-driven system with multiple points of entry (say, a web service) can be designed without a global state, but it doesn't boil down to passing around tons of variables or massive data references (which is hardly a fragrant design). Unless it's just an abstraction over a database (which then, is your global state/SSoT).

@mr3 2018-02-22 23:28:25

@avgvstvs Maybe you're trying to stress the value of limiting the scope of access to data when it makes sense to do so. It's only in likening that to complexity (in terms of code paths) that you're running into technical and people resistance here.

@DylanYoung 2020-01-10 18:07:54

Passing the shared parameter through to all the functions involved still involves a functionally global variable. I would hypothesize that you must change the semantics of the program to remove global state. That said, I don't think it usually reduces complexity (quite the opposite: the reason newbie programmers use global variables is because they are very simple to reason about, barring concurrent access).

@alper 2020-01-30 09:59:47

My main program ( was calling and sets the global variable and returns. Within the program when I recall the already set global variable is seen instead of its initial value, is it the normal case?

@Mohsen Haddadi 2020-05-04 12:47:48

one of the significant benefits of using global is to reduce a large number of parameters from a function which make your code looks neat

@Mike Lampton 2016-01-07 20:41:19

Writing to explicit elements of a global array does not apparently need the global declaration, though writing to it "wholesale" does have that requirement:

import numpy as np

hostValue = 3.14159
hostArray = np.array([2., 3.])
hostMatrix = np.array([[1.0, 0.0],[ 0.0, 1.0]])

def func1():
    global hostValue    # mandatory, else local.
    hostValue = 2.0

def func2():
    global hostValue    # mandatory, else UnboundLocalError.
    hostValue += 1.0

def func3():
    global hostArray    # mandatory, else local.
    hostArray = np.array([14., 15.])

def func4():            # no need for globals
    hostArray[0] = 123.4

def func5():            # no need for globals
    hostArray[1] += 1.0

def func6():            # no need for globals
    hostMatrix[1][1] = 12.

def func7():            # no need for globals
    hostMatrix[0][0] += 0.33

print "After func1(), hostValue = ", hostValue
print "After func2(), hostValue = ", hostValue
print "After func3(), hostArray = ", hostArray
print "After func4(), hostArray = ", hostArray
print "After func5(), hostArray = ", hostArray
print "After func6(), hostMatrix = \n", hostMatrix
print "After func7(), hostMatrix = \n", hostMatrix

@Jeff Shannon 2009-01-08 09:19:55

If I'm understanding your situation correctly, what you're seeing is the result of how Python handles local (function) and global (module) namespaces.

Say you've got a module like this:

myGlobal = 5

def func1():
    myGlobal = 42

def func2():
    print myGlobal


You might expecting this to print 42, but instead it prints 5. As has already been mentioned, if you add a 'global' declaration to func1(), then func2() will print 42.

def func1():
    global myGlobal
    myGlobal = 42

What's going on here is that Python assumes that any name that is assigned to, anywhere within a function, is local to that function unless explicitly told otherwise. If it is only reading from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes (e.g. the module's global scope).

When you assign 42 to the name myGlobal, therefore, Python creates a local variable that shadows the global variable of the same name. That local goes out of scope and is garbage-collected when func1() returns; meanwhile, func2() can never see anything other than the (unmodified) global name. Note that this namespace decision happens at compile time, not at runtime -- if you were to read the value of myGlobal inside func1() before you assign to it, you'd get an UnboundLocalError, because Python has already decided that it must be a local variable but it has not had any value associated with it yet. But by using the 'global' statement, you tell Python that it should look elsewhere for the name instead of assigning to it locally.

(I believe that this behavior originated largely through an optimization of local namespaces -- without this behavior, Python's VM would need to perform at least three name lookups each time a new name is assigned to inside a function (to ensure that the name didn't already exist at module/builtin level), which would significantly slow down a very common operation.)

@watashiSHUN 2015-10-12 22:36:24

You mentioned that the namespace decision happens at compile time, I don't think it is true. from what I learn python's compilation only checks for syntax error, not name error try this example def A(): x+=1, if you don't run it, it will not give UnboundLocalError, please verify thank you

@Vassilis 2018-01-24 11:55:51

It is common to use a capital letter for global variables like MyGlobal = 5

@BlackJack 2018-01-25 17:43:57

@watashiSHUN: The namespace decision does happen at compile time. Deciding that x is local is different from checking at runtime if the local name was bound to a value before it is used the first time.

@BlackJack 2018-01-25 17:46:35

@Vassilis: It is common to upper case all letters: MY_GLOBAL = 5. See the Style Guide for Python Code.

@Mohamed El-Saka 2014-12-20 12:45:26

You need to reference the global variable in every 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

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

@spazm 2015-03-19 23:43:18

'in every function you want to use' is subtly incorrect, should be closer to: 'in every function where you want to update'

@Rauni Lillemets 2014-07-04 10:23:56

In addition to already existing answers and to make this more confusing:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

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

@SingleNegationElimination 2011-07-12 12:35:08

Python uses a simple heuristic to decide which scope it should load a variable from, between local and global. If a variable name appears on the left hand side of an assignment, but is not declared global, it is assumed to be local. If it does not appear on the left hand side of an assignment, it is assumed to be global.

>>> import dis
>>> def foo():
...     global bar
...     baz = 5
...     print bar
...     print baz
...     print quux
>>> dis.disassemble(foo.func_code)
  3           0 LOAD_CONST               1 (5)
              3 STORE_FAST               0 (baz)

  4           6 LOAD_GLOBAL              0 (bar)
              9 PRINT_ITEM          
             10 PRINT_NEWLINE       

  5          11 LOAD_FAST                0 (baz)
             14 PRINT_ITEM          
             15 PRINT_NEWLINE       

  6          16 LOAD_GLOBAL              1 (quux)
             19 PRINT_ITEM          
             20 PRINT_NEWLINE       
             21 LOAD_CONST               0 (None)
             24 RETURN_VALUE        

See how baz, which appears on the left side of an assignment in foo(), is the only LOAD_FAST variable.

@Martijn Pieters 2015-08-08 23:56:44

The heuristic looks for binding operations. Assignment is one such operation, importing another. But the target of a for loop and the name after as in with and except statements also are bound to.

@Robert 2020-02-07 11:17:41

@MartijnPieters For the name after as in an except clause this wasn't obvious to me. But it gets auto-deleted to save memory.

@Martijn Pieters 2020-02-07 11:27:19

@Robert: not to save memory, but to avoid creating a circular reference, which can lead to memory leaks. That's because an exception references a traceback, and the traceback references every local and global namespace along the whole call stack, including the as ... target in the exception handler.

@Kylotan 2009-01-09 11:56:19

You're not actually storing the global in a local variable, just creating a local reference to the same object that your original global reference refers to. Remember that pretty much everything in Python is a name referring to an object, and nothing gets copied in usual operation.

If you didn't have to explicitly specify when an identifier was to refer to a predefined global, then you'd presumably have to explicitly specify when an identifier is a new local variable instead (for example, with something like the 'var' command seen in JavaScript). Since local variables are more common than global variables in any serious and non-trivial system, Python's system makes more sense in most cases.

You could have a language which attempted to guess, using a global variable if it existed or creating a local variable if it didn't. However, that would be very error-prone. For example, importing another module could inadvertently introduce a global variable by that name, changing the behaviour of your program.

Related Questions

Sponsored Content

45 Answered Questions

[SOLVED] How do I merge two dictionaries in a single expression in Python?

13 Answered Questions

[SOLVED] Calling a function of a module by using its name (a string)

  • 2008-08-06 03:36:08
  • ricree
  • 716659 View
  • 1757 Score
  • 13 Answer
  • Tags:   python object

86 Answered Questions

[SOLVED] How do JavaScript closures work?

11 Answered Questions

[SOLVED] How to access environment variable values?

12 Answered Questions

[SOLVED] Iterating over dictionaries using 'for' loops

26 Answered Questions

[SOLVED] What is the scope of variables in JavaScript?

35 Answered Questions

[SOLVED] What's the difference between using "let" and "var"?

34 Answered Questions

[SOLVED] How do I sort a dictionary by value?

17 Answered Questions

[SOLVED] How to make a chain of function decorators?

4 Answered Questions

[SOLVED] Is there a reason for C#'s reuse of the variable in a foreach?

Sponsored Content