Stack OverflowUsing global variables in a function other than the one that created them
[+956] [13] user46646
[2009-01-08 05:45:02]
[ python scope global-variables variable-scope ]
[ ]

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

(2) thank you this question helped me solve my problem of a variable being used before it was declared. even though it was already declared before the scope of the function in which it was being referenced. - advocate
[+1490] [2009-01-08 08:39:44] Paul Stephenson [ACCEPTED]

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.

(6) The same thing applies to PHP to make sure you're aware they're global - Aram Kocharyan
(179) 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. - Anthony
(46) I think they are fairly dangerous. However in python "global" variables are actually module-level, which solves a lot of issues. - Fábio Santos
(5) @Anthony, "has ever existed and ever will exist", don't you think that statement is kind of broad?! :-D IIRC some languages don't even have globals. - Prof. Falken
(12) I was using hyperbole, but I think my underlying point is still valid. - Anthony
(2) @Anthony - Please supply one case where it's a good idea to use globals in Python. I'm using it right now because I'm just hacking something together, but as soon as I see it working I'll be finding a proper way of passing the argument to my function (or I'll see it doesn't work and give up on having this feature...) I'm personally surprised it's in Python... most of the time it seems like Python doesn't have such constructs and forces you to do things the smart/safe way the first time. - ArtOfWarfare
(14) @ArtOfWarfare Aren't set_globvar_to_one and print_globvar globals too? Everybody freaks out about global scalars (lists, objects, etc), but not global functions, which are first-class citizens, too. - Hyperboreus
@ArtOfWarfare how about this - you have a variable which holds a large amount of data. you want to use several functions to manipulate the data in this variable and you also want to conserve memory. wouldn't globals be the best way of doing this since multiple large local variables would take up more memory? - mulllhausen
(2) @mulllhausen - If you're so strapped for resources, you shouldn't be using Python. I'd recommend you switch to C++ in such a situation, although if even that's not adequate, you could consider C or ASM. The overhead of using an interpreted language with garbage collection is far larger than having to pass a pointer around a few times (which, remember, is what you're passing around. Why would you be copying your large variables everywhere?) - ArtOfWarfare
(2) @Hyperboreus: how often do you see the code like global some_function? Most functions once defined are never changed. Moreover, good interfaces try to expose only as many names as necessary. __all__ may contain only a tiny part of all available functions in a module. - J.F. Sebastian
(2) Try reading in a massive dictionary file and passing it around on recursion function calls. See if you run out of stack space, even after doing the hacky sys.setrecursionlimit. Globals have their place. - mdenton8
Also relevant: python's obviously not for real programs, but it's useful to use concurrency in python for even the most menial tasks (a downloader or scraper?) and sometimes globals then become necessary. - mdenton8
(1) @Hypeboreus: functions are global constants and not global variables! - Daniel
@mullhausen: global variables has nothing to do with the amount of memory. Since all variables in python are only references, many local variables can share the same memory - Daniel
(3) @mdenton8: if you have a problem with the recursion limit, global variables don't solve your problem, but add another one. Try to use loops. - Daniel
@Daniel I don't think you understand. Loops are not always possible, simple as that. If you could give me a single reason as to why globals "add another problem", I might listen. But as of now, the program I'm specifically talking about would involve a 400 line-long method if it were to be written with loops, and would not have half the functionality of the original recursive solution. Do you really think that is less of a problem than globals? - mdenton8
@Anthony Sure, there is nothing wrong with global variables as long as you use them correctly. However non-final global variables are incompatible with reentrant procedures, and if necessary will need proper synchronization. In this scenario, unless used correctly, they are indeed "dangerous", leading to unsuspected concurrency issues. But to be honest, it has nothing to do with global variables as such, the same would happen with an class member for instance. I agree with you saying global variables are only a tool and there is nothing wrong with it. At the end it comes to the programmer. - tiktak
(3) 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. - Nate C-K
@NateC-K: Good point. But the interesting comparison here is not with something like C, which requires you to declare variables, but with something like JavaScript, which has implicitly-declared variables but defaults to globals. (Global variables aren't inherently dangerous, but accidental global variables are…) - abarnert
[+321] [2009-01-08 09:19:55] Jeff Shannon

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 [1] 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.)


(39) You should write a Python text book :) - alwbtc
(26) Good explanation. I find it convenient to remind myself from time to time that, in python, "assignment is not an operator." (Contrary to, say, C++, which is where I spend most of my programming time, hence the need for frequent reminders.) This leads to some apparently paradoxical results -- if myGlobal were an array -- [5] -- instead of a scalar, and func1 did myGlobal.append(42), then func2 would print [5, 42] even without a "global" declaration. - c-urchin
Your answers is like meditation. I want to be still and meditate on this answer. This is so good. - dt1369
Here is what is most surprising to me: if you modify func2() to print myGlobal then modify it then print it again, then you get an error as well. - Matyas
Yep, good answer. If you understand how the language is interpreted (read books about language parsing) it explains a lot why the global keyword is needed. - tiktak
[+86] [2009-01-08 05:59:04] gimel

