[SOLVED] Local Variable Referenced Before Assignment

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

[Fixed] typeerror can’t compare datetime.datetime to datetime.date

Local Variable Referenced Before Assignment Error with Explanation

Try these examples yourself using our Online Compiler.

Let’s look at the following function:

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.

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

[Fixed] nameerror: name Unicode is not defined

  • 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.

Please Login to comment...

Similar reads.

  • Python Programs
  • Python Errors
  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

The Research Scientist Pod

Python UnboundLocalError: local variable referenced before assignment

by Suf | Programming , Python , Tips

If you try to reference a local variable before assigning a value to it within the body of a function, you will encounter the UnboundLocalError: local variable referenced before assignment.

The preferable way to solve this error is to pass parameters to your function, for example:

Alternatively, you can declare the variable as global to access it while inside a function. For example,

This tutorial will go through the error in detail and how to solve it with code examples .

Table of contents

What is scope in python, unboundlocalerror: local variable referenced before assignment, solution #1: passing parameters to the function, solution #2: use global keyword, solution #1: include else statement, solution #2: use global keyword.

Scope refers to a variable being only available inside the region where it was created. A variable created inside a function belongs to the local scope of that function, and we can only use that variable inside that function.

A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available within any scope, global and local.

UnboundLocalError occurs when we try to modify a variable defined as local before creating it. If we only need to read a variable within a function, we can do so without using the global keyword. Consider the following example that demonstrates a variable var created with global scope and accessed from test_func :

If we try to assign a value to var within test_func , the Python interpreter will raise the UnboundLocalError:

This error occurs because when we make an assignment to a variable in a scope, that variable becomes local to that scope and overrides any variable with the same name in the global or outer scope.

var +=1 is similar to var = var + 1 , therefore the Python interpreter should first read var , perform the addition and assign the value back to var .

var is a variable local to test_func , so the variable is read or referenced before we have assigned it. As a result, the Python interpreter raises the UnboundLocalError.

Example #1: Accessing a Local Variable

Let’s look at an example where we define a global variable number. We will use the increment_func to increase the numerical value of number by 1.

Let’s run the code to see what happens:

The error occurs because we tried to read a local variable before assigning a value to it.

We can solve this error by passing a parameter to increment_func . This solution is the preferred approach. Typically Python developers avoid declaring global variables unless they are necessary. Let’s look at the revised code:

We have assigned a value to number and passed it to the increment_func , which will resolve the UnboundLocalError. Let’s run the code to see the result:

We successfully printed the value to the console.

We also can solve this error by using the global keyword. The global statement tells the Python interpreter that inside increment_func , the variable number is a global variable even if we assign to it in increment_func . Let’s look at the revised code:

Let’s run the code to see the result:

Example #2: Function with if-elif statements

Let’s look at an example where we collect a score from a player of a game to rank their level of expertise. The variable we will use is called score and the calculate_level function takes in score as a parameter and returns a string containing the player’s level .

In the above code, we have a series of if-elif statements for assigning a string to the level variable. Let’s run the code to see what happens:

The error occurs because we input a score equal to 40 . The conditional statements in the function do not account for a value below 55 , therefore when we call the calculate_level function, Python will attempt to return level without any value assigned to it.

We can solve this error by completing the set of conditions with an else statement. The else statement will provide an assignment to level for all scores lower than 55 . Let’s look at the revised code:

In the above code, all scores below 55 are given the beginner level. Let’s run the code to see what happens:

We can also create a global variable level and then use the global keyword inside calculate_level . Using the global keyword will ensure that the variable is available in the local scope of the calculate_level function. Let’s look at the revised code.

In the above code, we put the global statement inside the function and at the beginning. Note that the “default” value of level is beginner and we do not include the else statement in the function. Let’s run the code to see the result:

Congratulations on reading to the end of this tutorial! The UnboundLocalError: local variable referenced before assignment occurs when you try to reference a local variable before assigning a value to it. Preferably, you can solve this error by passing parameters to your function. Alternatively, you can use the global keyword.

If you have if-elif statements in your code where you assign a value to a local variable and do not account for all outcomes, you may encounter this error. In which case, you must include an else statement to account for the missing outcome.

For further reading on Python code blocks and structure, go to the article: How to Solve Python IndentationError: unindent does not match any outer indentation level .

Go to the  online courses page on Python  to learn more about Python for data science and machine learning.

Have fun and happy researching!

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Tumblr (Opens in new window)

Local variable referenced before assignment in Python

avatar

Last updated: Apr 8, 2024 Reading time · 4 min

banner

# 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 .

unboundlocalerror local variable name referenced before assignment

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.

mark variable as global

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 global variables in functions

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.

variables declared in function cannot be accessed in 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.

return value from the function

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.

pass global variable as argument to 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.

assign value to local variable from outer scope

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.

not using nonlocal prints 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

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

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 ⚡️

Python Forum

  • View Active Threads
  • View Today's Posts
  • View New Posts
  • My Discussions
  • Unanswered Posts
  • Unread Posts
  • Active Threads
  • Mark all forums read
  • Member List
  • Interpreter

UnboundLocalError: local variable referenced before assignment

  • Python Forum
  • Python Coding
  • General Coding Help
  • 0 Vote(s) - 0 Average

Unladen Swallow
Dec-27-2019, 05:23 AM https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

I used both global , nonlocal but both throws different error

throws this error
nonlocal test_var ^
SyntaxError: invalid syntax


throws this error ^
NameError: global name 'test_var' is not defined

Any suggestions ? I have gone through top 10 search results , all suggest to use nonlocal or global...

Dec-27-2019, 09:08 AM

I think that this boils down to this:

You should also understand difference between reference and assignment:

When you reference a variable in an expression, the Python interpreter will traverse the scope to resolve the reference in following order:

- current function’s scope
- any enclosing scopes (like containing functions)
- scope of the module that contains the code (global scope)
- built-in scope (that contains functions like int and abs)

If Python doesn't find defined variable with the referenced name, then a NameError exception is raised.

Assigning a value to a variable works differently. If the variable is already defined in the current scope, then it will just take on the new value. If the variable doesn’t exist in the current scope, then Python treats the assignment as a variable definition. The scope of the newly defined variable is the function that contains the assignment. Bucky Katt, Get Fuzzy

: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
  225 Yesterday, 03:19 PM
:
  694 Jun-15-2024, 07:15 PM
:
  1,711 Oct-02-2023, 12:57 AM
:
  1,996 Jan-10-2023, 10:58 PM
:
  1,948 Feb-25-2022, 01:21 AM
:
  2,251 Feb-10-2022, 07:36 PM
:
  3,623 Mar-02-2021, 08:11 PM
:
  3,943 Feb-04-2021, 06:27 AM
:
  4,779 Jul-13-2020, 03:53 PM
:
  2,523 Jun-11-2020, 12:45 PM
:
  • View a Printable Version

User Panel Messages

Announcements.

unboundlocalerror local variable 'weight' referenced before assignment

Login to Python Forum

Metaphlan3 running problem UnboundLocalError

I had an error when running metaphlan3 in the first step. My command is “metaphlan SRR7563636_1.fastq,SRR7563636_2.fastq --input_type fastq -s sams/SRR7563636.sam.bz2 --bowtie2out bowtie2/SRR7563636.bowtie2.bz2 -o profiles/SRR7563636_profile.tsv”.

But it reported, Downloading https://www.dropbox.com/sh/7qze7m7g9fe2xjg/AAA4XDP85WHon_eHvztxkamTa/file_list.txt?dl=1

Warning: Unable to download https://www.dropbox.com/sh/7qze7m7g9fe2xjg/AAA4XDP85WHon_eHvztxkamTa/file_list.txt?dl=1 Traceback (most recent call last): File “/gpfs/share/apps/python/cpu/3.6.5/bin/metaphlan”, line 8, in sys.exit(main()) File “/gpfs/share/apps/python/cpu/3.6.5/lib/python3.6/site-packages/metaphlan/metaphlan.py”, line 916, in main pars[‘index’] = check_and_install_database(pars[‘index’], pars[‘bowtie2db’], pars[‘bowtie2_build’], pars[‘nproc’], pars[‘force_download’]) File “/gpfs/share/apps/python/cpu/3.6.5/lib/python3.6/site-packages/metaphlan/init.py”, line 271, in check_and_install_database index = resolve_latest_database(bowtie2_db, ls_f[‘mpa_latest’], force_redownload_latest) UnboundLocalError: local variable ‘ls_f’ referenced before assignment

I can’t download the database by dropbox on our public server. Is there any way to solve or bypass this problem? For example, could I download the file and deposit it under some directory? Thank you so much!

Yes, you can download the database from Zenodo https://zenodo.org/record/3957592#.XzYjcB7RZ-E

and run MetaPhlan with the -x mpa_v30_CHOCOPhlAn_201901 parameter. You probably should update your installation, the latest version (3.0.2) automatically retrieves the database from Zenodo if Dropbox fails.

Thank you so much!!! I will try it.

Hi, Sorry to bother you. I download the database and deposited it under the path “/gpfs/data/lilab/home/zhoub03/software/metaphlan3_database/mpa_v30_CHOCOPhlAn_201901”. I have tried to specify the database by using

  • “metaphlan SRR7563636_1.fastq,SRR7563636_2.fastq --input_type fastq -s sams/SRR7563636.sam.bz2 –bowtie2db /gpfs/data/lilab/home/zhoub03/software/metaphlan3_database/mpa_v30_CHOCOPhlAn_201901 -x mpa_v30_CHOCOPhlAn_201901 --bowtie2out bowtie2/SRR7563636.bowtie2.bz2 -o profiles/SRR7563636_profile.tsv”
  • “metaphlan SRR7563636_1.fastq,SRR7563636_2.fastq --input_type fastq -s sams/SRR7563636.sam.bz2 -x mpa_v30_CHOCOPhlAn_201901 --bowtie2out bowtie2/SRR7563636.bowtie2.bz2 -o profiles/SRR7563636_profile.tsv”
  • “metaphlan SRR7563636_1.fastq,SRR7563636_2.fastq --input_type fastq -s sams/SRR7563636.sam.bz2 –bowtie2db /gpfs/data/lilab/home/zhoub03/software/metaphlan3_database/mpa_v30_CHOCOPhlAn_201901 --bowtie2out bowtie2/SRR7563636.bowtie2.bz2 -o profiles/SRR7563636_profile.tsv”

However, none of these commands worked. The tutorial just said, “Just download the .tar, .md5, and the mpa_latest files and place them in the metaphlan_databases folder .” So, where should I deposit the database? How can I let the metaphlan know where to find the database? Thank you so much!

Have you built the database with bowtie2-build ?

Yes, I have built the database under “/gpfs/data/lilab/home/zhoub03/software/metaphlan3_database/mpa_v30_CHOCOPhlAn_201901” and obtained “mpa_v30_CHOCOPhlAn_201901.1.bt2”. But when I ran “metaphlan SRR7563636_1.fastq,SRR7563636_2.fastq --input_type fastq -s sams/SRR7563636.sam.bz2 –bowtie2db /gpfs/data/lilab/home/zhoub03/software/metaphlan3_database/mpa_v30_CHOCOPhlAn_201901 --index mpa_v30_CHOCOPhlAn_201901 --bowtie2out bowtie2/SRR7563636.bowtie2.bz2 -o profiles/SRR7563636_profile.tsv”, it still reported the following error.

Downloading … Warning: Unable to download No MetaPhlAn BowTie2 database found (–index option)! Expecting location /gpfs/data/lilab/home/zhoub03/software/metaphlan3_database/mpa_v30_CHOCOPhlAn_201901/mpa_v30_CHOCOPhlAn_201901 Exiting…

Due to some internet safety issues, the metaphlan can’t automatically download the database. So where should I deposit the built database? How should I name the folder that contains the database? Thank you so much for your kindly help!

Is it the only file you got? You should have six .bt2 files in the “/gpfs/data/lilab/home/zhoub03/software/metaphlan3_database/mpa_v30_CHOCOPhlAn_201901” folder

Thank you so much! The bowtie reference was not completely generated. Now, this problem has been solved.

Related Topics

Topic Replies Views Activity
MetaPhlAn 3 583 December 30, 2020
MetaPhlAn 11 1104 June 7, 2022
MetaPhlAn 9 869 May 30, 2022
MetaPhlAn 1 357 January 31, 2023
MetaPhlAn 2 367 October 8, 2022

UnboundLocalError: local variable ‘trialList’ referenced before assignment

OS (e.g. Win10): macOS13.2.1 PsychoPy version (e.g. 1.84.x): 2022.2.5 What are you trying to achieve?: upload a csv making it a condition for trials

What did you try to make it work?: I’ve reload PsychoPy version from 2023 to 2022, and my friends’ mac works with the 2022 version. Also, I checked my csv file to make sure it’s right for PsychoPy.

