share
Stack OverflowUsing global variables in a function other than the one that created them
[+487] [7] user46646
[2009-01-08 05:45:03]
[ python global-variables ]
[ http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them ]

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?

[+745] [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

set_globvar_to_one()
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.


(1) The same thing applies to PHP to make sure you're aware they're global - Aram Kocharyan
(9) 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
(8) I think they are fairly dangerous. However in python "global" variables are actually module-level, which solves a lot of issues. - Fábio Santos
(1) @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
(2) I was using hyperbole, but I think my underlying point is still valid. - Anthony
1
[+191] [2009-01-08 09:19:56] 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:

----- sample.py -----
myGlobal = 5

def func1():
    myGlobal = 42

def func2():
    print myGlobal

func1()
func2()

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.)

[1] http://www.digi.com/wiki/developer/index.php/Python_Garbage_Collection

(19) You should write a Python text book :) - alwbtc
(17) 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
2
[+60] [2009-01-08 05:59:05] 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:

File: config.py

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

File: mod.py

import config
config.x = 1

File: main.py

import config
import mod
print config.x
[1] http://docs.python.org/reference/datamodel.html
[2] http://docs.python.org/tutorial/modules.html
[3] http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm

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
(2) 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
3
[+20] [2011-07-12 12:35:09] TokenMacGuy

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.


4
[+17] [2009-01-08 09:03:34] 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
5
[+9] [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
(1) 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
(1) I'd downvote this "answer" if I had the rep. Contrast with gimel's very instructive answer which provides a classy alternative. - MarkHu
6
[+3] [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.


7