Local variable referenced before assignment in Python

avatar

Last updated: Feb 17, 2023 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

unboundlocalerror local variable 'n' referenced before assignment

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

Career Karma

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

icon_10

Get matched with top bootcamps

Ask a question to our community, take our careers quiz.

James Gallagher

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Apply to top tech training programs in one click

Fixing Python UnboundLocalError: Local Variable ‘x’ Accessed Before Assignment

Understanding unboundlocalerror.

The UnboundLocalError in Python occurs when a function tries to access a local variable before it has been assigned a value. Variables in Python have scope that defines their level of visibility throughout the code: global scope, local scope, and nonlocal (in nested functions) scope. This error typically surfaces when using a variable that has not been initialized in the current function’s scope or when an attempt is made to modify a global variable without proper declaration.

Solutions for the Problem

To fix an UnboundLocalError, you need to identify the scope of the problematic variable and ensure it is correctly used within that scope.

Method 1: Initializing the Variable

Make sure to initialize the variable within the function before using it. This is often the simplest fix.

Method 2: Using Global Variables

If you intend to use a global variable and modify its value within a function, you must declare it as global before you use it.

Method 3: Using Nonlocal Variables

If the variable is defined in an outer function and you want to modify it within a nested function, use the nonlocal keyword.

That’s it. Happy coding!

Next Article: Fixing Python TypeError: Descriptor 'lower' for 'str' Objects Doesn't Apply to 'dict' Object

Previous Article: Python TypeError: write() argument must be str, not bytes

Series: Common Errors in Python and How to Fix Them

Related Articles

  • Python Warning: Secure coding is not enabled for restorable state
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings

Search tutorials, examples, and resources

  • PHP programming
  • Symfony & Doctrine
  • Laravel & Eloquent
  • Tailwind CSS
  • Sequelize.js
  • Mongoose.js

Local variable referenced before assignment in Python

The “local variable referenced before assignment” error occurs in Python when you try to use a local variable before it has been assigned a value.

This error typically arises in situations where you declare a variable within a function but then try to access or modify it before actually assigning a value to it.

Here’s an example to illustrate this error:

In this example, you would encounter the “local variable ‘x’ referenced before assignment” error because you’re trying to print the value of x before it has been assigned a value. To fix this, you should assign a value to x before attempting to access it:

In the corrected version, the local variable x is assigned a value before it’s used, preventing the error.

Keep in mind that Python treats variables inside functions as local unless explicitly stated otherwise using the global keyword (for global variables) or the nonlocal keyword (for variables in nested functions).

If you encounter this error and you’re sure that the variable should have been assigned a value before its use, double-check your code for any logical errors or typos that might be causing the variable to not be assigned properly.

Using the global keyword

If you have a global variable named letter and you try to modify it inside a function without declaring it as global, you will get error.

This is because Python assumes that any variable that is assigned a value inside a function is a local variable, unless you explicitly tell it otherwise.

To fix this error, you can use the global keyword to indicate that you want to use the global variable:

Using nonlocal keyword

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. It allows you to modify the value of a non-local variable in the outer scope.

For example, if you have a function outer that defines a variable x , and another function inner inside outer that tries to change the value of x , you need to use the nonlocal keyword to tell Python that you are referring to the x defined in outer , not a new local variable in inner .

Here is an example of how to use the nonlocal keyword:

If you don’t use the nonlocal keyword, Python will create a new local variable x in inner , and the value of x in outer will not be changed:

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Python program to find power of a number
  • Python program to calculate gross pay
  • Python - Ways to print longest consecutive list without considering duplicates element
  • Python - Golomb Encoding for b=2n and b!=2n
  • SpongeBob Mocking Text Generator - Python
  • Python - Frequency of x follow y in Number
  • Spelling checker in Python
  • Python | Visualizing O(n) using Python
  • Operations on Python Counter
  • Python | Convert list of strings to space separated string
  • Python | Ways to convert hex into binary
  • Smart calculator in Python
  • Python | Check possible bijection between sequence of characters and digits
  • Python | Check if string is a valid identifier
  • Download Anything to Google Drive using Google colab
  • Python program to convert POS to SOP
  • Python code to convert SOP to POS
  • Python | Calculate geographic coordinates of places using google geocoding API
  • Python implementation of automatic Tic Tac Toe game using random number

How to Fix – UnboundLocalError: Local variable Referenced Before Assignment in Python

Developers often encounter the  UnboundLocalError Local Variable Referenced Before Assignment error in Python. In this article, we will see what is local variable referenced before assignment error in Python and how to fix it by using different approaches.

What is UnboundLocalError: Local variable Referenced Before Assignment?

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

Below, are the reasons by which UnboundLocalError: Local variable Referenced Before Assignment error occurs in  Python :

Nested Function Variable Access

Global variable modification.

In this code, the outer_function defines a variable ‘x’ and a nested inner_function attempts to access it, but encounters an UnboundLocalError due to a local ‘x’ being defined later in the inner_function.

In this code, the function example_function tries to increment the global variable ‘x’, but encounters an UnboundLocalError since it’s treated as a local variable due to the assignment operation within the function.

Solution for Local variable Referenced Before Assignment in Python

Below, are the approaches to solve “Local variable Referenced Before Assignment”.

In this code, example_function successfully modifies the global variable ‘x’ by declaring it as global within the function, incrementing its value by 1, and then printing the updated value.

In this code, the outer_function defines a local variable ‘x’, and the inner_function accesses and modifies it as a nonlocal variable, allowing changes to the outer function’s scope from within the inner function.

Please Login to comment...

  • Python Errors
  • Python How-to-fix
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Consultancy

  • Technology Consulting
  • Customer Experience Consulting
  • Solution Architect Consulting

Software Development Services

  • Ecommerce Development
  • Web App Development
  • Mobile App Development
  • SAAS Product Development
  • Content Management System
  • System Integration & Data Migration
  • Cloud Computing
  • Computer Vision

Dedicated Development Team

  • Full Stack Developers For Hire
  • Offshore Development Center

Marketing & Creative Design

  • UX/UI Design
  • Customer Experience Optimization
  • Digital Marketing
  • Devops Services
  • Service Level Management
  • Security Services
  • Odoo gold partner

By Industry

  • Retail & Ecommerce
  • Manufacturing
  • Import & Distribution
  • Financical & Banking
  • Technology For Startups

Business Model

  • MARKETPLACE ECOMMERCE

Our realized projects

unboundlocalerror local variable 'n' referenced before assignment

MB Securities - A Premier Brokerage

unboundlocalerror local variable 'n' referenced before assignment

iONAH - A Pioneer in Consumer Electronics Industry

unboundlocalerror local variable 'n' referenced before assignment

Emers Group - An Official Nike Distributing Agent

unboundlocalerror local variable 'n' referenced before assignment

Academy Xi - An Australian-based EdTech Startup

  • Market insight

unboundlocalerror local variable 'n' referenced before assignment

  • Ohio Digital
  • Onnet Consoulting

></center></p><h2>Local variable referenced before assignment: The UnboundLocalError in Python</h2><p>When you start introducing functions into your code, you’re bound to encounter an UnboundLocalError at some point. Because you try to use a local variable referenced before assignment. So, in this guide, we talk about what this error means and why it is raised. We walk through an example in action to help you understand how you can solve it.</p><p>Source: careerkarma</p><p><center><img style=

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. To clarify, a variable is assigned in a function, that variable is local. 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. Whereas, local variables are only accessible within the function in which they are originally defined.

An example of Local variable referenced before assignment

We’re going to write a program that calculates the grade a student has earned in class.

Firstly, 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”. Then, 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 of Local variable referenced before assignment and see what happens:

Here is an error!

The Solution of Local variable referenced before assignment

The code returns an error: Unboundlocalerror local variable referenced before assignment 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.

Moreover, we do define “letter” at the start of our program. However, we define it in the global context. Because Python treats “return letter” as trying to return a local variable called “letter”, not a global variable.

Therefore, this problem of variable referenced before assignment could be solved in two ways. Firstly, 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. This approach is good because it lets us keep “letter” in the local context. To clarify, we could even remove the “letter = “F”” statement from the top of our code because we do not use it in the global context.

Alternatively, we could use the “global” keyword to make our global keyword available in the local context in our  calculate_grade()  function:

We use the “global” keyword at the start of our function.

This keyword changes the scope of our variable to a global variable. This means the “return” statement will no longer treat “letter” like a local variable. Let’s run our code. Our code returns: F.

The code works successfully! Let’s try it using a different grade number by setting the value of “numerical” to a new number:

Our code returns: B.

Finally, we have fixed the local variable referenced before assignment error in the code.

To sum up, as you can see, 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. Then, you can solve this error by ensuring that a local variable is declared before you assign it a value. Moreover, if a variable is declared globally that you want to access in a function, you can use the “global” keyword to change its value. In case you have any inquiry, let’s CONTACT US . With a lot of experience in Mobile app development services , we will surely solve it for you instantly.

>>> Read more

  • Average python length: How to find it with examples
  • List assignment index out of range: Python indexerror solution you should know
  • Spyder vs Pycharm: The detailed comparison to get best option for Python programming
  • fix python error , Local variable referenced before assignment , python , python dictionary , python error , python learning , UnboundLocalError , UnboundLocalError in Python

Our Other Services

  • E-commerce Development
  • Web Apps Development
  • Web CMS Development
  • Mobile Apps Development
  • Software Consultant & Development
  • System Integration & Data Migration
  • Dedicated Developers & Testers For Hire
  • Remote Working Team
  • Saas Products Development
  • Web/Mobile App Development
  • Outsourcing
  • Hiring Developers
  • Digital Transformation
  • Advanced SEO Tips

Offshore Development center

Lastest News

cloud computing for healthcare

Uncover The Treasures Of Cloud Computing For Healthcare 

cloud computing in financial services

A Synopsis of Cloud Computing in Financial Services 

applications of cloud computing

Discover Cutting-Edge Cloud Computing Applications To Optimize Business Resources

headless cms vs traditional cms

Headless CMS Vs Traditional CMS: Key Considerations in 2024

cloud computing platforms

Find Out The Best Cloud Computing Platforms To Foster Your Business Infrastructure

hybrid cloud computing

Hybrid Cloud Computing Essential Guide (2024)

Tailor your experience

  • Success Stories

Copyright ©2007 – 2021 by AHT TECH JSC. All Rights Reserved.

unboundlocalerror local variable 'n' referenced before assignment

Thank you for your message. It has been sent.

UnboundLocalError: local variable 'trialList' referenced before assignment

OS (e.g. Win10): mac 10.15.4 PsychoPy version (e.g. 1.84.x): 2020.1.2 Standard Standalone? (y/n) If not then what?: y What are you trying to achieve?:

I have this old exp that I can still run [github link removed after problem solved ]. I just refactored it: the stimuli are slightly different, but I meant to use the same paradigm [github link removed after problem solved ]. I copied the .psyexp file over, and when I run it, psychopy crushes after instruction presentation and gives me

I am stumped, waiting for help.

This happens for a reason: probably I did something different, but the error message doesn’t make any sense.

So I pip installed psychopy2020.1.2 into my conda python3 env and ran the script from the terminal. Crash, then correct error messages are shown: I fixed it and the script is running now (from both terminal and runner). The runner is not showing correct error messages, a psychopy bug?

I’m currently receiving the same error message about ‘trialList’ being referenced before assignment. What did you do to fix it? Any help would be much appreciated.

I had the same error and found out that it was caused by an oversight in the csv file, which was generated by another script:

There were leading spaces on the column names. After I removed them, things worked.

Hope that helps

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!

Hi @ar2 I found a partial solution to this. Copying the cell data into a new csv file and overwriting the existing file solved this error for me.

Though it’s still not clear why this problem is occurring.

Hi, I got the same error. I checked the .cvs: two columns had the same name. I changed them, made sure that all column names differed and the problem got solved. Hope this could help!

Hello, I was getting the same error when I was trying to add my .csv conditions file to a loop. Referring to some of the above answers, I ensured that there were no spaces in my column names. It turns out that Psychopy didn’t like that one of my column names had a slash (I was trying to define a variable as old/new). But I generally use underscore a lot in my column names to make it easier during data cleaning and analysis and that hasn’t given me any errors in Psychopy so far. Hope this helps others who are getting a similar error!

This worked!! thank you!

Hello, I need help with the same issue too!

I tried every suggestion mentioned here but I am still having the same error. I also tried it with .csv format, with numbers under the index column, recreating the excel table, writing choice without the ‘’

Screenshot 2024-02-08 at 8.41.47 PM

Related Topics

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

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 'cam_image' referenced before assignment #1

@Markson-Young

Markson-Young commented Dec 18, 2023

No branches or pull requests

@Markson-Young

码龄 粉丝数 原力等级 --

unboundlocalerror local variable 'n' referenced before assignment

训练时遇到UnboundLocalError: local variable 'output_proposals' referenced before assignment

  • transformer

我在训练时,使用单阶段模型训练,如下

img

  • 编辑 收藏 删除 结题

¥ 15 (您已提供 ¥ 20, 还可追加 ¥ 485)

提供问题酬金的用户不参与问题酬金结算和分配

支付即为同意 《付费问题酬金结算规则》

9 条回答 默认 最新

unboundlocalerror local variable 'n' referenced before assignment

🕒下午好,题主!目前:🟢[ 在线 ] 📢参考通义千问、由郭老师整理提供! 📣今日诗号:桃李春风一杯酒,江 湖夜雨十年灯。

根据您提供的代码片段和错误信息 "UnboundLocalError: local variable 'output_proposals' referenced before assignment",问题在于当 self.two_stage 为 False 时, output_proposals 变量没有被赋值,但在最后返回时却被引用。

要解决这个问题,你需要确保在两种情况下(即 self.two_stage 为 True 和 False )都对 output_proposals 进行初始化或赋值。由于这段代码似乎是 Deformable DETR 模型的一部分,而在单阶段模式下可能不需要 output_proposals ,因此可以在非两阶段模式下为其赋予一个合理的默认值或者直接移除不必要的返回项。

示例解决方案:

请注意,我在这里假设了一个默认值 torch.zeros(...) ,你需要根据实际情况替换为合适的默认输出。如果单阶段模式下确实不需要 output_proposals ,那么在返回时不包含它即可。

unboundlocalerror local variable 'n' referenced before assignment

  • 没有解决我的问题, 去提问

unboundlocalerror local variable 'n' referenced before assignment

  • ¥15 找会单片机 AI 深度学习的朋友
  • ¥15 C语言keil4编写发动机指针式转速表
  • ¥90 BQ27441学习过程卡在充电是为什么
  • ¥15 关DNS问题怎么解决
  • ¥15 计算机控制系统问题求解答
  • ¥15 COCOS动态加载问题
  • ¥15 ubuntu22.04才装了一天就上不了网了
  • ¥15 用MAX7219点阵模块显示笑脸
  • ¥15 swapface实时换脸obs输出怎么调人脸肤色怎么补光
  • ¥15 在sheet1录入的数据1、数据3、数据5,自动同步到sheet2和sheet3中数据1、数据3、数据5,sheet2和sheet3的表样一致,用VBA如何实现
  • Google Cloud

PythonでUnboundLocalErrorに遭遇したら

データアナリティクス事業本部 機械学習チームの中村( nokomoro3 )です。

本記事ではPythonの変数スコープと、 UnboundLocalError について整理したいと思います。

Pythonでは、関数外の変数であっても、関数内で以下のように参照することができます。

上記のようにインデントの最も浅い部分に定義された変数は、グローバル変数となります。

以下のコードでそれをチェックしてみましょう。

var1はグローバル変数であり、オブジェクトIDも同じものとなっていることが分かります。

グローバル変数を書き換えようとすると

ただし、例えば以下のように参照しつつ再代入しようとするとエラーとなります。

これは関数内で var1 がローカル変数と見なされるようになるためです。

こういった UnboundLocalError に遭遇する機会は意外と経験があることかと思います。

ローカル変数を定義しなおすと

こちらは関数内で変数を定義しなおすとエラーがなくなります。

しかしこれは元のグローバル変数を変更するわけではありません。

グローバル変数は書き変わっておらず、オブジェクトIDも関数内と関数外で異なることが分かります。

つまり、グローバル変数と同じ変数名のものを、ローカル変数として関数内で定義すると、ローカル変数と見なされていることが分かります。

ここまでの話を整理すると

先ほどのエラーとなるコードでは var1 = var1 + "_結合したい文字列" という一行により、ローカル変数としての定義と参照を同時に行っています。

また定義前に参照が実行されるため、 UnboundLocalError が発生しているということとなります。

つまり、グローバル変数と同じ名前の変数を関数内でローカル変数として使用すると、ローカル変数と見なされ、ローカル変数と見なされたものを、定義前に参照しようとすることでエラーとなっています。

よって以下のようなコードも、もちろんエラーとなります。

グローバル変数を書き換えるには

先ほどのコードではグローバル変数は書き換えができなかったですが、グローバル変数を書き換えたい場合は(良いかどうかは置いておいて)、以下のように global 変数名 と書くことで実現できます。

ちなみに、最初とオブジェクトIDが変わるのは再代入により新しい変数となっているだけで、str型がimmutableなためであるため、今回の変数スコープの話とは無関係となります。

またmutableなデータ型の場合、 global 変数名 などと記述しなくとも参照さえできれば書き換えが可能となります。

(mutable、immutableについては機会があれば別途記事にしようと思います)

関数内の関数の場合もエラーとなりうる

これらの挙動はグローバル変数だけではなく、関数内の関数で、その親関数の変数を参照する際にも発生します。

wrapper内で定義された変数が、その中の関数でも変数として定義されているため、未定義前に参照しに行くこととなり、先ほどと同様に UnboundLocalError となることがわかります。

親関数の変数を書き換えたい場合はnonlocal

このような場合に、親関数の変数を書き換えたい時は、 global 変数 の代わりに nonlocal 変数 を記載する必要があります。

関数内の関数内の関数でnonlocalを使うと?

では関数内の関数内の関数でnonlocalを使うとどうなるか?気になるところですが、これはひとつ外側の変数を取ってくるという挙動のようです。

いかがでしたでしょうか。本ブログがPythonの変数スコープや UnboundLocalError に遭遇した方の参考になれば幸いです。

EVENT 【4/30(火)リモート】クラスメソッドの会社説明会を開催します

Event 【5/9(木)】組織的なクラウド統制 はじめの一歩, event 【4/24(水)リモート】フリーランストーク#10 -フリーランスとしてのキャリアを成功させるアイデア&ヒント- を開催します, event 【4/2, 4/9リモート】クラスメソッドの会社説明会 〜フリーランスエンジニア/データ分析系案件特集〜 を開催します, event 【4/18(木)東京】gitlabで実現!初級者向けci/cd実践ハンズオン, event 【毎週開催】メソドロジック社共催!イチから始めるデータ活用!8週連続ウェビナー, event 【5/15(水)】classmethod showcase 事例で学ぶ、データ活用戦略の最新動向, event 【4/16(火)】snowflakeを触ってみよう!初めての方向けハンズオンセミナー, event 【4/10(水)リモート】クラスメソッドの会社説明会を開催します, event 【4/17(水)】初心者向け 問い合わせ対応業務をカンタンにする「zendesk for service」とは?, pytest-mockでモックを使ってみる.

unboundlocalerror local variable 'n' referenced before assignment

kobayashi.m

[Boto3] オプトインリージョンに作成したS3バケットにAPIアクセスする際にはリージョンを指定しなければいけない

unboundlocalerror local variable 'n' referenced before assignment

pytest-xdistでテストを並列実行するとき、sessionのfixtureを1度だけ実行させる

unboundlocalerror local variable 'n' referenced before assignment

Pytestでカスタムマークを使って特定のテストのみを実行する

IMAGES

  1. UnboundLocalError: Local Variable Referenced Before Assignment

    unboundlocalerror local variable 'n' referenced before assignment

  2. UnboundLocalError: local variable referenced before assignment

    unboundlocalerror local variable 'n' referenced before assignment

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

    unboundlocalerror local variable 'n' referenced before assignment

  4. Local Variable Referenced Before Assignment Solved Error In Python

    unboundlocalerror local variable 'n' referenced before assignment

  5. Unboundlocalerror local variable error referenced before assignment

    unboundlocalerror local variable 'n' referenced before assignment

  6. UnboundLocalError: local variable 'epoch_logs' referenced before

    unboundlocalerror local variable 'n' referenced before assignment

VIDEO

  1. Java Programming # 44

  2. 【Lowest Price Ever!🔥】Best uad compressor vst plugin 2024?😲Manley Vari-Mu, Universal Audio Sound Demo

  3. Housing Corruption

  4. Variable Frequency Drive (VFD) #youtubeshorts #electrical

  5. The Weeknd

  6. local variable referenced before assignment error in python in hindi

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. UnboundLocalError Local variable Referenced Before Assignment in Python

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

  3. [SOLVED] 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.

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

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

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

  7. Python local variable referenced before assignment Solution

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

  8. Fixing Python UnboundLocalError: Local Variable 'x' Accessed Before

    2 Solutions for the Problem. 2.1 Method 1: Initializing the Variable. 2.2 Method 2: Using Global Variables. 2.3 Method 3: Using Nonlocal Variables.

  9. Python成功解决 UnboundLocalError: local variable 'xxx' referenced before

    在python中有一个经典错误: local variable xxx referenced before assignment #赋值前引用的局部变量xxx 这里引入两个概念: 局部变量指的在函数内部定义并使用的变量,它只在函数内部有效。全局变量指的是能作用于函数内外的变量,即全局变量既可以在各个函数的外部使用,也可以在各函数内部使用。

  10. local variable referenced before assignment 原因及解决办法-CSDN博客

    local variable referenced before assignment 原因及解决办法. 一句话, 在函数内部更改全局变量就会出现此错误 。. 在上面一段代码中,函数temp的操作是打印a的值,但函数内部并没有对a进行定义,此时系统会在外部寻找a的值,而我们在函数外部给a赋值为3,这种 在函数 ...

  11. UnboundLocalError: local variable <var> referenced before assignment

    UnboundLocalError: local variable 'n' referenced before assignment Share. Improve this answer. Follow answered Apr 29, 2021 at 7:21. nobleknight nobleknight. 755 7 7 silver badges 15 15 bronze badges. ... UnboundLocalError: local variable referenced before assignment issue. 2.

  12. Local variable referenced before assignment in Python

    Using nonlocal keyword. The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. It allows you to modify the value of a non-local variable in the outer scope. For example, if you have a function outer that defines a variable x, and another function inner inside outer that tries to change the value of x, you need to ...

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

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

    To fix this, you can either move the assignment of the variable x before the print statement, or give it an initial value before the print statement. def example (): x = 5 print (x) example()

  15. Local variable referenced before assignment: The UnboundLocalError

    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: 1 UnboundLocalError: local variable referenced before assignment. Python has a simple rule to determine the scope of a variable.

  16. UnboundLocalError: local variable 'x' referenced before assignment

    UnboundLocalError: local variable referenced before assignment. 1. PGRouting Layer plugin "UnboundLocalError: local variable 'db' referenced before assignment" 2. Error: local variable referenced before assignment in ArcPy. 1. python - psycopg2.errors.RaiseException find_srid() - could not find the corresponding SRID. 3.

  17. UnboundLocalError: local variable 'active_adapters' referenced before

    ) from peft. tuners. tuners_utils import BaseTunerLayer for _, module in self. named_modules (): if isinstance (module, BaseTunerLayer): active_adapters = module. active_adapter break # For previous PEFT versions > if isinstance (active_adapters, str): E UnboundLocalError: local variable 'active_adapters' referenced before assignment

  18. UnboundLocalError: local variable ... referenced before assignment

    There isn't a standard way to handle this situation. Common approaches are: 1. make sure that the variable is initialized in every code path (in your case: including the else case) 2. initialize the variable to some reasonable default value at the beginning. 3. return from the function in the code paths which cannot provide a value for the ...

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

  20. UnboundLocalError: local variable 'cam_image' referenced before

    UnboundLocalError: local variable 'cam_image' referenced before assignment #1. Open Markson-Young opened this issue Dec 18, 2023 · 0 comments Open ... UnboundLocalError: local variable 'cam_image' referenced before assignment ...

  21. UnboundLocalError: local variable 'x' referenced before assignment

    findPoints(geometry, results) File "identify_northsouth_point.py", line 8, in findPoints. results['north'] = (x,y) UnboundLocalError: local variable 'x' referenced before assignment. I have tried global and nonlocal, but it does not work. Since I am not gettin any input from outside the function, so I anyways would not require global or nonlocal.

  22. 训练时遇到UnboundLocalError: local variable 'output_proposals' referenced

    引自免费微信小程序:皆我百晓生 在训练模型的过程中,您遇到了 UnboundLocalError: Local variable 'output_proposals' referenced before assignment 错误,这是由于Python中的引用语句在深度学习模型中可能会导致局部变量被动态重新赋值,而在多层神经网络中,这种调用可能发生在不同的位置,而这些位置的变量名是 ...

  23. PythonでUnboundLocalErrorに遭遇したら

    こういったUnboundLocalErrorに遭遇する機会は意外と経験があることかと思います。 ローカル変数を定義しなおすと こちらは関数内で変数を定義しなおすとエラーがなくなります。

  24. How to fix UnboundLocalError: local variable 'df' referenced before

    You only create an object named df, if the details are either "csv" or "xlsx".If they have another type, no df will be created. Hence, you can not return df at the end of your function. It will crash, whenever you try.