Fix "local variable referenced before assignment" in Python
Introduction
If you're a Python developer, you've probably come across a variety of errors, like the "local variable referenced before assignment" error. This error can be a bit puzzling, especially for beginners and when it involves local/global variables.
Today, we'll explain this error, understand why it occurs, and see how you can fix it.
The "local variable referenced before assignment" Error
The "local variable referenced before assignment" error in Python is a common error that occurs when a local variable is referenced before it has been assigned a value. This error is a type of UnboundLocalError , which is raised when a local variable is referenced before it has been assigned in the local scope.
Here's a simple example:
Running this code will throw the "local variable 'x' referenced before assignment" error. This is because the variable x is referenced in the print(x) statement before it is assigned a value in the local scope of the foo function.
Even more confusing is when it involves global variables. For example, the following code also produces the error:
But wait, why does this also produce the error? Isn't x assigned before it's used in the say_hello function? The problem here is that x is a global variable when assigned "Hello ". However, in the say_hello function, it's a different local variable, which has not yet been assigned.
We'll see later in this Byte how you can fix these cases as well.
Fixing the Error: Initialization
One way to fix this error is to initialize the variable before using it. This ensures that the variable exists in the local scope before it is referenced.
Let's correct the error from our first example:
In this revised code, we initialize x with a value of 1 before printing it. Now, when you run the function, it will print 1 without any errors.
Fixing the Error: Global Keyword
Another way to fix this error, depending on your specific scenario, is by using the global keyword. This is especially useful when you want to use a global variable inside a function.
No spam ever. Unsubscribe anytime. Read our Privacy Policy.
Here's how:
In this snippet, we declare x as a global variable inside the function foo . This tells Python to look for x in the global scope, not the local one . Now, when you run the function, it will increment the global x by 1 and print 1 .
Similar Error: NameError
An error that's similar to the "local variable referenced before assignment" error is the NameError . This is raised when you try to use a variable or a function name that has not been defined yet.
Running this code will result in a NameError :
In this case, we're trying to print the value of y , but y has not been defined anywhere in the code. Hence, Python raises a NameError . This is similar in that we are trying to use an uninitialized/undefined variable, but the main difference is that we didn't try to initialize y anywhere else in our code.
Variable Scope in Python
Understanding the concept of variable scope can help avoid many common errors in Python, including the main error of interest in this Byte. But what exactly is variable scope?
In Python, variables have two types of scope - global and local. A variable declared inside a function is known as a local variable, while a variable declared outside a function is a global variable.
Consider this example:
In this code, x is a global variable, and y is a local variable. x can be accessed anywhere in the code, but y can only be accessed within my_function . Confusion surrounding this is one of the most common causes for the "variable referenced before assignment" error.
In this Byte, we've taken a look at the "local variable referenced before assignment" error and another similar error, NameError . We also delved into the concept of variable scope in Python, which is an important concept to understand to avoid these errors. If you're seeing one of these errors, check the scope of your variables and make sure they're being assigned before they're being used.
Monitor with Ping Bot
Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.
© 2013- 2024 Stack Abuse. All rights reserved.
How to Fix Local Variable Referenced Before Assignment Error in Python
Table of Contents
Fixing local variable referenced before assignment error.
In Python , when you try to reference a variable that hasn't yet been given a value (assigned), it will throw an error.
That error will look like this:
In this post, we'll see examples of what causes this and how to fix it.
Let's begin by looking at an example of this error:
If you run this code, you'll get
The issue is that in this line:
We are defining a local variable called value and then trying to use it before it has been assigned a value, instead of using the variable that we defined in the first line.
If we want to refer the variable that was defined in the first line, we can make use of the global keyword.
The global keyword is used to refer to a variable that is defined outside of a function.
Let's look at how using global can fix our issue here:
Global variables have global scope, so you can referenced them anywhere in your code, thus avoiding the error.
If you run this code, you'll get this output:
In this post, we learned at how to avoid the local variable referenced before assignment error in Python.
The error stems from trying to refer to a variable without an assigned value, so either make use of a global variable using the global keyword, or assign the variable a value before using it.
Thanks for reading!
- Privacy Policy
- Terms of Service
Local variable referenced before assignment in Python
Last updated: Apr 8, 2024 Reading time · 4 min
# Local variable referenced before assignment in Python
The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function.
To solve the error, mark the variable as global in the function definition, e.g. global my_var .
Here is an example of how the error occurs.
We assign a value to the name variable in the function.
# Mark the variable as global to solve the error
To solve the error, mark the variable as global in your function definition.
If a variable is assigned a value in a function's body, it is a local variable unless explicitly declared as global .
# Local variables shadow global ones with the same name
You could reference the global name variable from inside the function but if you assign a value to the variable in the function's body, the local variable shadows the global one.
Accessing the name variable in the function is perfectly fine.
On the other hand, variables declared in a function cannot be accessed from the global scope.
The name variable is declared in the function, so trying to access it from outside causes an error.
Make sure you don't try to access the variable before using the global keyword, otherwise, you'd get the SyntaxError: name 'X' is used prior to global declaration error.
# Returning a value from the function instead
An alternative solution to using the global keyword is to return a value from the function and use the value to reassign the global variable.
We simply return the value that we eventually use to assign to the name global variable.
# Passing the global variable as an argument to the function
You should also consider passing the global variable as an argument to the function.
We passed the name global variable as an argument to the function.
If we assign a value to a variable in a function, the variable is assumed to be local unless explicitly declared as global .
# Assigning a value to a local variable from an outer scope
If you have a nested function and are trying to assign a value to the local variables from the outer function, use the nonlocal keyword.
The nonlocal keyword allows us to work with the local variables of enclosing functions.
Had we not used the nonlocal statement, the call to the print() function would have returned an empty string.
Printing the message variable on the last line of the function shows an empty string because the inner() function has its own scope.
Changing the value of the variable in the inner scope is not possible unless we use the nonlocal keyword.
Instead, the message variable in the inner function simply shadows the variable with the same name from the outer scope.
# Discussion
As shown in this section of the documentation, when you assign a value to a variable inside a function, the variable:
- Becomes local to the scope.
- Shadows any variables from the outer scope that have the same name.
The last line in the example function assigns a value to the name variable, marking it as a local variable and shadowing the name variable from the outer scope.
At the time the print(name) line runs, the name variable is not yet initialized, which causes the error.
The most intuitive way to solve the error is to use the global keyword.
The global keyword is used to indicate to Python that we are actually modifying the value of the name variable from the outer scope.
- If a variable is only referenced inside a function, it is implicitly global.
- If a variable is assigned a value inside a function's body, it is assumed to be local, unless explicitly marked as global .
If you want to read more about why this error occurs, check out [this section] ( this section ) of the docs.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- SyntaxError: name 'X' is used prior to global declaration
Borislav Hadzhiev
Web Developer
Copyright © 2024 Borislav Hadzhiev
How to fix UnboundLocalError: local variable 'x' referenced before assignment in Python
You could also see this error when you forget to pass the variable as an argument to your function.
How to reproduce this error
How to fix this error.
I hope this tutorial is useful. See you in other tutorials.
Take your skills to the next level ⚡️
Explore your training options in 10 minutes Get Started
- Graduate Stories
- Partner Spotlights
- Bootcamp Prep
- Bootcamp Admissions
- University Bootcamps
- Coding Tools
- Software Engineering
- Web Development
- Data Science
- Tech Guides
- Tech Resources
- Career Advice
- Online Learning
- Internships
- Apprenticeships
- Tech Salaries
- Associate Degree
- Bachelor's Degree
- Master's Degree
- University Admissions
- Best Schools
- Certifications
- Bootcamp Financing
- Higher Ed Financing
- Scholarships
- Financial Aid
- Best Coding Bootcamps
- Best Online Bootcamps
- Best Web Design Bootcamps
- Best Data Science Bootcamps
- Best Technology Sales Bootcamps
- Best Data Analytics Bootcamps
- Best Cybersecurity Bootcamps
- Best Digital Marketing Bootcamps
- Los Angeles
- San Francisco
- Browse All Locations
- Digital Marketing
- Machine Learning
- See All Subjects
- Bootcamps 101
- Full-Stack Development
- Career Changes
- View all Career Discussions
- Mobile App Development
- Cybersecurity
- Product Management
- UX/UI Design
- What is a Coding Bootcamp?
- Are Coding Bootcamps Worth It?
- How to Choose a Coding Bootcamp
- Best Online Coding Bootcamps and Courses
- Best Free Bootcamps and Coding Training
- Coding Bootcamp vs. Community College
- Coding Bootcamp vs. Self-Learning
- Bootcamps vs. Certifications: Compared
- What Is a Coding Bootcamp Job Guarantee?
- How to Pay for Coding Bootcamp
- Ultimate Guide to Coding Bootcamp Loans
- Best Coding Bootcamp Scholarships and Grants
- Education Stipends for Coding Bootcamps
- Get Your Coding Bootcamp Sponsored by Your Employer
- GI Bill and Coding Bootcamps
- Tech Intevriews
- Our Enterprise Solution
- Connect With Us
- Publication
- Reskill America
- Partner With Us
- Resource Center
- Bachelor’s Degree
- Master’s Degree
Python local variable referenced before assignment Solution
When you start introducing functions into your code, you’re bound to encounter an UnboundLocalError at some point. This error is raised when you try to use a variable before it has been assigned in the local context .
In this guide, we talk about what this error means and why it is raised. We walk through an example of this error in action to help you understand how you can solve it.
Find your bootcamp match
What is unboundlocalerror: local variable referenced before assignment.
Trying to assign a value to a variable that does not have local scope can result in this error:
Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function , that variable is local. This is because it is assumed that when you define a variable inside a function you only need to access it inside that function.
There are two variable scopes in Python: local and global. Global variables are accessible throughout an entire program; local variables are only accessible within the function in which they are originally defined.
Let’s take a look at how to solve this error.
An Example Scenario
We’re going to write a program that calculates the grade a student has earned in class.
We start by declaring two variables:
These variables store the numerical and letter grades a student has earned, respectively. By default, the value of “letter” is “F”. Next, we write a function that calculates a student’s letter grade based on their numerical grade using an “if” statement :
Finally, we call our function:
This line of code prints out the value returned by the calculate_grade() function to the console. We pass through one parameter into our function: numerical. This is the numerical value of the grade a student has earned.
Let’s run our code and see what happens:
An error has been raised.
The Solution
Our code returns an error because we reference “letter” before we assign it.
We have set the value of “numerical” to 42. Our if statement does not set a value for any grade over 50. This means that when we call our calculate_grade() function, our return statement does not know the value to which we are referring.
We do define “letter” at the start of our program. However, we define it in the global context. Python treats “return letter” as trying to return a local variable called “letter”, not a global variable.
We solve this problem in two ways. First, we can add an else statement to our code. This ensures we declare “letter” before we try to return it:
Let’s try to run our code again:
Our code successfully prints out the student’s grade.
If you are using an “if” statement where you declare a variable, you should make sure there is an “else” statement in place. This will make sure that even if none of your if statements evaluate to True, you can still set a value for the variable with which you are going to work.
Alternatively, we could use the “global” keyword to make our global keyword available in the local context in our calculate_grade() function. However, this approach is likely to lead to more confusing code and other issues. In general, variables should not be declared using “global” unless absolutely necessary . Your first, and main, port of call should always be to make sure that a variable is correctly defined.
In the example above, for instance, we did not check that the variable “letter” was defined in all use cases.
That’s it! We have fixed the local variable error in our code.
The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. You can solve this error by ensuring that a local variable is declared before you assign it a value.
Now you’re ready to solve UnboundLocalError Python errors like a professional developer !
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .
What's Next?
Get matched with top bootcamps
Ask a question to our community, take our careers quiz.
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
How to Solve Error - Local Variable Referenced Before Assignment in Python
- Python How-To's
- How to Solve Error - Local Variable …
Check the Variable Scope to Fix the local variable referenced before assignment Error in Python
Initialize the variable before use to fix the local variable referenced before assignment error in python, use conditional assignment to fix the local variable referenced before assignment error in python.
This article delves into various strategies to resolve the common local variable referenced before assignment error. By exploring methods such as checking variable scope, initializing variables before use, conditional assignments, and more, we aim to equip both novice and seasoned programmers with practical solutions.
Each method is dissected with examples, demonstrating how subtle changes in code can prevent this frequent error, enhancing the robustness and readability of your Python projects.
The local variable referenced before assignment occurs when some variable is referenced before assignment within a function’s body. The error usually occurs when the code is trying to access the global variable.
The primary purpose of managing variable scope is to ensure that variables are accessible where they are needed while maintaining code modularity and preventing unexpected modifications to global variables.
We can declare the variable as global using the global keyword in Python. Once the variable is declared global, the program can access the variable within a function, and no error will occur.
The below example code demonstrates the code scenario where the program will end up with the local variable referenced before assignment error.
In this example, my_var is a global variable. Inside update_var , we attempt to modify it without declaring its scope, leading to the Local Variable Referenced Before Assignment error.
We need to declare the my_var variable as global using the global keyword to resolve this error. The below example code demonstrates how the error can be resolved using the global keyword in the above code scenario.
In the corrected code, we use the global keyword to inform Python that my_var references the global variable.
When we first print my_var , it displays the original value from the global scope.
After assigning a new value to my_var , it updates the global variable, not a local one. This way, we effectively tell Python the scope of our variable, thus avoiding any conflicts between local and global variables with the same name.
Ensure that the variable is initialized with some value before using it. This can be done by assigning a default value to the variable at the beginning of the function or code block.
The main purpose of initializing variables before use is to ensure that they have a defined state before any operations are performed on them. This practice is not only crucial for avoiding the aforementioned error but also promotes writing clear and predictable code, which is essential in both simple scripts and complex applications.
In this example, the variable total is used in the function calculate_total without prior initialization, leading to the Local Variable Referenced Before Assignment error. The below example code demonstrates how the error can be resolved in the above code scenario.
In our corrected code, we initialize the variable total with 0 before using it in the loop. This ensures that when we start adding item values to total , it already has a defined state (in this case, 0).
This initialization is crucial because it provides a starting point for accumulation within the loop. Without this step, Python does not know the initial state of total , leading to the error.
Conditional assignment allows variables to be assigned values based on certain conditions or logical expressions. This method is particularly useful when a variable’s value depends on certain prerequisites or states, ensuring that a variable is always initialized before it’s used, thereby avoiding the common error.
In this example, message is only assigned within the if and elif blocks. If neither condition is met (as with guest ), the variable message remains uninitialized, leading to the Local Variable Referenced Before Assignment error when trying to print it.
The below example code demonstrates how the error can be resolved in the above code scenario.
In the revised code, we’ve included an else statement as part of our conditional logic. This guarantees that no matter what value user_type holds, the variable message will be assigned some value before it is used in the print function.
This conditional assignment ensures that the message is always initialized, thereby eliminating the possibility of encountering the Local Variable Referenced Before Assignment error.
Throughout this article, we have explored multiple approaches to address the Local Variable Referenced Before Assignment error in Python. From the nuances of variable scope to the effectiveness of initializations and conditional assignments, these strategies are instrumental in developing error-free code.
The key takeaway is the importance of understanding variable scope and initialization in Python. By applying these methods appropriately, programmers can not only resolve this specific error but also enhance the overall quality and maintainability of their code, making their programming journey smoother and more rewarding.
[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 Variables | Global Variables |
---|---|
A 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 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:
Explanation
The variable myVar has been assigned a value twice. Once before the declaration of myFunction and within myFunction itself.
Using Global Variables
Passing the variable as global allows the function to recognize the variable outside the function.
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.
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.
Try and update your Anaconda Navigator with the following command.
If solution one doesn’t work, you have to edit a file located at
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.
Upon running you get the following error:
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:
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:
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 –
Here, p_name means package name.
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.
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.
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.
Trending Python Articles
- Python Course
- Python Basics
- Interview Questions
- Python Quiz
- Popular Packages
- Python Projects
- Practice Python
- AI With Python
- Learn Python3
- Python Automation
- Python Web Dev
- DSA with Python
- Python OOPs
- Dictionaries
UnboundLocalError Local variable Referenced Before Assignment in Python
Handling errors is an integral part of writing robust and reliable Python code. One common stumbling block that developers often encounter is the “UnboundLocalError” raised within a try-except block. This error can be perplexing for those unfamiliar with its nuances but fear not – in this article, we will delve into the intricacies of the UnboundLocalError and provide a comprehensive guide on how to effectively use try-except statements to resolve it.
What is UnboundLocalError Local variable Referenced Before Assignment in Python?
The UnboundLocalError occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution.
Why does UnboundLocalError: Local variable Referenced Before Assignment Occur?
below, are the reasons of occurring “Unboundlocalerror: Try Except Statements” in Python :
Variable Assignment Inside Try Block
Reassigning a global variable inside except block.
- Accessing a Variable Defined Inside an If Block
In the below code, example_function attempts to execute some_operation within a try-except block. If an exception occurs, it prints an error message. However, if no exception occurs, it prints the value of the variable result outside the try block, leading to an UnboundLocalError since result might not be defined if an exception was caught.
In below code , modify_global function attempts to increment the global variable global_var within a try block, but it raises an UnboundLocalError. This error occurs because the function treats global_var as a local variable due to the assignment operation within the try block.
Solution for UnboundLocalError Local variable Referenced Before Assignment
Below, are the approaches to solve “Unboundlocalerror: Try Except Statements”.
Initialize Variables Outside the Try Block
Avoid reassignment of global variables.
In modification to the example_function is correct. Initializing the variable result before the try block ensures that it exists even if an exception occurs within the try block. This helps prevent UnboundLocalError when trying to access result in the print statement outside the try block.
Below, code calculates a new value ( local_var ) based on the global variable and then prints both the local and global variables separately. It demonstrates that the global variable is accessed directly without being reassigned within the function.
In conclusion , To fix “UnboundLocalError” related to try-except statements, ensure that variables used within the try block are initialized before the try block starts. This can be achieved by declaring the variables with default values or assigning them None outside the try block. Additionally, when modifying global variables within a try block, use the `global` keyword to explicitly declare them.
Similar Reads
- Python Programs
- Python Errors
Please Login to comment...
- How to Watch NFL on NFL+ in 2024: A Complete Guide
- Best Smartwatches in 2024: Top Picks for Every Need
- Top Budgeting Apps in 2024
- 10 Best Parental Control App in 2024
- GeeksforGeeks Practice - Leading Online Coding Platform
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
Python Numerical Methods
This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists , the content is also available at Berkeley Python Numerical Methods .
The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license . If you find this content useful, please consider supporting the work on Elsevier or Amazon !
< 3.1 Function Basics | Contents | 3.3 Nested Functions >
Local Variables and Global Variables ¶
Chapter 2 introduced the idea of the memory associated with the notebook where variables created in the notebook are stored. A function also has its own memory block that is reserved for variables created within that function. This block of memory is not shared with the whole notebook memory block. Therefore, a variable with a given name can be assigned within a fucntion without changing a variable with the same name outside of the function. The memory block associated with the function is opened every time a function is used.
TRY IT! What will the value of out be after the following lines of code are executed? Note that it is not 6, which is the value out is assigned inside of my_adder .
In my_adder , the variable out is a local variable . That is, it is only defined in the function of my_adder . Therefore, it cannot affect variables outside of the function, and actions taken in the notebook outside the function cannot affect it, even if they have the same name. So in the previous example, there is a variable, out , defined in the notebook cell. When my_adder is called on the next line, Python opens a new memory block for that function’s variables. One of the variables created within the function is another variable, out . However, since they are in different memory blocks, the assignment to out inside my_adder does not change the value assigned to out outside the function.
Why have separate function memory blocks rather than a single memory block? Although it may seem like a lot of trouble for Python to separate memory blocks, it is very efficient for large projects consisting of many functions working together. If one programmer is responsible for making one function, and another for making a different function, we would not want each programmer to have to worry about what variable names the other is using. We want them to be able to work independently and be confident that their own work did not interfere with the other’s and vice versa. Therefore, separate memory blocks protect a function from outside influence. The only things from outside the function’s memory block that can affect what happens inside a function are the input arguments, and the only things that can escape to the outside world from a function’s memory block when the function terminates are the output arguments.
The next examples are designed to be exercises in the concept of local variables. They are intentionally very confusing, but if you can untangle them, then you probably understand the local variable within a function. Focus on exactly what Python is doing, in the order that Python does it.
EXAMPLE: Consider the following function:
TRY IT! What will the value of a, b, x, y, and z be after the following code is run?
TRY IT! What will the value of m if you print m outside of the function?
We can see the value m is not defined outside of the function, since it is defined within the function. The opposite is similar, for example, if you define a variable outside a function, but you want to use it inside the function and change the value, you will get the same error.
EXAMPLE: Try to use and change the value n within the function.
The solution is to use the keyword global to let Python know this variable is a global variable that it can be used both outside and inside the function.
EXAMPLE: Define n as the global variable, and then use and change the value n within the function.
Navigation Menu
Search code, repositories, users, issues, pull requests..., provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications You must be signed in to change notification settings
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
UnboundLocalError: local variable 'request' referenced before assignment #492
CasellaJr commented Aug 26, 2022
For my experiments on CIFAR-10, until now I have used ResNet-18 or an EfficientNet. In the jupyter notebook, I initialise these models in this way: Then they works without problems, also even if I change normalization layers, number of classes and so on, no problem. The problem is when I use a different model, like a VGG16: then I have the following error: This is the complete log of the error: The error happens also if I create the VGG16 Class in this way: I remember that some weeks ago, this error appeared also with other different networks I tried (maybe alexnet or inception, but I do not remember), however it was not important so I skipped the problem, but now I want to use some different network and I want to solve. For the environment: I am using a real federation with 11 different machines. |
The text was updated successfully, but these errors were encountered: |
- 👍 1 reaction
- 👀 1 reaction
igor-davidyuk commented Aug 29, 2022
Let me try it myself |
Sorry, something went wrong.
I can confirm this. could you please report if the error is also shown on the front end (in your interactive environment) |
CasellaJr commented Aug 29, 2022
The error is shown on the terminal (used to start director and envoys). In the jupyter notebook I remember that the cells stop in |
I imagine, but what was the error? |
No error in the notebook, just the cell stops running, but there is no error |
igor-davidyuk commented Aug 30, 2022 • edited Loading
Investigation showed that the model is just too big for client to transfer, it will be fixed, for now just try using models with layers under 512 Mb |
- 👍 2 reactions
CasellaJr commented Aug 30, 2022
Yes, I have seen your PR. If that works, I can modify my python scripts as yours. |
CasellaJr commented Dec 8, 2022
News on this? |
igor-davidyuk commented Dec 8, 2022
The PR was merged. The message length was increased up to 1 GB, I am not sure if this change is in PyPI already. |
Installing from the source will also help you to increase the message length even further as it did not find its way to user settings and should be changed here: |
I did not installed anything new :D |
igor-davidyuk commented Dec 11, 2022
Ok, consider closing this issue when you ensure everything is working. |
CasellaJr commented May 31, 2023
Hello everyone in the collaborators, and the following in the aggregator: |
No branches or pull requests
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
ipython %timeit "local variable 'a' referenced before assignment"
I am trying to the run the following code but I get a local variable 'a' referenced before assignment.
The statement works without the %timeit magic.
Is there something I am missing?
- have you tried %timeit $a+=$b – Jean-François Fabre ♦ Commented Jan 15, 2018 at 19:49
- Thank you for taking the time to answer but that does not work. Neither surrounding the expression with braces. I thought the "$" and {braces} are only used when making system calls! – mandy Commented Jan 15, 2018 at 20:28
- yeah, sorry, too quick. Reopening. – Jean-François Fabre ♦ Commented Jan 15, 2018 at 20:30
What do you expect it to do?
Outside of the timeit it does:
I tried initializing x , and got a near infinite loop, eventually ending with a memory error
In other words each timeit loop concatenated another list of b values to x (and by extension a ), resulting are very long loop. I suspect an individual x+=b was fast, resulting in timeit choosing to loop many times.
Lets create an a fresh each loop:
This produces the memory error as well:
If I control the number of loops:
With ns times I can see why the default loops is so large.
I haven't tried timing a plain a+=... before (not even with numpy arrays), but evidently it expects some sort of local initialization for that a , either within the loop or in the initialization block. But it is important to keep in mind that the timed actions may be performed many times (the -r and -n parameters or the default values). So any in-place action might result bit changes to the global values. In this case timeit might be trying to protect us from that kind of unexpected growth, by expecting some sort of 'local' variable.
Lets try the a+b , but with an assignment:
Notice that the global c has not changed. The assignment is to a temporary local c - even though a global of the same name is available.
As a general rule, calculations performed inside the timing loop should not leak outside the loop. You have to something explicit as I did in the memory error loop, or here
Both use an in-place assignment to a local variable which has been linked to a mutable global.
- 4 I just expect it to time a+=b . The following commands work: %timeit a+b %timeit a.extend(b) but: %timeit a+=b returns the error message that local variable 'a' referenced before assignment. I just want to understand why a is not known in the latter but works with the former. – mandy Commented Jan 16, 2018 at 1:34
- 1 Which a is it supposed to use during each loop? The original 10 element list? Or the a produced by the last iteration (which keeps growing)? Or a new empty list? Do you understand why I got a memory error? – hpaulj Commented Jan 16, 2018 at 1:56
- Details of how the expression is compiled, and how the user namespace is passed to it (along with a local namespace) are buried in timeit code (not just the magic, but also the underlying timeit module. docs.python.org/3.5/library/timeit.html – hpaulj Commented Jan 16, 2018 at 3:16
Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Sign up or log in
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
Not the answer you're looking for? Browse other questions tagged python ipython timeit or ask your own question .
- The Overflow Blog
- Masked self-attention: How LLMs learn relationships between tokens
- Deedy Das: from coding at Meta, to search at Google, to investing with Anthropic
- Featured on Meta
- User activation: Learnings and opportunities
- Preventing unauthorized automated access to the network
- Feedback Requested: How do you use the tagged questions page?
Hot Network Questions
- How to forward one IP request to another port
- Used car dealership refused to let me use my OBDII on their car, is this a red flag?
- If mathematical platonism is true, how do biological brains governed by physical laws access eternal platonic mathematical truths?
- How to write an Antagonist that is hot, manipulative, but has good reasoning for being the 'villain'?
- \ContinuedFloat with threeparttable not working
- Why was Kanji used to write certain words in "Signal"?
- What is the greatest possible number of empty squares that could remain after the jumps?
- How do you measure exactly 31 minutes by burning the ropes?
- How to Organise/Present Built Worlds?
- Why are METAR issued at 53 minutes of the hour?
- Which ancient philosopher compared thoughts to birds?
- This puzzle is delicious
- Why do communists claim that capitalism began at the Industrial Revolution?
- Can I possibly win in this kind of situation?
- Lilypond Orchestral score: how to show duplicated tempo marking for violins?
- 2 NICs, PC is trying to use wrong one
- If a 'fire temple' was built in a gigantic city, with many huge perpetual flames inside, how could they keep smoke from bothering non-worshippers?
- How to reject non-physical solutions to the wave equation?
- What is the linguistic terminology for cases where the intonation or stress of a syllable determines its meaning?
- What is the name for this BC-BE back-to-back transistor configuration?
- God the Father punished the Son as sin-bearer: how does that prove God’s righteousness?
- Information about novel 'heavy weapons'
- In big band horn parts, should I write double flats (sharps) or the enharmonic equivalent?
- How can I make a 2D FTL-lane map on a galaxy-wide scale?
IMAGES
VIDEO
COMMENTS
I'm creating a Stop_word function in order to preprocessing my text data. "local variable 'text2' referenced before assignment" is my received error, working on Jupyter Notebook platform. In detail, text is an array of text token. list_stopwords = ['sinh viên', 'giảng viên']
File "weird.py", line 5, in main. print f(3) UnboundLocalError: local variable 'f' referenced before assignment. Python sees the f is used as a local variable in [f for f in [1, 2, 3]], and decides that it is also a local variable in f(3). You could add a global f statement: def f(x): return x. def main():
Output. Hangup (SIGHUP) Traceback (most recent call last): File "Solution.py", line 7, in <module> example_function() File "Solution.py", line 4, in example_function x += 1 # Trying to modify global variable 'x' without declaring it as global UnboundLocalError: local variable 'x' referenced before assignment Solution for Local variable Referenced Before Assignment in Python
Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.
value = value + 1 print (value) increment() If you run this code, you'll get. BASH. UnboundLocalError: local variable 'value' referenced before assignment. The issue is that in this line: PYTHON. value = value + 1. We are defining a local variable called value and then trying to use it before it has been assigned a value, instead of using the ...
If a variable is assigned a value in a function's body, it is a local variable unless explicitly declared as global. # Local variables shadow global ones with the same name. You could reference the global name variable from inside the function but if you assign a value to the variable in the function's body, the local variable shadows the ...
The UnboundLocalError: local variable 'x' referenced before assignment occurs when you reference a variable inside a function before declaring that variable. To resolve this error, you need to use a different variable name when referencing the existing variable, or you can also specify a parameter for the function. I hope this tutorial is useful.
Saved searches Use saved searches to filter your results more quickly
Trying to assign a value to a variable that does not have local scope can result in this error: UnboundLocalError: local variable referenced before assignment. Python has a simple rule to determine the scope of a variable. If a variable is assigned in a function, that variable is local. This is because it is assumed that when you define a ...
This tutorial explains the reason and solution of the python error local variable referenced before assignment
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.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
Avoid Reassignment of Global Variables. Below, code calculates a new value (local_var) based on the global variable and then prints both the local and global variables separately.It demonstrates that the global variable is accessed directly without being reassigned within the function.
% e) gpu-jupyter_1 | UnboundLocalError: local variable '_' referenced before assignment Should this line work? The text was updated successfully, but these errors were encountered:
The global variable __name__ is set by Python when it imports a module. Only when you run your file as a script (with python path/to/file.py), does Python set that variable to the string "__main__", and it is a handy value to test for when you want to run code only when the current module is the starting point.
Local Variables and Global Variables. Chapter 2 introduced the idea of the memory associated with the notebook where variables created in the notebook are stored. A function also has its own memory block that is reserved for variables created within that function. This block of memory is not shared with the whole notebook memory block.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.
"Local variable referenced before assignment" in Python 0 I'm doing this code and I am receiving an UnboundLocalError: local variable 'points' referenced before assignment
The problem happens in jupyter notebook and it's due to the varied behaviors of multiprocessing across different operating systems and python versions. For solutions, please refer to this thread #520 (comment). Also, execute the code via __main__ block might also dodge this issue.
For my experiments on CIFAR-10, until now I have used ResNet-18 or an EfficientNet. In the jupyter notebook, I initialise these models in this way: resnet18 = torchvision.models.resnet18(pretrained=False) efficientnet_b0 = torchvision.mo...
I am trying to the run the following code but I get a local variable 'a' referenced before assignment. a = [x for x in range(10)] b = [x for x in range(10)] %timeit a+=b The statement works without the %timeit magic.