How to fix UnboundLocalError: local variable 'x' referenced before assignment in Python

by Nathan Sebhastian

Posted on May 26, 2023

Reading time: 2 minutes

unboundlocalerror local variable 'xxx' referenced before assignment

One error you might encounter when running Python code is:

This error commonly occurs when you reference a variable inside a function without first assigning it a value.

You could also see this error when you forget to pass the variable as an argument to your function.

Let me show you an example that causes this error and how I fix it in practice.

How to reproduce this error

Suppose you have a variable called name declared in your Python code as follows:

Next, you created a function that uses the name variable as shown below:

When you execute the code above, you’ll get this error:

This error occurs because you both assign and reference a variable called name inside the function.

Python thinks you’re trying to assign the local variable name to name , which is not the case here because the original name variable we declared is a global variable.

How to fix this error

To resolve this error, you can change the variable’s name inside the function to something else. For example, name_with_title should work:

As an alternative, you can specify a name parameter in the greet() function to indicate that you require a variable to be passed to the function.

When calling the function, you need to pass a variable as follows:

This code allows Python to know that you intend to use the name variable which is passed as an argument to the function as part of the newly declared name variable.

Still, I would say that you need to use a different name when declaring a variable inside the function. Using the same name might confuse you in the future.

Here’s the best solution to the error:

Now it’s clear that we’re using the name variable given to the function as part of the value assigned to name_with_title . Way to go!

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. See you in other tutorials.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.

Learn more about this website

Connect with me on Twitter

Or LinkedIn

Type the keyword below and hit enter

Click to see all tutorials tagged with:

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

Fix "local variable referenced before assignment" in Python

unboundlocalerror local variable 'xxx' referenced before assignment

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.

unboundlocalerror local variable 'xxx' referenced before assignment

Building Your First Convolutional Neural Network With Keras

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup

© 2013- 2024 Stack Abuse. All rights reserved.

[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

[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

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

Python成功解决 UnboundLocalError: local variable ‘xxx‘ referenced before assignment

unboundlocalerror local variable 'xxx' referenced before assignment

UnboundLocalError: local variable ‘xxx’ referenced before assignment

把变量声明称global, global sum_score

如果我们在函数内部命名了函数外的变量,会引起歧义。

计算机认为变量正在定义,怎么直接用上了?,会报错 报错 UnboundLocalError: local variable 'number' referenced before assignment

我们需要告诉计算机,这个变量number不是函数内的原住民,他是外来变量。

然后,我们删除掉return,看看结果是怎么样的?

如果我们不调用函数,则函数是不会运行的,number打印结果还是原来的的数字。

unboundlocalerror local variable 'xxx' referenced before assignment

“相关推荐”对你有帮助么?

unboundlocalerror local variable 'xxx' referenced before assignment

请填写红包祝福语或标题

unboundlocalerror local variable 'xxx' referenced before assignment

你的鼓励将是我创作的最大动力

unboundlocalerror local variable 'xxx' referenced before assignment

您的余额不足,请更换扫码支付或 充值

unboundlocalerror local variable 'xxx' referenced before assignment

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

unboundlocalerror local variable 'xxx' referenced before assignment

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 'xxx' referenced before assignment

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

  • transformer

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

img

  • 编辑 收藏 删除 结题

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

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

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

9 条回答 默认 最新

unboundlocalerror local variable 'xxx' 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 'xxx' referenced before assignment

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

unboundlocalerror local variable 'xxx' 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 'xxx' referenced before assignment

kobayashi.m

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

unboundlocalerror local variable 'xxx' referenced before assignment

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

unboundlocalerror local variable 'xxx' referenced before assignment

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

IMAGES

  1. UnboundLocalError: Local Variable Referenced Before Assignment

    unboundlocalerror local variable 'xxx' referenced before assignment

  2. UnboundLocalError: local variable referenced before assignment

    unboundlocalerror local variable 'xxx' referenced before assignment

  3. [Solved] UnboundLocalError: local variable 'x' referenced

    unboundlocalerror local variable 'xxx' referenced before assignment

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

    unboundlocalerror local variable 'xxx' referenced before assignment

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

    unboundlocalerror local variable 'xxx' referenced before assignment

  6. Local Variable Referenced Before Assignment Solved Error In Python

    unboundlocalerror local variable 'xxx' referenced before assignment

VIDEO

  1. Java Programming # 44

  2. Rapture Before Assignment Completion?

  3. IICS

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

  5. Prophetic Word

  6. Alignment before assignment! You need to get your alignment right before getting your 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. 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. 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.

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

  6. Fix "local variable referenced before assignment" in Python

    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: x = "Hello "def say_hello (name): x = x + name print (x) say_hello("Billy ...

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

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

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

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

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

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

  12. UnboundLocalError: local variable referenced before assignment

    It gives me following error: UnboundLocalError: local variable 'a' referenced before assignment whic... 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.

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

  14. ['UnboundLocalError', ["local variable 'x' referenced before assignment"]]

    1. In python and almost all other programming languages, you cannot change the value in a variable unless you declare it. in your code: if exactShareNameFound: x+= line. you did not declare x, but you are referring to it in the above line. If you wanted to append the value of line to x, then declare a variable x before using it, like so:

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

    CSDN问答为您找到训练时遇到UnboundLocalError: local variable 'output_proposals' referenced before assignment相关问题答案,如果想了解更多关于训练时遇到UnboundLocalError: local variable 'output_proposals' referenced before assignment 目标检测、深度学习、transformer 技术问题等相关问答,请访问CSDN问答。

  16. PythonでUnboundLocalErrorに遭遇したら

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

  17. Unbound local error: ("local variable referenced before assignment")

    How do I stop UnboundLocalError: local variable referenced before assignment error? Hot Network Questions Recent Lovecraftian video game where the objective was to investigate a town or manor or lighthouse and solve a mystery

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

    Any variable which is changed or created inside of a function is local, if it hasn't been declared as a global variable. To tell Python, that we want to use the global variable, we have to explicitly state this by using the keyword "global".

  19. Local variable 'x' referenced before assignment

    UnboundLocalError: local variable 'tests' referenced before assignment I've tried many different things to try to get tests to go to get_initial_input() but it says that it is referenced before assignment. ... "Local variable referenced before assignment" in Python. 0.

  20. Why is this wrong? UnboundLocalError: local variable 'xxx' referenced

    UnboundLocalError: local variable 'ru_blade' referenced before assignment Unless I am missing something else, this doesn't make sense since I don't have duplicate global variables. Here is the code.

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

    UnboundLocalError: local variable referenced before assignment issue. 3. ... UnboundLocalError: local variable 'xxx' referenced before assignment. 1. How do I stop UnboundLocalError: local variable referenced before assignment error? Hot Network Questions PTIJ: How do you prove G-d is The BOSS?

  22. python

    I think you are using 'global' incorrectly. See Python reference.You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar. #!/usr/bin/python total def checkTotal(): global total total = 0