TAGS :Viewed: 9 - Published at: a few seconds ago

[ Global variable changed by multiple functions - how to declare in Python ]

I am using some variable in multiple functions.
This includes changing the variable values by each of those functions.
I already declared the variable as 'global' in the first function.
Should I declare this variable again and again as global in each function (and this will not overwrite the first global variable I declared in the first function) or I should not declare it again as global in all those functions (but the local variables there still will be seen as global since I already declared this variable so first time)?

Answer 1


You can declare a variable as global in each function definition. Here's an example:

def f():
    global x
    x = 2
    print x
    x +=2 
    # This will assign a new value to the global variable x

def g():
    global x
    print x
    x += 3
    # This will assign a new value to the global variable x

f()
# Prints 2
g()
# Prints 4
print x
# Prints 7

Answer 2


The global keyword tells the parser per function that a name shouldn't be treated as a local when assigned to.

Normally any name you bind in a function (assign to, use as a function argument, use in an import statement in the function body, etc.) is seen by the parser as a local.

By using the global keyword, the parser will instead generate bytecode that'll look for a global name instead. If you have multiple functions that assign to the global, you'll need to declare that name global in all those functions. They'll then look up the name in the global namespace instead.

See the global statement documentation:

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals.

and the Naming and Binding documentation:

If a name is bound in a block, it is a local variable of that block. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable.