Wednesday, October 2, 2013

Python: Why The global Statement

Often, you come across Python developers debugging a piece of code involving global variables. Sure, global variables are the devil, but when you inherit code for a previous developer, you are just going to have to live with it until there's a budget for refactoring or rewriting it. Typically, if you are referencing a global variable within a function, you would 'import' the global variable into the function scope using the global keyword like this:
film_name = "painted skin"
def film():
  global film_name
  print(film_name)
film()
Now, even when you leave out the global statement, Python is smart enough to figure out that the variable is a global variable, as in this case:
film_name = "painted skin"
def film():
  print(film_name)
film()
Suppose you perform a variable assignment within this second case, you would have code like this:
film_name = "painted skin"
def film():
  film_name="final fantasy"
  print(film_name)
film()
When you execute it, all would seem fine and dandy till you decide that you want assignment statement to occur after the print statement like this:
film_name = "painted skin"
def film():
  print(film_name)
  film_name="final fantasy"
film()
The error that you would now receive reads the following:
UnboundLocalError: local variable 'film_name' referenced before assignment
What has happened in this case and the previous is that when a variable assignment occurs, Python creates a local variable instead of using the global variable. In the case where we only printed the variable value, the global variable was referenced. This can be resolved using the global statement, as indicated in the first case.

No comments: