• Try it free
  • Spreadsheet (BI)
  • Point of Sale - Shop
  • Point of Sale - Restaurant
  • Subscriptions
  • Website Builder
  • Manufacturing
  • Maintenance
  • Recruitment
  • Social Marketing
  • Email Marketing
  • SMS Marketing
  • Marketing Automation
  • Field Service
  • Appointments
  • WhatsApp New!
  • Documentation
  • Certifications
  • Planet Odoo
  • Education Program
  • Scale Up! Business Game
  • Compare Editions
  • Translations
  • Become a Partner
  • Register your Accounting Firm
  • Find a Partner
  • Find an Accountant
  • Schedule a demo
  • Customer References
  • Implementation Services
  • Development Services

Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:

  • Project management

This question has been flagged

Avatar

Hi,  You are filtering the room_line_ids in your for loop as below 

But the product variable  in the right side of the expression is not assigned to any value. 

Odoo Experience on YouTube

1. Use the live chat to ask your questions. 2. The operator answers within a few minutes.

  • Python Home
  • Documentation
  • Developer's Guide
  • Random Issue
  • Issues with patch
  • Easy issues

Google

  • Lost your login?
  • Committer List
  • Tracker Documentation
  • Tracker Development
  • Report Tracker Problem

free variable 'x' referenced before assignment in enclosing scope

This issue tracker has been migrated to GitHub , and is currently read-only . For more information, see the GitHub FAQs in the Python's Developer Guide.

This issue has been migrated to GitHub: https://github.com/python/cpython/issues/48867

Created on 2008-12-10 12:18 by amaury.forgeotdarc , last changed 2022-04-11 14:56 by admin . This issue is now closed .

  • Ask a Question
  • All categories
  • installation (2)

I got an error "NameError: free variable 'gfk' referenced before assignment in enclosing scope"

I am trying to use your TransportMaps library to track an airplane using ground based radar. However, I got an error :  NameError: free variable 'gfk' referenced before assignment in enclosing scope.

I would very appreciate if you can find some time to answer me.

Best regards,

Here the python version information:

 Here the python script I use:

The whole Error information:

Please log in or register to add a comment.

Please log in or register to answer this question..

Hi Jack, you are trying to solve the following problem, right?

\[ \nu_{Z_0}=\mathcal{N}(0, Q_0) \;, \quad \nu_w = \mathcal{N}(0,Q) \;,\quad \nu_v=\mathcal{N}(0,R) \]

\[ Z_{t+1} = F Z_{t} + \varepsilon \;, \quad \varepsilon \sim \nu_{w} \]

\[ Y_t  = \sqrt{Z_{2,t}^2 + Z_{0,t}^2} + \delta \;, \quad \delta\sim\nu_v \]

I just tried to run your code and I run on a different error, namely

This means that the random sampler for the prior \( \nu_Z \) distribution is not implelemented (now that I know it, I will do it soon). If this is not implemented, then you need to provide a starting point for the optimization used to find the MAP point for the Laplace approximation. For example, if you wanted to use the generating states as a starting point, you would do

This way the code runs on my machine. Let me know whether you are still having the same problem and I can dig more into it.

 Daniele

PS: Also, if you want to see whether the optimization worked fine, you can lower the logging level to the INFO level (20) or to the debug level (10):

free variable 'x' referenced before assignment in enclosing scope

The SequentialInference is sensitive to the prior information? I have compared the SequentialInference method with the laplace approximation method and I found the performance of SequentialInference is influenced by the prior information.

The python code is:

When I set the prior covariance Q0= 5 *np.eye(state_dim), the filter will lose the target. However, when I set Q0= 10 *np.eye(state_dim), it performs well.

Besides, it runs  slow when I set the order=2 and qparams=[3]*dim_tm.

On the prior

Yes, in general the solution is sensitive to prior information (both for the sequential inference algorithm and the Laplace approximation). In the end the prior information concur in the definition of your problem/posterior, and the fact that you are able to track an object or not depends from two factors:

  • whether you give a good starting point and appropriately model the transitions and updates
  • you characterize the posterior distribution

If the model is not good (e.g. no good prior/transitions/updates), you can still characterize the posterior accurately, but in practice you are finding the "right answer to the wrong question". This is the case for any filtering technique I know of: if your starting guess is not good, it's quite unlikely the filter will recover.

On this account, I see that you have changed 100 to 10 in this line

This is indeed gives a better starting point for the filter, as well as relaxing the prior on x0 by using a variance 10 instead of 5. In fact, I tried to use

and it works very well. Again, one cannot always have accurate initial measurements, but then he should account for that by using an appropriate variance in Q0.

On the comparison with the Laplace approximation

The graphical comparison between Laplace and sequential inference is difficult to do, because the two methods are trying to answer to different questions.

  • The Laplace approximation finds a local-Gaussian approximation to the full posterior (after seeing all the data). This means that: (a) it cannot provide the filtering distribution at a cost that is constant in time, (b) it tends to perform well in the characterization of the full posterior (smoothing) after many steps, because the posterior tends to concentrate in the limit of infinite data.
  • The sequential inference method approximates the smoothing sequentially. This means that: (a) it provides us the filtering distributions at a cost that is constant in time, (b) the approximation of the full posterior (smoothing) is subject to accumulation of error (which probably the reason why you see that the variance diagnostic on the smoothing is better for the Laplace approximation with respect to the sequential inference algorithm)

Given this, if you want to graphically compare the two methods, you should plot the smoothing distribution given by the sequential algorithm:

The flexibility given by the sequential inference algorithm is that one can tune the approximation complexity to get the desired accuracy (which will be reflected also in better accuracy of the filtering distributions). As you probably experienced, this is done at the expences of computational time.

Monitoring convergence

One way to check whether the map you are using at each step is of the sufficient order, is to turn on the step-by-step variance diagnostic. First turn on logging at INFO level for the package TransportMaps (the indication I gave you before was turning on INFO level only for a sub-part of TransportMap):

Next, use the following setting for each step:

This will print out (and store in the variable INT.var_diag_convergence) the variance diagnostic for each step.

Using the setting above, I see that already the linear map (order 1) is doing a good job in approximating each step (the variance diagnostics are around \( < 10^{-6} \) ). This means that the fact that the variance diagnostic of the full smoothing is higher than in the Laplace approximation case, is given mostly by error accumulation. This error could be "cleaned away" by optimizing the resulting smoothing map with respect to the full posterior or by using a unbiased sampler (MCMC/importance sampling) preconditioned by this map. Both of these approach, however, defeat the purpose of filtering, because require the evaluation of the full posterior (smoothing).

I don't think you would gain anything from going to order 2, but rather you will need to use more quadrature points to identify all the coefficiens of the second order map, i.e. increase the computational cost. In our experiments (in the problems where higher orders were needed, e.g. the ones described in the tutorial) we often use an "adaptive" approach in the construction of the single maps. This feature is going to be available in the next release of the software.

I hope to have answered to most of your questions.

free variable 'x' referenced before assignment in enclosing scope

  • Send feedback

Python Scoping Rules – A Simple Illustrated Guide

Introduction to scope in python, ❖ what is name in python.

Everything in Python is an object. Since everything is an object we need to identify and distinguish each type of object from one another and this is what a name does. Name is simply a unique name given to objects in Python so that they can be identified. For example, when a function is defined in a program, it is given a name that is used to identify the function. Another example is a simple variable assignment var = 25 . Here 2 is the object stored in the memory while var is the name given to the object.

❖ What is Scope ?

The scope of a name like a variable, function, object, etc. is the region or part of the program where the name can be accessed directly. In other words, a name is visible and accessible only within its scope.

❖ What is Namespace ?

A namespace is simply a collection of names. It is a container that contains the names mapped to their respective objects. Namespaces are isolated; thus same names within different scopes do not collide.

? The namespace that contains all the built-in names is created by default because of which built-in functions like print() can be accessed from all parts of the program.

In the above example, we can see that the variable is in the global namespace as well as inside the local namespace and does not collide. Now that brings us to a very important discussion on variable scopes and the LEGB rule of scope resolution.

The LEGB Rule And Variable Scopes

Scope Of Variables In Python

LEGB is an abbreviation for Local(L)-Enclosed(E)-Global(G)-Built-In(B) and it is used to define Python Scope resolution. Let’s understand what is scope resolution and how LEGB works.

Disclaimer: The LEGB rules are specific to variable names and not attributes.

❖ Local Scope (L)

When a variable/name is created inside a function, it is only available within the scope of that function and ceases to exist if used outside the function. Thus the variable belongs to the  local scope  of the function. Every time the function is called, a new local scope is created. Local scope is also called function scope .

❖ Enclosing Scope (E)

An enclosing scope occurs when we have nested functions. When the variable is in the scope of the outside function, it means that the variable is in the enclosing scope of the function. Therefore, the variable is visible within the scope of the inner and outer functions. Enclosing Scope is often called non-local scope.

enclosed variable

In the above example, the variable  scope  is inside the enclosing scope of the function  foo()  and available inside the  foo()  as well as  func()  functions.

❖ Global Scope (G)

A global variable is a variable that is declared in a  global scope  and can be used across the entire program; that means it can be accessed inside as well outside the scope of a function. A global name is generally declared outside functions, in the main body of the Python code. In the backend, Python converts the programs main script into the __main__ module which is responsible for the execution of the main program. The namespace of the __main__ module is the global scope.

❖ Built-In Scope (B)

The built-in scope is the widest scope available in python and contains keywords, functions, exceptions, and other attributes that are built into Python. Names in the built-in scope are available all across the python program. It is loaded automatically at the time of executing a Python program/script.

❖ Example Of Scoping Rules In Python

The following diagram provides a pictorial representation of scopes rules in Python:

Understanding UnboundLocalError In Python

UnboundLocalError In Python

When a  variable  is assigned within a function, it is treated as a local variable by default in Python. If a local  variable  is referenced before a value has been assigned/bound to it, an  UnboundLocalError  is raised. In the above example when the variable  'val'  is read by the Python interpreter inside the  func()  function, it assumes that  'val'  is a local variable. However, it soon realizes that the local variable has been referenced before any value has been assigned to it within the function. Thus it throws an  UnboundLocalError .

In other words, we can only access a global variable inside a function but cannot modify it from within the function (unless you force a global or nonlocal assignment using the  global  or  nonlocal   keywords ).

Resolution: To resolve an  UnboundLocalError  when the local variable is reassigned after the first use, you can either use the  global   keyword or the  nonlocal  keyword. The  global  keyword allows you to modify the values of a global variable from within a function’s local scope while the  nonlocal  keyword provides similar functionality in the case of nested functions.

That brings us to a very important topic – global and nonlocal keywords.

The global And nonlocal Keyword In Python

❖ the global keyword.

We already read about the global scope where we learned that every variable that is declared in the main body and outside any function in the Python code is global by default. However, if we have a situation where we need to declare a global variable inside a function as in the problem statement of this article, then the  global keyword  comes to our rescue. We use the  global keyword  inside a function to make a variable global within the local scope. This means that the global keyword allows us to modify and use a variable outside the scope of the function within which it has been defined.

Now let us have a look at the following program to understand the usage of the  global  keyword.

❖ The nonlocal Keyword

The  nonlocal  keyword is useful when we have a nested function, i.e., functions having variables in the enclosing scope. In other words, if you want to change/modify a variable that is in the scope of the enclosing function (outer function), then you can use the  nonlocal  keyword. If we change the value of a  nonlocal  variable the value of the  local  variable also changes.

❖ Global Keyword vs Nonlocal Keyword

Before concluding this article, let us have a look at the key differences between a global and nonlocal variable/keywords.

  • Unlike the global keyword, the nonlocal keyword works only in Python 3 and above .
  • The global keyword can be used with pre-existing global variables or new variables whereas the nonlocal keyword must be defined with a pre-existing variable.

In this article we learned the following:

  • What are names in Python?
  • What are namespaces in Python?
  • What are scopes in Python?
  • The LEGB Scope Resolution Rule in Python.
  • The UnboundLocalError.
  • The Global and Nonlocal Keyword.

Please subscribe and stay tuned for more articles!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES! , consider becoming a Python freelance developer ! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.

You can contact me @:

UpWork LinkedIn

More than 3 years have passed since last update.

free variable 'x' referenced before assignment in enclosing scope

意外とややこしい Python のスコープを理解するためのクイズ14問

Python の変数のスコープ、参照のメカニズムは意外に直感的でない部分があり、初心者が罠にはまる可能性がある。しかし、一旦ルールを覚えればさほど複雑ではない。ここではその理解を助けるための問題を紹介する。

問題ごとに 何が出力されるか、もしくはエラーが出力されるかどうか を答えよう。実行環境は Python 3 とする。難しい(というかマニアックな)問題は見出しが 赤色 になっている。

Python では if 文はスコープを形成しない。そのため if 文内の x は外の x と同一の変数となる。

if と同様に for 文もスコープを形成しないので、ループ変数や内部で定義した変数はその for 文の後でもアクセスすることができる。

リスト内包表記(list comprehension)が実行されるとき、新たにスコープが作られそこでループ変数が定義される。そのため、外側のスコープに存在する print(x) からは x にアクセスできない。

関数 f の中から外側の変数 i を参照しているが、 print(i) が実行される時点での i の値が使われる ことになる。5つの f が実行されるのはいずれも for 文の後であり、その時点では i は 4 であるため、すべて 4 を出力することになる。

なお、リスト内包表記についても同じことが起きる。

関数 f が形成するブロック 1 には x = 1 という 代入文 が存在するため、このブロックのスコープには x という新しい変数が作られることになる。つまり、トップレベルの x は f によって変更されない。

1つ前の問題と同様に、関数 f が形成するブロックに x = 1 という 代入文が存在する ため、ブロックが実行される 前 にそのスコープに x という変数が作られる。しかし print(x) が実行される時点では x は値を持たない (unbound) であるため、例外が発生する。

+= も代入文とみなされるため、1つ前の問題と同様に f が形成するブロックに変数 x が作られる。しかし、 x += 1 が実行されるとき x の値は存在しないため、例外が発生する。

外側のスコープの変数の値を変更するには global や nonlocal を使う必要がある。

if 文はブロックを形成しないため、これも1つ前の問題と同様に f が形成するブロックに x への代入文が存在し、変数 x が作られる。しかし実際には x に値は代入されないため例外が発生する。

実は del 文も代入文と同様に、そのブロックに変数を生成する効果がある。そのため、 f が形成するブロックに変数 x が作られるが、 x の値が存在しないまま del x が実行されるため例外が発生する。

このように変数を作る効果のある構文は代入文、 del 文、 for 文、クラス定義、関数定義、 import 文、 with と except の as がある。

g が実行される時点では、一つ外側のスコープ ( f ) に x が存在し値が 1 であるため 1 が出力される。

del x が実行されても f のスコープに x は存在しつづける(値がなくなるだけ)。そのため、 g 内の x は f で定義された x を参照することになる。しかしその x は値を持たないので例外が発生する。

同じ理由で、以下の2つのコードでも同じ結果となる。

try 文で例外が発生し except 節が実行されると、その as で指定した変数は del と同様に 値が削除される 。そのため、 g が実行される時点では f 内の x は存在するが値がないため例外が発生する。

なお、 except 節が実行されなければ、該当する変数は削除されない。

クラス定義内のコードはスコープに関して特殊であり、そこで定義された変数(クラス変数)はそのスコープからしかアクセスできず、 クラス定義内の関数(つまりメソッド)からは直接アクセスできない 。

これは eval 関数の(直感に反する)振る舞いに関する問題である。 eval 関数で実行したコードからアクセスできる変数は、実は 「グローバル変数」と「 eval が実行されたブロックで定義された変数 」のみであり、その間で定義された変数にはアクセスできない。今のコードでは、 eval 関数に渡されたコードからアクセスできる(ビルトイン以外の)変数は、1行目の x と g 内で定義された変数(1つもない)である。よってトップレベルの x が参照され、 0 が出力される。

なお、 exec 関数も同様の振る舞いをする。

  • 4. Execution model — Python 3.8.0 documentation
  • satwikkansal/wtfpython: A collection of surprising Python snippets and lesser-known features.

ブロック とはスコープ1つに対応するコードのまとまりであり、ブロックごとにスコープが形成される。ブロックを形成するのは関数、モジュール(つまりトップレベル)、クラス定義である。  ↩

Register as a new user and use Qiita more conveniently

  • You get articles that match your needs
  • You can efficiently read back useful information
  • You can use dark theme

free variable 'x' referenced before assignment in enclosing scope

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

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

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

free variable 'gfk' referenced before assignment in enclosing scope #14

@abhiramsingh0

abhiramsingh0 commented Aug 1, 2018 • edited

No branches or pull requests

@abhiramsingh0

Fix "local variable referenced before assignment" in Python

free variable 'x' referenced before assignment in enclosing scope

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.

free variable 'x' referenced before assignment in enclosing scope

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.

Python Variables Scope

Not all variables are accessible from all parts of our program. The part of the program where the variable is accessible is called its “ scope ” and is determined by where the variable is declared.

Python has three different variable scopes:

  • Local scope
  • Global scope
  • Enclosing scope

Local Scope

A variable declared within a function has a LOCAL SCOPE. It is accessible from the point at which it is declared until the end of the function, and exists for as long as the function is executing.

Local variables are removed from memory when the function call exits. Therefore, trying to get the value of the local variable outside the function causes an error.

Global Scope

A variable declared outside all functions has a GLOBAL SCOPE. It is accessible throughout the file, and also inside any file which imports that file.

