Skip to content

Accessing Global Variables from Within Functions in Python

Updated: at 04:56 AM

In Python, variables declared outside of a function are considered global variables and are accessible from anywhere in the code. However, when you declare a variable inside a function, it is considered a local variable and only accessible within that function. Sometimes you may need to access or modify a global variable from within a function. This is where the global keyword comes in handy in Python.

This comprehensive guide will explain what global variables and local variables are in Python, why we need the global keyword, how to use it to read and modify global variables from within functions, its scope, common mistakes, and best practices with examples. We will also look at alternatives to using global variables like arguments, return values and classes.

Table of Contents

Open Table of Contents

What are Global Variables and Local Variables in Python?

In Python, variable scope is implemented using namespaces. When we define a variable outside of any function, it becomes a global variable and belongs to the global namespace. Global variables can be accessed from anywhere in the code.

# global variable
count = 0

def my_func():
  print(count) #accessible here

Local variables are those declared inside a function body. They only exist within the function and cannot be referenced outside of that function.

def my_func():
   #local variable
   x = 1

print(x) #error, x not defined outside my_func()

By default, any variable assigned inside a function is considered local. To access a global variable from within a function, we need to explicitly state that we want to use the global variable rather than create a new local variable with the same name using the global keyword.

Why Use the global Keyword in Python?

In Python, assigning to a variable inside a function automatically declares it as a local variable. So if we want to reassign or modify a global variable from within a function, we need the global keyword.

For example:

count = 0 #global variable

def my_func():
  count += 1 #error without global keyword

my_func()
print(count) #still 0

This error occurs because count += 1 essentially means count = count + 1. By default count is treated as a local variable. So Python will look for count variable declared in the local function namespace instead of modifying the global count.

To fix this, we use the global keyword:

count = 0

def my_func():
  global count
  count += 1

my_func()
print(count) #1

Here, global count tells Python that count is a global variable so when we reassign count += 1, it updates the global variable.

How to Use global Keyword to Read Global Variables

The global keyword can also be used to read global variables from within functions for additional clarity, although it is not required for reading only.

For example:

count = 0

def my_func():
  global count
  print(count) #read global count

my_func()

We can also read globals without global keyword:

count = 0

def my_func():
  print(count) #still works without global

my_func()

However, explicitly using global can make the code easier to understand by signaling that the variable is global and not local to the function.

Modifying Global Variables with the global Statement

To modify a global variable from within a function, use the global keyword before assigning to the variable:

count = 0

def increment():
   global count
   count += 1

increment()
print(count) #1

Without global count, it would create a local variable count and not update the global count.

You can modify multiple global variables in one line:

count = 0
total = 100

def update_globals():
  global count, total
  count += 1
  total += count

update_globals()

Shorthand operators like += and -= also work to modify globals:

score = 0

def increment_score():
  global score
  score += 5 #add 5 to global variable

Scope of global Keyword

The global keyword only applies to the function it is used in, not any nested functions.

For example:

x = 'global'

def outer():
  x = 'outer'

  def inner():
    global x
    x = 'inner'

  inner()
  print(x) #outer

outer()
print(x) #global

Here, global x only modifies it in inner(), while outer() still prints the local x. The global x remains unchanged.

To modify globals from nested functions, use global again:

x = 'global'

def outer():
  x = 'outer'

  def inner():
    global x
    x = 'inner'

  inner()
  print(x) #inner

outer()
print(x) #inner

Common Mistakes with global Keyword

There are some common mistakes developers make when using the global keyword:

  1. Forgetting to declare global before modifying:

    count = 0
    
    def my_func():
      count += 1 #UnboundLocalError
    
    my_func()

    This tries to modify the global count without global and throws an error.

  2. Declaring global but trying to access undeclared global:

    def my_func():
      global count
      print(count) #NameError
    
    my_func()

    We declared count as global but didn’t define it outside the function.

  3. Modifying globals from within loop, exception handler, or comprehension:

    count = 0
    
    while True:
      global count
      count += 1 #SyntaxError
    
    for i in range(5):
      global count
      count += i #SyntaxError

    We can’t use global in loops, try/except blocks, list comprehensions etc.

  4. Creating global variable with same name as built-in:

    def my_func():
      global sum #overrides built-in sum()
      sum = 0

    This overrides Python’s built-in sum() with a global variable.

Best Practices for Using global Keyword

To avoid bugs and confusion when using global variables, follow these best practices:

Alternatives to Global Variables in Python

While globals can sometimes be useful, it is better to avoid using too many global variables. Here are some alternatives in Python:

1. Function Arguments

Rather than using globals, pass data into functions as arguments:

#global variable
count = 0

def my_func(count):
  count += 1
  return count

count = my_func(count)

This avoids reliance on globals and makes function easier to test.

2. Return Values

Return computed values from functions instead of modifying globals:

#instead of:

result = 0

def add(x, y):
  global result
  result = x + y

#do:

def add(x, y):
  return x + y

result = add(2, 3)

This reduces side effects and makes code more modular.

3. Classes

Use object oriented approach to encapsulate data and functions operating on it:

class Counter:
  def __init__(self):
    self.count = 0

  def increment(self):
    self.count += 1

c = Counter()
c.increment()
print(c.count) #1

This keeps data and behavior together and avoids use of globals.

4. Modules

Store global constants, configs or utility functions in modules and import into other code.

Conclusion

The global keyword in Python provides access to global variables from within functions. This allows modifying and reassigning global variables at the module scope from within a local function scope. However, improper use of global variables can lead to bugs and maintenance issues. Following best practices like avoiding overuse, using arguments and returns instead, and encapsulation via classes can help write cleaner Python code. The global keyword is a useful tool but should be used judiciously when necessary.