[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 decleration 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.

FAQs on Local Variable Referenced Before Assignment

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.

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