You may want to explore the notion of namespaces [1]. In Python, the module [2] 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 [3]:

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

It seems to me like it would be cleaner to express these configuration variables using the ConfigParser class. In fact, that's what I'm trying to do at the moment, and I can't seem to figure it out. - g33kz0r
(3) ConfigParser is not related to sharing global variables between functions; You will still need a "config" instance and some sharing strategy. - gimel
This seems to fail if, instead of doing 'import config' you do 'from config import x'; the changes to x in one module importing config are not visible to other modules importing config. Does anyone understand why? - BlueBomber
@BlueBomber: because x would be a local identifier to the module that imported it. Think this way: a = SomeClass(); x = a.someattrib; x = 10. Would you expect a's values to have changed? No, right? Same with modules. - MestreLion
@BlueBomber: think of modules as objects (which they are). Importing is just assigning them to a local identifier. from config import x means, in layman's terms, the same as x = config.x. But be aware that if x is mutable (like a list), appending items to it will reflect in config! - MestreLion
[+33] [2011-07-12 12:35:08] SingleNegationElimination

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.

[+22] [2009-01-08 09:03:33] J S

If you want to refer to global variable in a function, you can use 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.

Thank you, this perfectly answered why sometimes global variables worked fine and other times (particularly when changing the value) didn't work at all - Nathan Garabedian
[+11] [2009-01-08 05:53:51] ironfroggy

I could ask just as properly why you're asking. Why do you believe the global is a better solution?

Global shared state is a widely known source of common problems. Keep adding functions that manipulate global data, and you'll quickly loose track what what might be causing some unexpected problem with it. Python's many design decisions are artifacts of understanding what keeps software understandable and crafting a language that encourages that wisdom.

(1) Agree. It's often bad form to use globals. Make sure you have a valid reason. If not your probably better off restructuring your code, using a class for example. - monkut
+1: Globals are simply a bad policy. They make functions have confusing (and unexpected) side-effects. They break idempotency. - S.Lott
(2) please keep in mind on many occasions, you may be writing a quick and dirty one-time scripts which require some function call. such as" if at first request doesn't succeed, call again" type of functionality. in these scenarios, global variables are a perfect fit. - Joshua Burns
(2) I'd downvote this "answer" if I had the rep. Contrast with gimel's very instructive answer which provides a classy alternative. - MarkHu
@MarkHu, indeed, but it's never too often to be reminded that global dta and side effects are a constant source of pulled hair :-) - vbocan
(2) Whether this proscription is a good idea or not, this should have been a comment, not an answer because it does not answer the question asked - Mel Nicholson
[+9] [2014-07-04 10:23:56] Rauni

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? [1].


[+6] [2009-01-09 11:56:19] Kylotan

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.

[+4] [2013-10-03 05:41:16] Bohdan

Global variables are much more fun when you deal with parallel execution. 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 time
import os
import sys
import random
def worker(a):
    oldValue = get()
    set(random.randint(0, 100))
    sys.stderr.write(' '.join([str(os.getpid()), str(a), 'old:', str(oldValue), 'new:', str(get()), '\n']))

def get():
    global globalVariable
    return globalVariable

globalVariable = -1
def set(v):
    global globalVariable
    globalVariable = v

print get()
print get()

processPool = multiprocessing.Pool(5)
results =, range(15))


27094 0 old: -2 new: 2
27094 1 old: 2 new: 95
27094 2 old: 95 new: 20
27094 3 old: 20 new: 54
27098 4 old: -2 new: 80
27098 6 old: 80 new: 62
27095 5 old: -2 new: 100
27094 7 old: 54 new: 23
27098 8 old: 62 new: 67
27098 10 old: 67 new: 22
27098 11 old: 22 new: 85
27095 9 old: 100 new: 32
27094 12 old: 23 new: 65
27098 13 old: 85 new: 60
27095 14 old: 32 new: 71

[+4] [2013-10-13 16:07:41] user2876408

As it turns out the answer is always simple.

Here is a small sample module. It is is a way to show it in a main definition:

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

def isTheNumber():
    return helper

Here is a way 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.

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 - barlop
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! - swdev
[+1] [2014-12-20 12:45:26] Mohamed El-Saka

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]

'in every function you want to use' is subtly incorrect, should be closer to: 'in every function where you want to update' - spazm
[0] [2014-12-04 06:27:43] gxyd

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.

[-1] [2015-02-04 19:19:54] Sagar Mehta

Try This :

def x1():
    global x
    x = 6

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

x = 5