What specifically went wrong when you tried that?: Traceback (most recent call last): File “/Applications/PsychoPy.app/Contents/Resources/lib/python3.8/psychopy/app/builder/dialogs/ init .py”, line 1531, in onBrowseTrialsFile File “/Applications/PsychoPy.app/Contents/Resources/lib/python3.8/psychopy/data/utils.py”, line 466, in importConditions UnboundLocalError: local variable ‘trialList’ referenced before assignment

Check your conditions file for spaces in the column names

Thanks for your answering, I’ve checked it. Below is my file, hope you can find the error I get. conditions_1.csv (139 Bytes)

I’ve also tried to use commas rather than semicolons, it causes the same error message.

Sorry for the delay. I’ve just checked our bug fixes and I think this is due to one of your columns being called corrAns, which accidentally got used by the developers for something else.

It should be fixed if your change your column to something else (e.g. corrAnswer) or you could try the 2024.1.0 release which is now available to download from Releases · psychopy/psychopy · GitHub

However, it may be something else, such as:

or maybe you have used word or congruent as an object name as well as a variable

Related Topics

Topic Replies Views Activity
Builder 10 4278 February 9, 2024
Builder 5 884 November 9, 2021
Builder 6 1413 March 12, 2024
Builder 2 529 February 1, 2023
Builder 10 305 December 11, 2023

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 'currentblock' referenced before assignment #150

@asopasopaso

asopasopaso commented Feb 11, 2024

いつもお世話になっています。
SDXLで使用すると以下のエラーが出てしまい、層別適用、lbw=やstop=などの指定が全て機能しません。
他の拡張をすべてオフにした状態でやっても同様のエラーが出ます。

なお、Automatic1111のバージョンは1.7.0です。1.5のLoRAに対しては問題なく使用できています。

@silveroxides

silveroxides commented Feb 11, 2024

Same issue here

Sorry, something went wrong.

@hako-mikan

hako-mikan commented Feb 12, 2024

May be fixed.

asopasopaso commented Feb 12, 2024

無事動きました。早速の対応ありがとうございました!

@asopasopaso

No branches or pull requests

@silveroxides

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

UnboundLocalError: local variable referenced before assignment

I have following simple function to get percent values for different cover types from a raster. It gives me following error: UnboundLocalError: local variable 'a' referenced before assignment

which isn't clear to me. Any suggestions?

  • arcgis-10.1
  • unboundlocalerror

PolyGeo's user avatar

  • 1 Because if row.getValue("Value") == 1 might be false and so a never gets assigned. –  Nathan W Commented May 20, 2013 at 2:39
  • It has value and do gets assigned. I checked it in arcmap interactive python window but can't get it to work in a stand alone script. –  Ibe Commented May 20, 2013 at 2:44
  • 1 your loop will also only give you the values of the last loop iteration as you are returning out of the loop and not doing anything with each value. –  Nathan W Commented May 20, 2013 at 2:49
  • You could use 3 x elif and an else to see if any values other than 1-4 are encountered. –  PolyGeo ♦ Commented May 20, 2013 at 3:44
  • I tried that way as well but still hung up with error. –  Ibe Commented May 20, 2013 at 4:15

This error is pretty much explained here and it helped me to get assignments and return values for all variables.

Your Answer

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 arcpy arcgis-10.1 unboundlocalerror or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • What to do when 2 light switches are too far apart for the light switch cover plate?
  • How to total time duration for an arbitrary number of tracked tasks in Excel?
  • Trying to find an old book (fantasy or scifi?) in which the protagonist and their romantic partner live in opposite directions in time
  • How long does it take to achieve buoyancy in a body of water?
  • Story where character has "boomerdisc"
  • What was I thinking when I made this grid?
  • Passport Carry in Taiwan
  • Do metal objects attract lightning?
  • Philosophies about how childhood beliefs influence / shape adult thoughts
  • If inflation/cost of living is such a complex difficult problem, then why has the price of drugs been absoultly perfectly stable my whole life?
  • How would increasing atomic bond strength affect nuclear physics?
  • What is the difference between using a resistor or a capacitor as current limiter?
  • How much missing data is too much (part 2)? statistical power, effective sample size
  • Completely introduce your friends
  • Is "using active record pattern" a reason to inherit from standard container (eg:vector)?
  • Why did General Leslie Groves evade Robert Oppenheimer's question here?
  • What happens if all nine Supreme Justices recuse themselves?
  • What would the appropriate cost be for a magical set of full plate with a Cast On and Cast Off property?
  • Why is one of the Intel 8042 keyboard controller outputs inverted?
  • How to Change Bullet Shapes Based on Frame Attributes (e.g., frametitle) in Beamer
  • What issues are there with my perspective on truth?
  • pgf plots-Shifting the tick label down while changing the decimal seperator to comma (,)
  • Could someone tell me what this part of an A320 is called in English?
  • Dress code for examiner in UK PhD viva

unboundlocalerror local variable 'weight' referenced before assignment

  • 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.

optimum.onnxruntime Yields UnboundLocalError: local variable ‘all_files’ referenced before assignment

Code is below. I have tried numerous popular model names and all give the same error. I used pip install optimum[exporters,onnxruntime] . Both of the below give the same error.

  • huggingface-transformers
  • sentence-transformers

lowlyprogrammer's user avatar

Know someone who can answer? Share a link to this question via email , Twitter , or Facebook .

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 .

Browse other questions tagged pytorch nlp huggingface-transformers onnx sentence-transformers or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • How do you determine what order to process chained events/interactions?
  • What is this strengthening dent called in a sheet metal part?
  • Does the Greek used in 1 Peter 3:7 properly translate as “weaker” and in what way might that be applied?
  • My school wants me to download an SSL certificate to connect to WiFi. Can I just avoid doing anything private while on the WiFi?
  • Purpose of burn permit?
  • How could Bangladesh protect itself from Indian dams and barrages?
  • Are quantum states like the W, Bell, GHZ, and Dicke state actually used in quantum computing research?
  • If inflation/cost of living is such a complex difficult problem, then why has the price of drugs been absoultly perfectly stable my whole life?
  • Fill a grid with numbers so that each row/column calculation yields the same number
  • Trying to find an old book (fantasy or scifi?) in which the protagonist and their romantic partner live in opposite directions in time
  • How to reply to reviewers who ask for more work by responding that the paper is complete as it stands?
  • Why did General Leslie Groves evade Robert Oppenheimer's question here?
  • What did the Ancient Greeks think the stars were?
  • Topology on a module over a topological ring
  • How does \vdotswithin work?
  • Can a 2-sphere be squashed flat?
  • I don’t know what to buy! Again!
  • Philosophies about how childhood beliefs influence / shape adult thoughts
  • What would be non-slang equivalent of "copium"?
  • Why doesn't the world fill with time travelers?
  • Is every recursively axiomatizable and consistent theory interpretable in the true arithmetic (TA)?
  • Is it possible to create a board position where White must make the move that leads to stalemating Black to avoid Black stalemating White?
  • Should I report a review I suspect to be AI-generated?
  • Meaning of “ ’thwart” in a 19th century poem

unboundlocalerror local variable 'weight' referenced before assignment

IMAGES

  1. "Fixing UnboundLocalError: Local Variable Referenced Before Assignment"

    unboundlocalerror local variable 'weight' referenced before assignment

  2. UnboundLocalError: Local Variable Referenced Before Assignment

    unboundlocalerror local variable 'weight' referenced before assignment

  3. UnboundLocalError: local variable referenced before assignment

    unboundlocalerror local variable 'weight' referenced before assignment

  4. UnboundLocalError: local variable 'weights_normed' referenced before

    unboundlocalerror local variable 'weight' referenced before assignment

  5. UnboundLocalError: Local variable referenced before assignment in

    unboundlocalerror local variable 'weight' referenced before assignment

  6. GIS: UnboundLocalError: local variable referenced before assignment

    unboundlocalerror local variable 'weight' referenced before assignment

