Friday, July 13, 2012

Python: Global Variable Access

Current post is on how to access the global variables in Python 3.2. 


Global variables can be easily accessed by using the keyword global.

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. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

Names listed in a global statement must not be used in the same code block textually preceding that global statement.

Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.

Example 1: Change the global variable
globalVariable = False

def ChangeGlobalFunction():
      """Function that changes global variable"""
      global  globalVariable  #Global statement
      globalVariable = True

def PrintGlobalFunction():
      """Function that prints global variable"""
      print(globalVariable)

PrintGlobalFunction()
ChangeGlobalFunction()
PrintGlobalFunction()
Output:
False
True

No comments:

Post a Comment

Disclaimer:

The above post and all the posts in the blog are derived from facts, information, logical interpretation and logical conclusion of printed and internet materials available to me, perceived and produced by 99 gm brain of mine, which by no means always be accurate, consistent and complete.

All the posts are for personal quick reference only.

If any suggestion, correction, misinterpretation, misconception commented, which will be moderated and deleted if required, to avoid unforeseen issues.

If any trademark / copywrite issue is present, do send in a mail and appropriate tag (logo, name, website link) will be attached to the same.

Additional disclaimer will be attached wherever required in the post.