Using Global Variables in a Function

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.

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.

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.

What is the scope of global variables between two functions

You can use globals() to give you a dictionary of global variables.
You only need to use the keyword global if you plan to update a global variable, not if you are trying to access its value

You do need to assign them outside of the function so in your case

var1 = 1 # outside function, can be used as global variable
var2 = 2

def function1():
global var1, var2
var1 = 2 # as global is used, from here on var1 will have the value 2
var2 = 3

def function2():
# as you are not assigning a value to var1,2 but only access their value so
# you do not need to use the global keyword
ans = var1 + var2

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)

How can i access global variable using function in c++?

To access a global variable you should use of :: sign before it :

long s = 5;          //global value definition

int main()
{
long s = 1; //local value definition
cout << ::s << endl; // output is 5
cout << s << endl; // output is 1
}

Also It's so simple to use global s in cin :

cin >> ::s;
cout << ::s << endl;

Please try it online



Related Topics



Leave a reply



Submit