[SOLVED] Local Variable Referenced Before Assignment

Python treats variables referenced only inside a function as global variables. Any variable assigned to a function’s body is assumed to be a local variable unless explicitly declared as global.

Why Does This Error Occur?

Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created. Python does not have the concept of variable declarations. Hence it searches for the variable whenever used. When not found, it throws the error.

Before we hop into the solutions, let’s have a look at what is the global and local variables.

Local Variable Declarations vs. Global Variable Declarations

Local VariablesGlobal Variables
A local variable is declared primarily within a Python function.Global variables are in the global scope, outside a function.
A local variable is created when the function is called and destroyed when the execution is finished.A Global Variable is created upon execution and exists in memory till the program stops.
Local Variables can only be accessed within their own function.All functions of the program can access global variables.
Local variables are immune to changes in the global scope. Thereby being more secure.Global Variables are less safer from manipulation as they are accessible in the global scope.

Local Variable Referenced Before Assignment Error with Explanation

Try these examples yourself using our Online Compiler.

Let’s look at the following function:

# Variable declaration outside function (global scope)
myVar = 10


def myFunction():
      if myVar == 5:
            print("5")
      elif myVar == 10:
            print("10")
      elif myVar >= 15:
            print("greater than 15 ")
     # reassigning myVar in the function
      myVar = 0

myFunction()

Output

Local Variable Referenced Before Assignment Error

Explanation

The variable myVar has been assigned a value twice. Once before the declaration of myFunction and within myFunction itself.

Solutions

Using Global Variables

Passing the variable as global allows the function to recognize the variable outside the function.

myVar = 10
def myFunction():
     # Telling the function to consider myVar as global
      global myVar
      if myVar == 5:
            print("5")
      elif myVar == 10:
            print("10")
      elif myVar >= 15:
            print("greater than 15 ")
      myVar = 0

myFunction()

Output

10

Create Functions that Take in Parameters

Instead of initializing myVar as a global or local variable, it can be passed to the function as a parameter. This removes the need to create a variable in memory.

# Passing myVar as a parameter in the function
def myFunction(myVar):
      if myVar == 5:
            print("5")
      elif myVar == 10:
            print("10")
      elif myVar >= 15:
            print("greater than 15 ")
      myVar = 0

myFunction(10)

Output

10

UnboundLocalError: local variable ‘DISTRO_NAME’

This error may occur when trying to launch the Anaconda Navigator in Linux Systems.

Upon launching Anaconda Navigator, the opening screen freezes and doesn’t proceed to load.

$ anaconda-navigator          
Traceback (most recent call last):
  File "/home/user/anaconda3/lib/python3.7/site-packages/anaconda_navigator/widgets/main_window.py", line 541, in setup
    self.post_setup(conda_data=conda_data)
...
...
UnboundLocalError: local variable 'DISTRO_NAME' referenced before assignment

Solution 1

Try and update your Anaconda Navigator with the following command.

conda update anaconda-navigator

Solution 2

If solution one doesn’t work, you have to edit a file located at

.../anaconda3//lib/python3.7/site-packages/anaconda_navigator/api/external_apps/vscode.py

After finding and opening the Python file, make the following changes:

In the function on line 159, simply add the line:

DISTRO_NAME = None

Save the file and re-launch Anaconda Navigator.

DJANGO – Local Variable Referenced Before Assignment [Form]

The program takes information from a form filled out by a user. Accordingly, an email is sent using the information.

from django import forms


# Creating a Class for django forms
class MyForm(forms.Form):
    name = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    msg = forms.CharField(
        required=True,
        widget=forms.Textarea
    )


...
# Create a function to retrieve info from the form
def GetContact(request):
    form_class = ContactForm
    if request.method == 'POST':
        form = form_class(request.POST)

        # Upon verifying validity, get following info and email with said info
        if form.is_valid():
            name = request.POST.get('name')
            email = request.POST.get('email')
            msg = request.POST.get('msg')

            send_mail('Subject here', msg, email, ['[email protected]'], fail_silently=False)
            return HttpResponseRedirect('blog/inicio')
            return render(request, 'blog/inicio.html', {'form': form})
...

Upon running you get the following error:

local variable 'form' referenced before assignment

Explanation

We have created a class myForm that creates instances of Django forms. It extracts the user’s name, email, and message to be sent.

A function GetContact is created to use the information from the Django form and produce an email. It takes one request parameter. Prior to sending the email, the function verifies the validity of the form. Upon True, .get() function is passed to fetch the name, email, and message. Finally, the email sent via the send_mail function

Why does the error occur?

We are initializing form under the if request.method == “POST” condition statement. Using the GET request, our variable form doesn’t get defined.

Local variable Referenced before assignment but it is global

This is a common error that happens when we don’t provide a value to a variable and reference it. This can happen with local variables. Global variables can’t be assigned.

This error message is raised when a variable is referenced before it has been assigned a value within the local scope of a function, even though it is a global variable.

Here’s an example to help illustrate the problem:

x = 10
def my_func():
    print(x)
    x += 1
my_func()

In this example, x is a global variable that is defined outside of the function my_func(). However, when we try to print the value of x inside the function, we get a UnboundLocalError with the message “local variable ‘x’ referenced before assignment”.

This is because the += operator implicitly creates a local variable within the function’s scope, which shadows the global variable of the same name. Since we’re trying to access the value of x before it’s been assigned a value within the local scope, the interpreter raises an error.

To fix this, you can use the global keyword to explicitly refer to the global variable within the function’s scope:

x = 10
def my_func():
    global x
    print(x)
    x += 1
my_func()

However, in the above example, the global keyword tells Python that we want to modify the value of the global variable x, rather than creating a new local variable. This allows us to access and modify the global variable within the function’s scope, without causing any errors.

Local variable ‘version’ referenced before assignment ubuntu-drivers

This error occurs with Ubuntu version drivers. To solve this error, you can re-specify the version information and give a split as 2 –

version = int(p_name.split('-')[-2])

Here, p_name means package name.

FAQs

How would you avoid using a global variable in multi-threads?

With the help of the threading module, you can avoid using global variables in multi-threading. Make sure you lock and release your threads correctly to avoid the race condition.

What is UnboundLocalError?

When a variable that is created locally is called before assigning, it results in Unbound Local Error in Python. The interpreter can’t track the variable.

Conclusion

Therefore, we have examined the local variable referenced before the assignment Exception in Python. The differences between a local and global variable declaration have been explained, and multiple solutions regarding the issue have been provided.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments