Python Function Global Variables

Using global variables in a function

You can use a global variable within other functions by declaring it as global within each function that assigns a value 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

Since it's unclear whether globvar = 1 is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with the global keyword.

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

Python function global variables?

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.

E.g.

global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

How do I use global variables in python functions?

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.

Using Global Variables inside a Nested Function in Python

In add, x is not a global variable; it's local to add. You either need to make it global as well, so that add and change are referring to the same variable

def add(): 
global x
x = 15

def change():
global x
x = 20
print("Before making changes: ", x)
print("Making change")
change()
print("After making change: ", x)

add()
print("value of x",x)

or you need to declare x in change as nonlocal, rather than global.

def add(): 
x = 15

def change():
nonlocal x
x = 20
print("Before making changes: ", x)
print("Making change")
change()
print("After making change: ", x)

add()
print("value of x",x)

Calling versus defining global variables inside a Python function

The Programming FAQ explains the reasoning:

In Python, variables that are only referenced inside a function are
implicitly global. If a variable is assigned a value anywhere within
the function’s body, it’s assumed to be a local unless explicitly
declared 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.

The rule of thumb as to when we should use a global variable in a function

Style rules are not language rules. I.e. you shouldn't use eval(), but there it is, in the language.

tell me the rule of thumb as to when we should global a variable in a
function, and when it is not necessary?

The rules for when, and when not, to use global are simple, but even tutorials on the web get it wrong.

  1. The global keyword should not be used to create a global
    variable.

(Yes, that's partly a style rule.) When you define a top level variable outside a function, Python makes it global. (You don't use the global keyword for this.) When you assign to a variable inside a function, Python assumes it is local to the function. You only need the global keyword when you want change that later assumption so you can reassign (=) a global variable from within a function. You don't need the global declaration to examine a global variable. You don't need it to invoke a method on a global variable that might change its internal state or content:


  1. You only need the global keyword when you want to reassign (=) a
    global variable within a function.

The global declaration is used in any function where a global variable is reassigned. It is is placed ahead of the first reference to the variable, access or assignment. For simplicity, and style, global statements are put at the beginning of the function.

A statement like, "You should never use global variables", is a style rule and true of most programming languages -- apply it if/when you can. And if you absolutely can't, don't feel bad about it, just:


  1. Comment all globals you do use properly.

Global constants are less an issue:


  1. If global constants are truly constant, they never need the global
    keyword.

@juanpa.arrivillaga's example of go_left() taking the additional values as parameters instead of global variables, fails to take into account that go_left() is a callback and that the turtle event assignment functions don't provide for additional parameters. (They should, but they don't.) We can get around this using a lambda expression (or partial function from functools), but when used this way, lambda isn't particularly great style either, IMHO.

@martineau's suggestion of "making them attributes of a class that the class' methods can access" (aka class variables) is fine, but what is left unsaid is that it means subclassing Turtle or wrapping a turtle instance with another class.

My personal issue with mutable globals is that they are problematic in a multi-threaded world.

I have a problem with Python global variables. Is this a bug or an error?

You should use the global keyword inside your method, to refer to the object defined in an outer scope.

Your code should look like this :

def playerGainSoldiers():
global playerExtraSoldier
playerExtraSoldiers+=100*len(playerCountries)
if(ownsNorth==1):
playerExtraSoldiers+=250
if(ownsCentral==1):
playerExtraSoldiers+=600
if(ownsSouth==1):
playerExtraSoldiers+=350


Related Topics



Leave a reply



Submit