COMMENTS

  1. Python 3: UnboundLocalError: local variable referenced before assignment

    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():

  2. How to Fix

    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

  3. [SOLVED] Local Variable Referenced Before Assignment

    Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created. Python does not have the concept of variable declarations. Python does not have the concept of variable declarations.

  4. UnboundLocalError Local variable Referenced Before Assignment in Python

    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.

  5. Python UnboundLocalError: local variable referenced before assignment

    UnboundLocalError: local variable referenced before assignment. Example #1: Accessing a Local Variable. Solution #1: Passing Parameters to the Function. Solution #2: Use Global Keyword. Example #2: Function with if-elif statements. Solution #1: Include else statement. Solution #2: Use global keyword. Summary.

  6. 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 .

  7. How to fix UnboundLocalError: local variable 'x' referenced before

    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.

  8. UnboundLocalError: local variable 'Normalizer' referenced before assignment

    UnboundLocalError: local variable 'Normalizer' referenced before assignment #173. Closed ... Closed UnboundLocalError: local variable 'Normalizer' referenced before assignment #173. wdyyyyyy opened this issue Jun 1, 2024 · 10 comments · Fixed by #420. Labels. bug Something isn't working. Comments. Copy link wdyyyyyy commented Jun 1, 2024.

  9. UnboundLocalError: local variable 'trialList' referenced before assignment

    UnboundLocalError: local variable 'trialList' referenced before assignment. CSV file has no spaces or other marking. I haven't used any other script so far to have interference with this. I would appreciate any help. Thank you in advance! JLC1 January 8, 2021, 10:56am 6.

  10. Local (?) variable referenced before assignment

    In order for you to modify test1 while inside a function you will need to do define test1 as a global variable, for example: test1 = 0. def test_func(): global test1. test1 += 1. test_func() However, if you only need to read the global variable you can print it without using the keyword global, like so: test1 = 0.

  11. UndboundLocalError: local variable referenced before assignment

    UndboundLocalError: local variable referenced before assignment. Coding. MarcelloSilvestre February 29, 2024, 12:17pm 1. Hello all, I'm using PsychoPy 2023.2.3 Win 10 x64bits. I am having a few issues in my experiment, some of the errors I never saw in older versions of Psychopy ... "UnboundLocalError: local variable 'os' referenced before ...

  12. UnboundLocalError: local variable referenced before assignment

    Assigning a value to a variable works differently. If the variable is already defined in the current scope, then it will just take on the new value. If the variable doesn't exist in the current scope, then Python treats the assignment as a variable definition. The scope of the newly defined variable is the function that contains the assignment.

  13. Metaphlan3 running problem UnboundLocalError

    UnboundLocalError: local variable 'ls_f' referenced before assignment. I can't download the database by dropbox on our public server. Is there any way to solve or bypass this problem? For example, could I download the file and deposit it under some directory? Thank you so much!

  14. UnboundLocalError: local variable 'im' referenced before assignment

    👋 Hello @Shi33, thank you for your interest in Ultralytics YOLOv8 🚀!We recommend a visit to the Docs for new users where you can find many Python and CLI usage examples and where many of the most common questions may already be answered.. If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us debug it.. If this is a custom training Question, please provide ...

  15. UnboundLocalError: local variable 'trialList' referenced before assignment

    OS (e.g. Win10): macOS13.2.1 PsychoPy version (e.g. 1.84.x): 2022.2.5 What are you trying to achieve?: upload a csv making it a condition for trials What did you try to make it work?: I've reload PsychoPy version from 2023 to 2022, and my friends' mac works with the 2022 version. Also, I checked my csv file to make sure it's right for PsychoPy. What specifically went wrong when you tried ...

  16. "UnboundLocalError: local variable 'input' referenced before assignment"

    UnBoundLocalError: local variable referenced before assignment (Python) 1. UnboundLocalError: local variable .. referenced before assignment ... UnboundLocalError: local variable referenced before assignment # Hot Network Questions Having one math symbol be in a different font from the others

  17. UnboundLocalError: local variable 'currentblock' referenced before

    Saved searches Use saved searches to filter your results more quickly

  18. UnboundLocalError: local variable 'y' referenced before assignment in

    And what is the value of weight for those two rows... Should be pretty simple to see why it's breaking. ... UnboundLocalError: local variable referenced before assignment issue. 0. ... "UnboundLocalError: local variable referenced before assignment" when calling a function. 1. Python Error, Local variable might be referenced before assignment ...

  19. UnboundLocalError: local variable referenced before assignment

    I have following simple function to get percent values for different cover types from a raster. It gives me following error: UnboundLocalError: local variable 'a' referenced before assignment whic...

  20. python: UnboundLocalError: local variable 'open' referenced before

    19. This means that further down in your function you create a variable called open: open = ... Rename it so that it doesn't clash with the built-in function. edited May 16, 2012 at 17:02. answered May 16, 2012 at 16:51. NPE. 496k 111 965 1k. "somewhere in your function" here means somewhere after your call to open.

  21. pytorch

    optimum.onnxruntime Yields UnboundLocalError: local variable 'all_files' referenced before assignment. Ask Question Asked today. Modified today. Viewed 3 times Part of NLP Collective ... using pipelines with a local model. 24