Python ‘Global name not defined’ Error and How to Handle It

Global Name Not Defined' Concept In Python

Global in a general sense refers to something that is known all over the world. Global comes from the word globe, hence it means relating to the whole planet. In the scope of programming, a global variable refers to a variable that is not only known by its name inside a function but can be called from anywhere within a program.

In contrast to local variables, which are specifically designed for use inside a particular code block or function, global variables (usually defined with the keyword global) can be referred to from anywhere in the code.

The global name not defined error will pop up on your screen when the interpreter is trying to refer to a variable in the scope of the entire program and not limited to specific segments but couldn’t find any.

In Python, a ‘Global name not defined’ error occurs when the interpreter fails to find a global variable it’s trying to access. Global variables can be declared in two ways: outside a function, making it accessible throughout the program; or inside a function using the ‘global’ keyword, making it usable beyond the function.

Working with Global Variables in Python

A variable declared outside all function definitions is a global variable, meaning it’s accessible throughout the entire program, from any function or method. On the other hand, a variable declared inside a function is a local variable, and its scope is limited to that function alone.

The concept of a global variable may be easier to understand with an example. Let’s say we have a variable, ‘count‘, which is initialized with a value of zero. This variable is declared outside of all functions, making it a global variable. In a user-defined function, ‘increase_count()’, we’ll increment ‘count’ by one each time the function is invoked.

It’s important to note that if we want to modify a global variable within a function, we need to explicitly state that it is global using the ‘global’ keyword. Without this keyword, the function will treat ‘count’ as a local variable, and the changes will not reflect in the global scope.

Let’s look at a Python code snippet demonstrating this:

# declaring global variables
count=0

# increasing the value inside our function
def increase_count():
    global count
    count = count + 1
    return count

# display the changed value in the scope of the function
print(increase_count()) # will print: 1
print(count) # will print: 1

Image 1
Image 1

In this example, we see that the ‘count’ variable is declared globally (outside the function). Within ‘increase_count()’, we increment the value of ‘count’ by one and return the new value.

The global keyword before ‘count’ in the function lets Python know that we mean the ‘count’ variable that exists in the global scope, not a new, local ‘count’ variable. Thus, the changes we make to ‘count’ inside the function apply to the global ‘count’ variable. Therefore, both print statements display the same value: 1.

Related: Using the Python globals() function.

Troubleshooting ‘Global name not defined’ Errors in Python

“The global name not defined” is a Name error which can be caused due to various reasons. A couple of them are:

  1. Local variable used as a global variable: If you forget to declare a variable as global inside a function and then try to access it outside the function, Python will raise a NameError. That’s because the interpreter will only search for the variable in the global scope, not finding it as it was defined only within the function.
  2. Global variable not initialized: If a global variable has been declared using the global keyword inside a function, but it hasn’t been assigned a value, a NameError will occur. The Python interpreter requires that every variable referenced has a value assigned to it, including global variables.

Let’s illustrate these cases with a couple of examples:

def increase_count():
    # No global keyword before count, this will be a local variable.
    local_count = 0
    return local_count+1

print(increase_count())  # This will work fine and print 1
print(local_count)  # This will raise a NameError

In the first case, local_count is a local variable and is not defined in the global scope. Thus, when we attempt to print it outside of the function, we get a NameError.

def increase_count():
    # Declared but not initialized.
    global global_count
    if global_count == 0:
        return global_count+1

print(increase_count())  # This will raise a NameError

In the second case, we declare global_count as a global variable but don’t assign a value to it. Therefore, when the function tries to check if global_count == 0, it raises a NameError.

To resolve “Global name not defined” error, ensure all variables are defined in the correct scope and properly initialized before they’re used. If a variable is meant to be global, use the global keyword within the function and assign a value to the variable. If the variable should only exist within a function, only reference it within that function.

Do check out: How to Disable a Warning in Python?

Summary

This article talks about what global variables are in Python. Global variables can be used in the scope of an entire program, be it inside or outside a particular block of code. There are a couple of ways to declare global variables and they have been discussed in the above sections. The name error associated with global variables is fairly simple to rectify. What other differences do you think are there between local and global variables other than their scope of use?