Global variables are often used for flags (boolean variables that indicate whether a condition is true). For example, some programs use a flag named verbose to report more information about an operation.

Modifying Globals Inside a Function

Although you can access global variables inside or outside of a function, you cannot modify it inside a function.

Here’s an example that tries to reassign a global variable inside a function.

Here, the value of global variable x didn’t change. Because Python created a new local variable named x ; which disappears when the function ends, and has no effect on the global variable.

To access the global variable rather than the local one, you need to explicitly declare x global, using the global keyword .

The x inside the function now refers to the x outside the function, so changing x inside the function changes the x outside it.

Here’s another example that tries to update a global variable inside a function.

Here, Python assumes that x is a local variable, which means that you are reading it before defining it.

The solution, again, is to declare x global.

There’s another way to update a global variable from a no-global scope – use globals() function.

Enclosing Scope

If a variable is declared in an enclosing function, it is nonlocal to nested functions. It allows you to assign to variables in an outer, but no-global, scope.

Here’s an example that tries to reassign enclosing (outer) function’s local variable inside a nested (inner) function.

Here, the value of existing variable x didn’t change. Because Python created a new local variable named x that shadows the variable in the outer scope.

Preventing that behavior is where the nonlocal keyword comes in.

The x inside the nested function now refers to the x outside the function, so changing x inside the function changes the x outside it.

The usage of nonlocal is very similar to that of global, except that the former is primarily used in nested methods.

Scoping Rule – LEGB Rule

python scoping rule legb rule

When a variable is referenced, Python follows LEGB rule and searches up to four scopes in this order:

first in the local (L) scope,

then in the local scopes of any enclosing (E) functions and lambdas,

then in the global (G) scope,

and finally in then the built-in (B) scope

and stops at the first occurrence. If no match is found, Python raises a NameError exception.

IMAGES

  1. [Solved] Python: NameError: free variable 're' referenced

    free variable 'x' referenced before assignment in enclosing scope

  2. An Essential Guide to Python nonlocal Scopes and nonlocal Variables

    free variable 'x' referenced before assignment in enclosing scope

  3. NameError: free variable 'url' referenced before assignment in

    free variable 'x' referenced before assignment in enclosing scope

  4. Worksheets for Python Global Variable In Function Referenced Before

    free variable 'x' referenced before assignment in enclosing scope

  5. [Solved] Local variable defined in an enclosing scope

    free variable 'x' referenced before assignment in enclosing scope

  6. "Fixing UnboundLocalError: Local Variable Referenced Before Assignment

    free variable 'x' referenced before assignment in enclosing scope

VIDEO

  1. Flask+Mysql #CURD OPERATION#rlocal variable 'cursor' referenced before assignment

  2. Week 08 : Functions (Part 3)

  3. error in django: local variable 'context' referenced before assignment

  4. Lamda Expressions Access Variable? #JavaProgramming #Java8Features #LambdaExpressions

  5. Normalization Attribute Closure

  6. Lesson 1 Part 9

COMMENTS

  1. How can "NameError: free variable 'var' referenced before assignment in

    NameError: free variable 'var' referenced before assignment in enclosing scope. When we talk about free variables, we're dealing with nested functions. Python has done some "magic" in order to give nested functions the ability to access the variables defined inside their parent scope. If we have:

  2. free variable referenced before assignment in enclosing scope

    Local variable referenced before assignment in Python 11 How can "NameError: free variable 'var' referenced before assignment in enclosing scope" occur in real code?

  3. Python: NameError: free variable 're' referenced before assignment in

    NameError: free variable 're' referenced before assignment in enclosing scope Share. Improve this answer. Follow answered Jan 10, 2019 at 3:12. Yasin Zähringer Yasin Zähringer. 621 6 6 ... NameError: free variable 'product' referenced before assignment in enclosing scope. Related. 0.

  4. NameError: free variable 'product' referenced before assignment ...

    Best Answer. Hi, You are filtering the room_line_ids in your for loop as below. lambda l: l.order_line_id.product_id == product. But the product variable in the right side of the expression is not assigned to any value. 0.

  5. Issue 4617: SyntaxError when free variable name is also an exception

    After all, the "variable referenced" has no value before it is set, accessing it raises either NameError("free variable referenced before assignment in enclosing scope") or UnboundLocalError("local variable referenced before assignment") The Attached patch adds a DELETE_DEREF opcode, that removes the value of a cell variable, and put it in a ...

  6. free variable 'do_return_5' referenced before assignment in enclosing

    free variable 'do_return_5' referenced before assignment in enclosing scope #1622. Closed SamNPowers opened this issue Nov 12, 2019 ... Unknown: NameError: free variable 'do_return_5' referenced before assignment in enclosing scope Traceback (most recent call last): File "C:\Users<my_path>\lib\site-packages\tensorflow_core\python\ops\script_ops ...

  7. NameError: free variable 'i' referenced before assignment in enclosing

    NameError: free variable 'i' referenced before assignment in enclosing scope #13. Closed lomnom opened this issue Jun 11, 2023 · 1 comment Closed ... '=', self.namespace)) NameError: free variable 'i' referenced before assignment in enclosing scope ...

  8. I got an error "NameError: free variable 'gfk' referenced before

    'gfk' referenced before assignment in enclosing scope. Remember. Register; TransportMaps Q&A. Questions; Unanswered; Users; ... , 1521 success=(warnflag == 0), message=msg, x=xk, NameError: free variable 'gfk' referenced before assignment in enclosing scope asked Apr 6, 2018 in usage by ...

  9. NameError: free variable 'outer' referenced before assignment in

    BPO 46859 Nosy @asvetlov, @1st1, @JelleZijlstra, @miss-islington, @sobolevn, @onerandomusername Note: these values reflect the state of the issue at the time it was migrated and might not reflect t...

  10. Exploring the Local, Enclosing, and Global Scope

    And the reason for this is because the print() function in line 6 is not in the same local scope as a variable definition of total. 01:54 The E in LEGB stands for enclosing. The enclosing scope is a special scope that only exists for nested functions. Names that you define in the enclosing scope are commonly known as nonlocal names.

  11. Python Scoping Rules

    An enclosing scope occurs when we have nested functions. When the variable is in the scope of the outside function, it means that the variable is in the enclosing scope of the function. Therefore, the variable is visible within the scope of the inner and outer functions. Enclosing Scope is often called non-local scope. def foo():

  12. 意外とややこしい Python のスコープを理解するためのクイズ14問 #Python

    (del x のとこで) UnboundLocalError: local variable 'x' referenced before assignment 実は del 文も代入文と同様に、そのブロックに変数を生成する効果がある。 そのため、 f が形成するブロックに変数 x が作られるが、 x の値が存在しないまま del x が実行されるため例外が ...

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

  14. Python Variable Scope

    Types of Python Variable Scope. There are 4 types of Variable Scope in Python, let's discuss them one by one: Python Variable Scope - Types. 1. Local Scope in Python. In the above code, we define a variable 'a' in a function 'func'. So, 'a' is local to 'func'. Hence, we can read/write it in func, but not outside it.

  15. Local variable referenced before assignment in Python

    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.

  16. free variable 'gfk' referenced before assignment in enclosing scope

    NameError: free variable 'gfk' referenced before assignment in enclosing scope. Please fix this issue. The text was updated successfully, but these errors were encountered:

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

  18. Python Variables Scope

    It allows you to assign to variables in an outer, but no-global, scope. Here's an example that tries to reassign enclosing (outer) function's local variable inside a nested (inner) function. x = 42 # nested function def f2(): x = 0 print(x) # x is 0. f2() print(x) # x is still 42.

  19. python 3 local variable defined in enclosing scope referenced before

    python 3 local variable defined in enclosing scope referenced before assignment. I have declared global variables that i need to access and modify in a function in a class. This function loops indefinitely once called and stream data passes through it. I need to be able to use x y z variables inside the function, and redefine their values as ...

  20. Python Scope & the LEGB Rule: Resolving Names in Your Code

    square() is a function that computes the square of a given number, base.When you call the function, Python creates a local scope containing the names base (an argument) and result (a local variable). After the first call to square(), base holds a value of 10 and result holds a value of 100.The second time, the local names will not remember the values that were stored in them the first time the ...

  21. Why am I getting "free variable 'is_noun' referenced before assignment

    You are using is_noun in the first for loop before it is even defined. This definition happens only after. This definition happens only after. Move your is_noun = lambda pos: pos[:2] == 'NN' line at the beginning of the function code.

  22. 【Python】成功解决UnboundLocalError: local variable 'a' referenced before

    Python 中出现 UnboundLocalError: local variable 'xxx' reference d before assignment 情况的 解决 方法. variable 'xxx' d before 在函数外部已经定义了变量n,在函数内部对该变量进行运算,运行时会遇到了这样的错误:主要是因为没有让解释器清楚变量是全局变量还是局部变量 ...