Fix "local variable referenced before assignment" in Python

python3 global variable 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.

python3 global variable 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.

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

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

by Nathan Sebhastian

Posted on May 26, 2023

Reading time: 2 minutes

python3 global variable 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:

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)

How to Fix Local Variable Referenced Before Assignment Error in Python

How to Fix Local Variable Referenced Before Assignment Error in Python

Table of Contents

Fixing local variable referenced before assignment error.

In Python , when you try to reference a variable that hasn't yet been given a value (assigned), it will throw an error.

That error will look like this:

In this post, we'll see examples of what causes this and how to fix it.

Let's begin by looking at an example of this error:

If you run this code, you'll get

The issue is that in this line:

We are defining a local variable called value and then trying to use it before it has been assigned a value, instead of using the variable that we defined in the first line.

If we want to refer the variable that was defined in the first line, we can make use of the global keyword.

The global keyword is used to refer to a variable that is defined outside of a function.

Let's look at how using global can fix our issue here:

Global variables have global scope, so you can referenced them anywhere in your code, thus avoiding the error.

If you run this code, you'll get this output:

In this post, we learned at how to avoid the local variable referenced before assignment error in Python.

The error stems from trying to refer to a variable without an assigned value, so either make use of a global variable using the global keyword, or assign the variable a value before using it.

Thanks for reading!

python3 global variable referenced before assignment

  • Privacy Policy
  • Terms of Service
  • 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 That Prints Out the Decimal Equivalents of 1/2, 1/3, 1/4, . . . ,1/10
  • How to Convert PIL Image into pygame surface image?
  • Python program to print the binary value of the numbers from 1 to N
  • Python Program for Sum the digits of a given number
  • Python program to print number of bits to store an integer and also the number in Binary format
  • Python program to get all pairwise combinations from a list
  • Python program to repeat M characters of a string N times
  • How to format a string using a dictionary in Python
  • Python program to convert binary to ASCII
  • Python program to convert unix timestamp string to readable date
  • Python program to print an array of bytes representing an integer
  • Python Program to Multiply Two Binary Numbers
  • Python Program to Find Sum of First and Last Digit
  • Python Program to Sort Words in Alphabetical Order
  • Python program to convert integer to roman
  • Python - Lambda Function to Check if value is in a List
  • Python - Get first element from a List of tuples
  • Get Your System Information - Using Python Script
  • Python - Get the object with the max attribute value in a list of objects

UnboundLocalError Local variable Referenced Before Assignment in Python

Handling errors is an integral part of writing robust and reliable Python code. One common stumbling block that developers often encounter is the “UnboundLocalError” raised within a try-except block. This error can be perplexing for those unfamiliar with its nuances but fear not – in this article, we will delve into the intricacies of the UnboundLocalError and provide a comprehensive guide on how to effectively use try-except statements to resolve it.

What is UnboundLocalError Local variable Referenced Before Assignment in Python?

The UnboundLocalError occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution.

Why does UnboundLocalError: Local variable Referenced Before Assignment Occur?

below, are the reasons of occurring “Unboundlocalerror: Try Except Statements” in Python :

Variable Assignment Inside Try Block

Reassigning a global variable inside except block.

  • Accessing a Variable Defined Inside an If Block

In the below code, example_function attempts to execute some_operation within a try-except block. If an exception occurs, it prints an error message. However, if no exception occurs, it prints the value of the variable result outside the try block, leading to an UnboundLocalError since result might not be defined if an exception was caught.

In below code , modify_global function attempts to increment the global variable global_var within a try block, but it raises an UnboundLocalError. This error occurs because the function treats global_var as a local variable due to the assignment operation within the try block.

Solution for UnboundLocalError Local variable Referenced Before Assignment

Below, are the approaches to solve “Unboundlocalerror: Try Except Statements”.

Initialize Variables Outside the Try Block

Avoid reassignment of global variables.

In modification to the example_function is correct. Initializing the variable result before the try block ensures that it exists even if an exception occurs within the try block. This helps prevent UnboundLocalError when trying to access result in the print statement outside the try block.

Below, code calculates a new value ( local_var ) based on the global variable and then prints both the local and global variables separately. It demonstrates that the global variable is accessed directly without being reassigned within the function.

In conclusion , To fix “UnboundLocalError” related to try-except statements, ensure that variables used within the try block are initialized before the try block starts. This can be achieved by declaring the variables with default values or assigning them None outside the try block. Additionally, when modifying global variables within a try block, use the `global` keyword to explicitly declare them.

Please Login to comment...

  • Python Errors
  • WhatsApp To Launch New App Lock Feature
  • Node.js 21 is here: What’s new
  • Zoom: World’s Most Innovative Companies of 2024
  • 10 Best Skillshare Alternatives in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

python3 global variable 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

How to Solve Error - Local Variable Referenced Before Assignment in Python

  • Python How-To's
  • How to Solve Error - Local Variable …

Check the Variable Scope to Fix the local variable referenced before assignment Error in Python

Initialize the variable before use to fix the local variable referenced before assignment error in python, use conditional assignment to fix the local variable referenced before assignment error in python.

How to Solve Error - Local Variable Referenced Before Assignment in Python

This article delves into various strategies to resolve the common local variable referenced before assignment error. By exploring methods such as checking variable scope, initializing variables before use, conditional assignments, and more, we aim to equip both novice and seasoned programmers with practical solutions.

Each method is dissected with examples, demonstrating how subtle changes in code can prevent this frequent error, enhancing the robustness and readability of your Python projects.

The local variable referenced before assignment occurs when some variable is referenced before assignment within a function’s body. The error usually occurs when the code is trying to access the global variable.

The primary purpose of managing variable scope is to ensure that variables are accessible where they are needed while maintaining code modularity and preventing unexpected modifications to global variables.

We can declare the variable as global using the global keyword in Python. Once the variable is declared global, the program can access the variable within a function, and no error will occur.

The below example code demonstrates the code scenario where the program will end up with the local variable referenced before assignment error.

In this example, my_var is a global variable. Inside update_var , we attempt to modify it without declaring its scope, leading to the Local Variable Referenced Before Assignment error.

We need to declare the my_var variable as global using the global keyword to resolve this error. The below example code demonstrates how the error can be resolved using the global keyword in the above code scenario.

In the corrected code, we use the global keyword to inform Python that my_var references the global variable.

When we first print my_var , it displays the original value from the global scope.

After assigning a new value to my_var , it updates the global variable, not a local one. This way, we effectively tell Python the scope of our variable, thus avoiding any conflicts between local and global variables with the same name.

python local variable referenced before assignment - output 1

Ensure that the variable is initialized with some value before using it. This can be done by assigning a default value to the variable at the beginning of the function or code block.

The main purpose of initializing variables before use is to ensure that they have a defined state before any operations are performed on them. This practice is not only crucial for avoiding the aforementioned error but also promotes writing clear and predictable code, which is essential in both simple scripts and complex applications.

In this example, the variable total is used in the function calculate_total without prior initialization, leading to the Local Variable Referenced Before Assignment error. The below example code demonstrates how the error can be resolved in the above code scenario.

In our corrected code, we initialize the variable total with 0 before using it in the loop. This ensures that when we start adding item values to total , it already has a defined state (in this case, 0).

This initialization is crucial because it provides a starting point for accumulation within the loop. Without this step, Python does not know the initial state of total , leading to the error.

python local variable referenced before assignment - output 2

Conditional assignment allows variables to be assigned values based on certain conditions or logical expressions. This method is particularly useful when a variable’s value depends on certain prerequisites or states, ensuring that a variable is always initialized before it’s used, thereby avoiding the common error.

In this example, message is only assigned within the if and elif blocks. If neither condition is met (as with guest ), the variable message remains uninitialized, leading to the Local Variable Referenced Before Assignment error when trying to print it.

The below example code demonstrates how the error can be resolved in the above code scenario.

In the revised code, we’ve included an else statement as part of our conditional logic. This guarantees that no matter what value user_type holds, the variable message will be assigned some value before it is used in the print function.

This conditional assignment ensures that the message is always initialized, thereby eliminating the possibility of encountering the Local Variable Referenced Before Assignment error.

python local variable referenced before assignment - output 3

Throughout this article, we have explored multiple approaches to address the Local Variable Referenced Before Assignment error in Python. From the nuances of variable scope to the effectiveness of initializations and conditional assignments, these strategies are instrumental in developing error-free code.

The key takeaway is the importance of understanding variable scope and initialization in Python. By applying these methods appropriately, programmers can not only resolve this specific error but also enhance the overall quality and maintainability of their code, making their programming journey smoother and more rewarding.

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:

Adventures in Machine Learning

4 ways to fix local variable referenced before assignment error in python, resolving the local variable referenced before assignment error in python.

Python is one of the world’s most popular programming languages due to its simplicity, readability, and versatility. Despite its many advantages, when coding in Python, one may encounter various errors, with the most common being the “local variable referenced before assignment” error.

Even the most experienced Python developers have encountered this error at some point in their programming career. In this article, we will look at four effective strategies for resolving the local variable referenced before assignment error in Python.

Strategy 1: Assigning a Value before Referencing

The first strategy is to assign a value to a variable before referencing it. The error occurs when the variable is referenced before it is assigned a value.

This problem can be avoided by initializing the variable before referencing it. For example, let us consider the snippet below:

“`python

add_numbers():

print(x + y)

add_numbers()

In the snippet above, the variables `x` and `y` are not assigned values before they are referenced in the `print` statement. Therefore, we will get a local variable “referenced before assignment” error.

To resolve this error, we must initialize the variables before referencing them. We can avoid this error by assigning a value to `x` and `y` before they are referenced, as shown below:

Strategy 2: Using the Global Keyword

In Python, variables declared inside a function are considered local variables. Thus, they are separate from other variables declared outside of the function.

If we want to use a variable outside of the function, we must use the global keyword. Using the global keyword tells Python that you want to use the variable that was defined globally, not locally.

For example:

In the code snippet above, the `global` keyword tells Python to use the variable `x` defined outside of the function rather than a local variable named `x`. Thus, Python will output 30.

Strategy 3: Adding Input Parameters for Functions

Another way to avoid the local variable referenced before assignment error is by adding input parameters to functions.

def add_numbers(x, y):

add_numbers(10, 20)

In the code snippet above, `x` and `y` are variables that are passed into the `add_numbers` function as arguments.

This approach allows us to avoid the local variable referenced before assignment error because the variables are being passed into the function as input parameters. Strategy 4: Initializing Variables before Loops or Conditionals

Finally, it’s also a good practice to initialize the variables before loops or conditionals.

If you are defining a variable within a loop, you must initialize it before the loop starts. This way, the variable already exists, and we can update the value inside the loop.

my_list = [1, 2, 3, 4, 5]

for number in my_list:

sum += number

In the code snippet above, the variable `sum` has been initialized with the value of 0 before the loop runs. Thus, we can update and use the variable inside the loop.

In conclusion, the “local variable referenced before assignment” error is a common issue in Python. However, with the strategies discussed in this article, you can avoid the error and write clean Python code.

Remember to initialize your variables, use the global keyword, add input parameters in functions, and initialize variables before loops or conditionals. By following these techniques, your Python code will be error-free and much easier to manage.

In essence, this article has provided four key strategies for resolving the “local variable referenced before assignment” error that is common in Python. These strategies include initializing variables before referencing, using the global keyword, adding input parameters to functions, and initializing variables before loops or conditionals.

These techniques help to ensure clean code that is free from errors. By implementing these strategies, developers can improve their code quality and avoid time-wasting errors that can occur in their work.

Popular Posts

Mastering convex hulls: implementation and applications, pandas row selection: the comprehensive guide, mastering memory management in python: from hardware to software.

  • Terms & Conditions
  • Privacy Policy

[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

  • Python »
  • 3.12.2 Documentation »
  • Python Frequently Asked Questions »
  • Programming FAQ
  • Theme Auto Light Dark |

Programming FAQ ¶

General questions ¶, is there a source code level debugger with breakpoints, single-stepping, etc. ¶.

Several debuggers for Python are described below, and the built-in function breakpoint() allows you to drop into any of them.

The pdb module is a simple but adequate console-mode debugger for Python. It is part of the standard Python library, and is documented in the Library Reference Manual . You can also write your own debugger by using the code for pdb as an example.

The IDLE interactive development environment, which is part of the standard Python distribution (normally available as Tools/scripts/idle3 ), includes a graphical debugger.

PythonWin is a Python IDE that includes a GUI debugger based on pdb. The PythonWin debugger colors breakpoints and has quite a few cool features such as debugging non-PythonWin programs. PythonWin is available as part of pywin32 project and as a part of the ActivePython distribution.

Eric is an IDE built on PyQt and the Scintilla editing component.

trepan3k is a gdb-like debugger.

Visual Studio Code is an IDE with debugging tools that integrates with version-control software.

There are a number of commercial Python IDEs that include graphical debuggers. They include:

Are there tools to help find bugs or perform static analysis? ¶

Pylint and Pyflakes do basic checking that will help you catch bugs sooner.

Static type checkers such as Mypy , Pyre , and Pytype can check type hints in Python source code.

How can I create a stand-alone binary from a Python script? ¶

You don’t need the ability to compile Python to C code if all you want is a stand-alone program that users can download and run without having to install the Python distribution first. There are a number of tools that determine the set of modules required by a program and bind these modules together with a Python binary to produce a single executable.

One is to use the freeze tool, which is included in the Python source tree as Tools/freeze . It converts Python byte code to C arrays; with a C compiler you can embed all your modules into a new program, which is then linked with the standard Python modules.

It works by scanning your source recursively for import statements (in both forms) and looking for the modules in the standard Python path as well as in the source directory (for built-in modules). It then turns the bytecode for modules written in Python into C code (array initializers that can be turned into code objects using the marshal module) and creates a custom-made config file that only contains those built-in modules which are actually used in the program. It then compiles the generated C code and links it with the rest of the Python interpreter to form a self-contained binary which acts exactly like your script.

The following packages can help with the creation of console and GUI executables:

Nuitka (Cross-platform)

PyInstaller (Cross-platform)

PyOxidizer (Cross-platform)

cx_Freeze (Cross-platform)

py2app (macOS only)

py2exe (Windows only)

Are there coding standards or a style guide for Python programs? ¶

Yes. The coding style required for standard library modules is documented as PEP 8 .

Core Language ¶

Why am i getting an unboundlocalerror when the variable has a value ¶.

It can be a surprise to get the UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function.

works, but this code:

results in an UnboundLocalError :

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x , the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.

In the example above you can access the outer scope variable by declaring it global:

This explicit declaration is required in order to remind you that (unlike the superficially analogous situation with class and instance variables) you are actually modifying the value of the variable in the outer scope:

You can do a similar thing in a nested scope using the nonlocal keyword:

What are the rules for local and global variables in Python? ¶

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Why do lambdas defined in a loop with different values all return the same result? ¶

Assume you use a for loop to define a few different lambdas (or even plain functions), e.g.:

This gives you a list that contains 5 lambdas that calculate x**2 . You might expect that, when called, they would return, respectively, 0 , 1 , 4 , 9 , and 16 . However, when you actually try you will see that they all return 16 :

This happens because x is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined. At the end of the loop, the value of x is 4 , so all the functions now return 4**2 , i.e. 16 . You can also verify this by changing the value of x and see how the results of the lambdas change:

In order to avoid this, you need to save the values in variables local to the lambdas, so that they don’t rely on the value of the global x :

Here, n=x creates a new variable n local to the lambda and computed when the lambda is defined so that it has the same value that x had at that point in the loop. This means that the value of n will be 0 in the first lambda, 1 in the second, 2 in the third, and so on. Therefore each lambda will now return the correct result:

Note that this behaviour is not peculiar to lambdas, but applies to regular functions too.

How do I share global variables across modules? ¶

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:

Note that using a module is also the basis for implementing the singleton design pattern, for the same reason.

What are the “best practices” for using import in a module? ¶

In general, don’t use from modulename import * . Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.

Import modules at the top of a file. Doing so makes it clear what other modules your code requires and avoids questions of whether the module name is in scope. Using one import per line makes it easy to add and delete module imports, but using multiple imports per line uses less screen space.

It’s good practice if you import modules in the following order:

standard library modules – e.g. sys , os , argparse , re

third-party library modules (anything installed in Python’s site-packages directory) – e.g. dateutil , requests , PIL.Image

locally developed modules

It is sometimes necessary to move imports to a function or class to avoid problems with circular imports. Gordon McMillan says:

Circular imports are fine where both modules use the “import <module>” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level. That’s because names in the 1st are not yet available, because the first module is busy importing the 2nd.

In this case, if the second module is only used in one function, then the import can easily be moved into that function. By the time the import is called, the first module will have finished initializing, and the second module can do its import.

It may also be necessary to move imports out of the top level of code if some of the modules are platform-specific. In that case, it may not even be possible to import all of the modules at the top of the file. In this case, importing the correct modules in the corresponding platform-specific code is a good option.

Only move imports into a local scope, such as inside a function definition, if it’s necessary to solve a problem such as avoiding a circular import or are trying to reduce the initialization time of a module. This technique is especially helpful if many of the imports are unnecessary depending on how the program executes. You may also want to move imports into a function if the modules are only ever used in that function. Note that loading a module the first time may be expensive because of the one time initialization of the module, but loading a module multiple times is virtually free, costing only a couple of dictionary lookups. Even if the module name has gone out of scope, the module is probably available in sys.modules .

Why are default values shared between objects? ¶

This type of bug commonly bites neophyte programmers. Consider this function:

The first time you call this function, mydict contains a single item. The second time, mydict contains two items because when foo() begins executing, mydict starts out with an item already in it.

It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object.

By definition, immutable objects such as numbers, strings, tuples, and None , are safe from change. Changes to mutable objects such as dictionaries, lists, and class instances can lead to confusion.

Because of this feature, it is good programming practice to not use mutable objects as default values. Instead, use None as the default value and inside the function, check if the parameter is None and create a new list/dictionary/whatever if it is. For example, don’t write:

This feature can be useful. When you have a function that’s time-consuming to compute, a common technique is to cache the parameters and the resulting value of each call to the function, and return the cached value if the same value is requested again. This is called “memoizing”, and can be implemented like this:

You could use a global variable containing a dictionary instead of the default value; it’s a matter of taste.

How can I pass optional or keyword parameters from one function to another? ¶

Collect the arguments using the * and ** specifiers in the function’s parameter list; this gives you the positional arguments as a tuple and the keyword arguments as a dictionary. You can then pass these arguments when calling another function by using * and ** :

What is the difference between arguments and parameters? ¶

Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what kind of arguments a function can accept. For example, given the function definition:

foo , bar and kwargs are parameters of func . However, when calling func , for example:

the values 42 , 314 , and somevar are arguments.

Why did changing list ‘y’ also change list ‘x’? ¶

If you wrote code like:

you might be wondering why appending an element to y changed x too.

There are two factors that produce this result:

Variables are simply names that refer to objects. Doing y = x doesn’t create a copy of the list – it creates a new variable y that refers to the same object x refers to. This means that there is only one object (the list), and both x and y refer to it.

Lists are mutable , which means that you can change their content.

After the call to append() , the content of the mutable object has changed from [] to [10] . Since both the variables refer to the same object, using either name accesses the modified value [10] .

If we instead assign an immutable object to x :

we can see that in this case x and y are not equal anymore. This is because integers are immutable , and when we do x = x + 1 we are not mutating the int 5 by incrementing its value; instead, we are creating a new object (the int 6 ) and assigning it to x (that is, changing which object x refers to). After this assignment we have two objects (the ints 6 and 5 ) and two variables that refer to them ( x now refers to 6 but y still refers to 5 ).

Some operations (for example y.append(10) and y.sort() ) mutate the object, whereas superficially similar operations (for example y = y + [10] and sorted(y) ) create a new object. In general in Python (and in all cases in the standard library) a method that mutates an object will return None to help avoid getting the two types of operations confused. So if you mistakenly write y.sort() thinking it will give you a sorted copy of y , you’ll instead end up with None , which will likely cause your program to generate an easily diagnosed error.

However, there is one class of operations where the same operation sometimes has different behaviors with different types: the augmented assignment operators. For example, += mutates lists but not tuples or ints ( a_list += [1, 2, 3] is equivalent to a_list.extend([1, 2, 3]) and mutates a_list , whereas some_tuple += (1, 2, 3) and some_int += 1 create new objects).

In other words:

If we have a mutable object ( list , dict , set , etc.), we can use some specific operations to mutate it and all the variables that refer to it will see the change.

If we have an immutable object ( str , int , tuple , etc.), all the variables that refer to it will always see the same value, but operations that transform that value into a new value always return a new object.

If you want to know if two variables refer to the same object or not, you can use the is operator, or the built-in function id() .

How do I write a function with output parameters (call by reference)? ¶

Remember that arguments are passed by assignment in Python. Since assignment just creates references to objects, there’s no alias between an argument name in the caller and callee, and so no call-by-reference per se. You can achieve the desired effect in a number of ways.

By returning a tuple of the results:

This is almost always the clearest solution.

By using global variables. This isn’t thread-safe, and is not recommended.

By passing a mutable (changeable in-place) object:

By passing in a dictionary that gets mutated:

Or bundle up values in a class instance:

There’s almost never a good reason to get this complicated.

Your best choice is to return a tuple containing the multiple results.

How do you make a higher order function in Python? ¶

You have two choices: you can use nested scopes or you can use callable objects. For example, suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b . Using nested scopes:

Or using a callable object:

In both cases,

gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2 .

The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:

Object can encapsulate state for several methods:

Here inc() , dec() and reset() act like functions which share the same counting variable.

How do I copy an object in Python? ¶

In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can.

Some objects can be copied more easily. Dictionaries have a copy() method:

Sequences can be copied by slicing:

How can I find the methods or attributes of an object? ¶

For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.

How can my code discover the name of an object? ¶

Generally speaking, it can’t, because objects don’t really have names. Essentially, assignment always binds a name to a value; the same is true of def and class statements, but in that case the value is a callable. Consider the following code:

Arguably the class has a name: even though it is bound to two names and invoked through the name B the created instance is still reported as an instance of class A . However, it is impossible to say whether the instance’s name is a or b , since both names are bound to the same value.

Generally speaking it should not be necessary for your code to “know the names” of particular values. Unless you are deliberately writing introspective programs, this is usually an indication that a change of approach might be beneficial.

In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to this question:

The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn’t really care – so the only way to find out what it’s called is to ask all your neighbours (namespaces) if it’s their cat (object)… ….and don’t be surprised if you’ll find that it’s known by many names, or no name at all!

What’s up with the comma operator’s precedence? ¶

Comma is not an operator in Python. Consider this session:

Since the comma is not an operator, but a separator between expressions the above is evaluated as if you had entered:

The same is true of the various assignment operators ( = , += etc). They are not truly operators but syntactic delimiters in assignment statements.

Is there an equivalent of C’s “?:” ternary operator? ¶

Yes, there is. The syntax is as follows:

Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators:

However, this idiom is unsafe, as it can give wrong results when on_true has a false boolean value. Therefore, it is always better to use the ... if ... else ... form.

Is it possible to write obfuscated one-liners in Python? ¶

Yes. Usually this is done by nesting lambda within lambda . See the following three examples, slightly adapted from Ulf Bartelt:

Don’t try this at home, kids!

What does the slash(/) in the parameter list of a function mean? ¶

A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position. For example, divmod() is a function that accepts positional-only parameters. Its documentation looks like this:

The slash at the end of the parameter list means that both parameters are positional-only. Thus, calling divmod() with keyword arguments would lead to an error:

Numbers and strings ¶

How do i specify hexadecimal and octal integers ¶.

To specify an octal digit, precede the octal value with a zero, and then a lower or uppercase “o”. For example, to set the variable “a” to the octal value “10” (8 in decimal), type:

Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero, and then a lower or uppercase “x”. Hexadecimal digits can be specified in lower or uppercase. For example, in the Python interpreter:

Why does -22 // 10 return -3? ¶

It’s primarily driven by the desire that i % j have the same sign as j . If you want that, and also want:

then integer division has to return the floor. C also requires that identity to hold, and then compilers that truncate i // j need to make i % j have the same sign as i .

There are few real use cases for i % j when j is negative. When j is positive, there are many, and in virtually all of them it’s more useful for i % j to be >= 0 . If the clock says 10 now, what did it say 200 hours ago? -190 % 12 == 2 is useful; -190 % 12 == -10 is a bug waiting to bite.

How do I get int literal attribute instead of SyntaxError? ¶

Trying to lookup an int literal attribute in the normal manner gives a SyntaxError because the period is seen as a decimal point:

The solution is to separate the literal from the period with either a space or parentheses.

How do I convert a string to a number? ¶

For integers, use the built-in int() type constructor, e.g. int('144') == 144 . Similarly, float() converts to floating-point, e.g. float('144') == 144.0 .

By default, these interpret the number as decimal, so that int('0144') == 144 holds true, and int('0x144') raises ValueError . int(string, base) takes the base to convert from as a second optional argument, so int( '0x144', 16) == 324 . If the base is specified as 0, the number is interpreted using Python’s rules: a leading ‘0o’ indicates octal, and ‘0x’ indicates a hex number.

Do not use the built-in function eval() if all you need is to convert strings to numbers. eval() will be significantly slower and it presents a security risk: someone could pass you a Python expression that might have unwanted side effects. For example, someone could pass __import__('os').system("rm -rf $HOME") which would erase your home directory.

eval() also has the effect of interpreting numbers as Python expressions, so that e.g. eval('09') gives a syntax error because Python does not allow leading ‘0’ in a decimal number (except ‘0’).

How do I convert a number to a string? ¶

To convert, e.g., the number 144 to the string '144' , use the built-in type constructor str() . If you want a hexadecimal or octal representation, use the built-in functions hex() or oct() . For fancy formatting, see the f-strings and Format String Syntax sections, e.g. "{:04d}".format(144) yields '0144' and "{:.3f}".format(1.0/3.0) yields '0.333' .

How do I modify a string in place? ¶

You can’t, because strings are immutable. In most situations, you should simply construct a new string from the various parts you want to assemble it from. However, if you need an object with the ability to modify in-place unicode data, try using an io.StringIO object or the array module:

How do I use strings to call functions/methods? ¶

There are various techniques.

The best is to use a dictionary that maps strings to functions. The primary advantage of this technique is that the strings do not need to match the names of the functions. This is also the primary technique used to emulate a case construct:

Use the built-in function getattr() :

Note that getattr() works on any object, including classes, class instances, modules, and so on.

This is used in several places in the standard library, like this:

Use locals() to resolve the function name:

Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings? ¶

You can use S.rstrip("\r\n") to remove all occurrences of any line terminator from the end of the string S without removing other trailing whitespace. If the string S represents more than one line, with several empty lines at the end, the line terminators for all the blank lines will be removed:

Since this is typically only desired when reading text one line at a time, using S.rstrip() this way works well.

Is there a scanf() or sscanf() equivalent? ¶

Not as such.

For simple input parsing, the easiest approach is usually to split the line into whitespace-delimited words using the split() method of string objects and then convert decimal strings to numeric values using int() or float() . split() supports an optional “sep” parameter which is useful if the line uses something other than whitespace as a separator.

For more complicated input parsing, regular expressions are more powerful than C’s sscanf and better suited for the task.

What does ‘UnicodeDecodeError’ or ‘UnicodeEncodeError’ error mean? ¶

See the Unicode HOWTO .

Can I end a raw string with an odd number of backslashes? ¶

A raw string ending with an odd number of backslashes will escape the string’s quote:

There are several workarounds for this. One is to use regular strings and double the backslashes:

Another is to concatenate a regular string containing an escaped backslash to the raw string:

It is also possible to use os.path.join() to append a backslash on Windows:

Note that while a backslash will “escape” a quote for the purposes of determining where the raw string ends, no escaping occurs when interpreting the value of the raw string. That is, the backslash remains present in the value of the raw string:

Also see the specification in the language reference .

Performance ¶

My program is too slow. how do i speed it up ¶.

That’s a tough one, in general. First, here are a list of things to remember before diving further:

Performance characteristics vary across Python implementations. This FAQ focuses on CPython .

Behaviour can vary across operating systems, especially when talking about I/O or multi-threading.

You should always find the hot spots in your program before attempting to optimize any code (see the profile module).

Writing benchmark scripts will allow you to iterate quickly when searching for improvements (see the timeit module).

It is highly recommended to have good code coverage (through unit testing or any other technique) before potentially introducing regressions hidden in sophisticated optimizations.

That being said, there are many tricks to speed up Python code. Here are some general principles which go a long way towards reaching acceptable performance levels:

Making your algorithms faster (or changing to faster ones) can yield much larger benefits than trying to sprinkle micro-optimization tricks all over your code.

Use the right data structures. Study documentation for the Built-in Types and the collections module.

When the standard library provides a primitive for doing something, it is likely (although not guaranteed) to be faster than any alternative you may come up with. This is doubly true for primitives written in C, such as builtins and some extension types. For example, be sure to use either the list.sort() built-in method or the related sorted() function to do sorting (and see the Sorting Techniques for examples of moderately advanced usage).

Abstractions tend to create indirections and force the interpreter to work more. If the levels of indirection outweigh the amount of useful work done, your program will be slower. You should avoid excessive abstraction, especially under the form of tiny functions or methods (which are also often detrimental to readability).

If you have reached the limit of what pure Python can allow, there are tools to take you further away. For example, Cython can compile a slightly modified version of Python code into a C extension, and can be used on many different platforms. Cython can take advantage of compilation (and optional type annotations) to make your code significantly faster than when interpreted. If you are confident in your C programming skills, you can also write a C extension module yourself.

The wiki page devoted to performance tips .

What is the most efficient way to concatenate many strings together? ¶

str and bytes objects are immutable, therefore concatenating many strings together is inefficient as each concatenation creates a new object. In the general case, the total runtime cost is quadratic in the total string length.

To accumulate many str objects, the recommended idiom is to place them into a list and call str.join() at the end:

(another reasonably efficient idiom is to use io.StringIO )

To accumulate many bytes objects, the recommended idiom is to extend a bytearray object using in-place concatenation (the += operator):

Sequences (Tuples/Lists) ¶

How do i convert between tuples and lists ¶.

The type constructor tuple(seq) converts any sequence (actually, any iterable) into a tuple with the same items in the same order.

For example, tuple([1, 2, 3]) yields (1, 2, 3) and tuple('abc') yields ('a', 'b', 'c') . If the argument is a tuple, it does not make a copy but returns the same object, so it is cheap to call tuple() when you aren’t sure that an object is already a tuple.

The type constructor list(seq) converts any sequence or iterable into a list with the same items in the same order. For example, list((1, 2, 3)) yields [1, 2, 3] and list('abc') yields ['a', 'b', 'c'] . If the argument is a list, it makes a copy just like seq[:] would.

What’s a negative index? ¶

Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of seq[-n] as the same as seq[len(seq)-n] .

Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string.

How do I iterate over a sequence in reverse order? ¶

Use the reversed() built-in function:

This won’t touch your original sequence, but build a new copy with reversed order to iterate over.

How do you remove duplicates from a list? ¶

See the Python Cookbook for a long discussion of many ways to do this:

https://code.activestate.com/recipes/52560/

If you don’t mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go:

If all elements of the list may be used as set keys (i.e. they are all hashable ) this is often faster

This converts the list into a set, thereby removing duplicates, and then back into a list.

How do you remove multiple items from a list ¶

As with removing duplicates, explicitly iterating in reverse with a delete condition is one possibility. However, it is easier and faster to use slice replacement with an implicit or explicit forward iteration. Here are three variations.:

The list comprehension may be fastest.

How do you make an array in Python? ¶

Use a list:

Lists are equivalent to C or Pascal arrays in their time complexity; the primary difference is that a Python list can contain objects of many different types.

The array module also provides methods for creating arrays of fixed types with compact representations, but they are slower to index than lists. Also note that NumPy and other third party packages define array-like structures with various characteristics as well.

To get Lisp-style linked lists, you can emulate cons cells using tuples:

If mutability is desired, you could use lists instead of tuples. Here the analogue of a Lisp car is lisp_list[0] and the analogue of cdr is lisp_list[1] . Only do this if you’re sure you really need to, because it’s usually a lot slower than using Python lists.

How do I create a multidimensional list? ¶

You probably tried to make a multidimensional array like this:

This looks correct if you print it:

But when you assign a value, it shows up in multiple places:

The reason is that replicating a list with * doesn’t create copies, it only creates references to the existing objects. The *3 creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want.

The suggested approach is to create a list of the desired length first and then fill in each element with a newly created list:

This generates a list containing 3 different lists of length two. You can also use a list comprehension:

Or, you can use an extension that provides a matrix datatype; NumPy is the best known.

How do I apply a method or function to a sequence of objects? ¶

To call a method or function and accumulate the return values is a list, a list comprehension is an elegant solution:

To just run the method or function without saving the return values, a plain for loop will suffice:

Why does a_tuple[i] += [‘item’] raise an exception when the addition works? ¶

This is because of a combination of the fact that augmented assignment operators are assignment operators, and the difference between mutable and immutable objects in Python.

This discussion applies in general when augmented assignment operators are applied to elements of a tuple that point to mutable objects, but we’ll use a list and += as our exemplar.

If you wrote:

The reason for the exception should be immediately clear: 1 is added to the object a_tuple[0] points to ( 1 ), producing the result object, 2 , but when we attempt to assign the result of the computation, 2 , to element 0 of the tuple, we get an error because we can’t change what an element of a tuple points to.

Under the covers, what this augmented assignment statement is doing is approximately this:

It is the assignment part of the operation that produces the error, since a tuple is immutable.

When you write something like:

The exception is a bit more surprising, and even more surprising is the fact that even though there was an error, the append worked:

To see why this happens, you need to know that (a) if an object implements an __iadd__() magic method, it gets called when the += augmented assignment is executed, and its return value is what gets used in the assignment statement; and (b) for lists, __iadd__() is equivalent to calling extend() on the list and returning the list. That’s why we say that for lists, += is a “shorthand” for list.extend() :

This is equivalent to:

The object pointed to by a_list has been mutated, and the pointer to the mutated object is assigned back to a_list . The end result of the assignment is a no-op, since it is a pointer to the same object that a_list was previously pointing to, but the assignment still happens.

Thus, in our tuple example what is happening is equivalent to:

The __iadd__() succeeds, and thus the list is extended, but even though result points to the same object that a_tuple[0] already points to, that final assignment still results in an error, because tuples are immutable.

I want to do a complicated sort: can you do a Schwartzian Transform in Python? ¶

The technique, attributed to Randal Schwartz of the Perl community, sorts the elements of a list by a metric which maps each element to its “sort value”. In Python, use the key argument for the list.sort() method:

How can I sort one list by values from another list? ¶

Merge them into an iterator of tuples, sort the resulting list, and then pick out the element you want.

What is a class? ¶

A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a datatype.

A class can be based on one or more other classes, called its base class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance. You might have a generic Mailbox class that provides basic accessor methods for a mailbox, and subclasses such as MboxMailbox , MaildirMailbox , OutlookMailbox that handle various specific mailbox formats.

What is a method? ¶

A method is a function on some object x that you normally call as x.name(arguments...) . Methods are defined as functions inside the class definition:

What is self? ¶

Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c) .

See also Why must ‘self’ be used explicitly in method definitions and calls? .

How do I check if an object is an instance of a given class or of a subclass of it? ¶

Use the built-in function isinstance(obj, cls) . You can check if an object is an instance of any of a number of classes by providing a tuple instead of a single class, e.g. isinstance(obj, (class1, class2, ...)) , and can also check whether an object is one of Python’s built-in types, e.g. isinstance(obj, str) or isinstance(obj, (int, float, complex)) .

Note that isinstance() also checks for virtual inheritance from an abstract base class . So, the test will return True for a registered class even if hasn’t directly or indirectly inherited from it. To test for “true inheritance”, scan the MRO of the class:

Note that most programs do not use isinstance() on user-defined classes very often. If you are developing the classes yourself, a more proper object-oriented style is to define methods on the classes that encapsulate a particular behaviour, instead of checking the object’s class and doing a different thing based on what class it is. For example, if you have a function that does something:

A better approach is to define a search() method on all the classes and just call it:

What is delegation? ¶

Delegation is an object oriented technique (also called a design pattern). Let’s say you have an object x and want to change the behaviour of just one of its methods. You can create a new class that provides a new implementation of the method you’re interested in changing and delegates all other methods to the corresponding method of x .

Python programmers can easily implement delegation. For example, the following class implements a class that behaves like a file but converts all written data to uppercase:

Here the UpperOut class redefines the write() method to convert the argument string to uppercase before calling the underlying self._outfile.write() method. All other methods are delegated to the underlying self._outfile object. The delegation is accomplished via the __getattr__() method; consult the language reference for more information about controlling attribute access.

Note that for more general cases delegation can get trickier. When attributes must be set as well as retrieved, the class must define a __setattr__() method too, and it must do so carefully. The basic implementation of __setattr__() is roughly equivalent to the following:

Most __setattr__() implementations must modify self.__dict__ to store local state for self without causing an infinite recursion.

How do I call a method defined in a base class from a derived class that extends it? ¶

Use the built-in super() function:

In the example, super() will automatically determine the instance from which it was called (the self value), look up the method resolution order (MRO) with type(self).__mro__ , and return the next in line after Derived in the MRO: Base .

How can I organize my code to make it easier to change the base class? ¶

You could assign the base class to an alias and derive from the alias. Then all you have to change is the value assigned to the alias. Incidentally, this trick is also handy if you want to decide dynamically (e.g. depending on availability of resources) which base class to use. Example:

How do I create static class data and static class methods? ¶

Both static data and static methods (in the sense of C++ or Java) are supported in Python.

For static data, simply define a class attribute. To assign a new value to the attribute, you have to explicitly use the class name in the assignment:

c.count also refers to C.count for any c such that isinstance(c, C) holds, unless overridden by c itself or by some class on the base-class search path from c.__class__ back to C .

Caution: within a method of C, an assignment like self.count = 42 creates a new and unrelated instance named “count” in self ’s own dict. Rebinding of a class-static data name must always specify the class whether inside a method or not:

Static methods are possible:

However, a far more straightforward way to get the effect of a static method is via a simple module-level function:

If your code is structured so as to define one class (or tightly related class hierarchy) per module, this supplies the desired encapsulation.

How can I overload constructors (or methods) in Python? ¶

This answer actually applies to all methods, but the question usually comes up first in the context of constructors.

In C++ you’d write

In Python you have to write a single constructor that catches all cases using default arguments. For example:

This is not entirely equivalent, but close enough in practice.

You could also try a variable-length argument list, e.g.

The same approach works for all method definitions.

I try to use __spam and I get an error about _SomeClassName__spam. ¶

Variable names with double leading underscores are “mangled” to provide a simple but effective way to define class private variables. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam , where classname is the current class name with any leading underscores stripped.

This doesn’t guarantee privacy: an outside user can still deliberately access the “_classname__spam” attribute, and private values are visible in the object’s __dict__ . Many Python programmers never bother to use private variable names at all.

My class defines __del__ but it is not called when I delete the object. ¶

There are several possible reasons for this.

The del statement does not necessarily call __del__() – it simply decrements the object’s reference count, and if this reaches zero __del__() is called.

If your data structures contain circular links (e.g. a tree where each child has a parent reference and each parent has a list of children) the reference counts will never go back to zero. Once in a while Python runs an algorithm to detect such cycles, but the garbage collector might run some time after the last reference to your data structure vanishes, so your __del__() method may be called at an inconvenient and random time. This is inconvenient if you’re trying to reproduce a problem. Worse, the order in which object’s __del__() methods are executed is arbitrary. You can run gc.collect() to force a collection, but there are pathological cases where objects will never be collected.

Despite the cycle collector, it’s still a good idea to define an explicit close() method on objects to be called whenever you’re done with them. The close() method can then remove attributes that refer to subobjects. Don’t call __del__() directly – __del__() should call close() and close() should make sure that it can be called more than once for the same object.

Another way to avoid cyclical references is to use the weakref module, which allows you to point to objects without incrementing their reference count. Tree data structures, for instance, should use weak references for their parent and sibling references (if they need them!).

Finally, if your __del__() method raises an exception, a warning message is printed to sys.stderr .

How do I get a list of all instances of a given class? ¶

Python does not keep track of all instances of a class (or of a built-in type). You can program the class’s constructor to keep track of all instances by keeping a list of weak references to each instance.

Why does the result of id() appear to be not unique? ¶

The id() builtin returns an integer that is guaranteed to be unique during the lifetime of the object. Since in CPython, this is the object’s memory address, it happens frequently that after an object is deleted from memory, the next freshly created object is allocated at the same position in memory. This is illustrated by this example:

The two ids belong to different integer objects that are created before, and deleted immediately after execution of the id() call. To be sure that objects whose id you want to examine are still alive, create another reference to the object:

When can I rely on identity tests with the is operator? ¶

The is operator tests for object identity. The test a is b is equivalent to id(a) == id(b) .

The most important property of an identity test is that an object is always identical to itself, a is a always returns True . Identity tests are usually faster than equality tests. And unlike equality tests, identity tests are guaranteed to return a boolean True or False .

However, identity tests can only be substituted for equality tests when object identity is assured. Generally, there are three circumstances where identity is guaranteed:

1) Assignments create new names but do not change object identity. After the assignment new = old , it is guaranteed that new is old .

2) Putting an object in a container that stores object references does not change object identity. After the list assignment s[0] = x , it is guaranteed that s[0] is x .

3) If an object is a singleton, it means that only one instance of that object can exist. After the assignments a = None and b = None , it is guaranteed that a is b because None is a singleton.

In most other circumstances, identity tests are inadvisable and equality tests are preferred. In particular, identity tests should not be used to check constants such as int and str which aren’t guaranteed to be singletons:

Likewise, new instances of mutable containers are never identical:

In the standard library code, you will see several common patterns for correctly using identity tests:

1) As recommended by PEP 8 , an identity test is the preferred way to check for None . This reads like plain English in code and avoids confusion with other objects that may have boolean values that evaluate to false.

2) Detecting optional arguments can be tricky when None is a valid input value. In those situations, you can create a singleton sentinel object guaranteed to be distinct from other objects. For example, here is how to implement a method that behaves like dict.pop() :

3) Container implementations sometimes need to augment equality tests with identity tests. This prevents the code from being confused by objects such as float('NaN') that are not equal to themselves.

For example, here is the implementation of collections.abc.Sequence.__contains__() :

How can a subclass control what data is stored in an immutable instance? ¶

When subclassing an immutable type, override the __new__() method instead of the __init__() method. The latter only runs after an instance is created, which is too late to alter data in an immutable instance.

All of these immutable classes have a different signature than their parent class:

The classes can be used like this:

How do I cache method calls? ¶

The two principal tools for caching methods are functools.cached_property() and functools.lru_cache() . The former stores results at the instance level and the latter at the class level.

The cached_property approach only works with methods that do not take any arguments. It does not create a reference to the instance. The cached method result will be kept only as long as the instance is alive.

The advantage is that when an instance is no longer used, the cached method result will be released right away. The disadvantage is that if instances accumulate, so too will the accumulated method results. They can grow without bound.

The lru_cache approach works with methods that have hashable arguments. It creates a reference to the instance unless special efforts are made to pass in weak references.

The advantage of the least recently used algorithm is that the cache is bounded by the specified maxsize . The disadvantage is that instances are kept alive until they age out of the cache or until the cache is cleared.

This example shows the various techniques:

The above example assumes that the station_id never changes. If the relevant instance attributes are mutable, the cached_property approach can’t be made to work because it cannot detect changes to the attributes.

To make the lru_cache approach work when the station_id is mutable, the class needs to define the __eq__() and __hash__() methods so that the cache can detect relevant attribute updates:

How do I create a .pyc file? ¶

When a module is imported for the first time (or when the source file has changed since the current compiled file was created) a .pyc file containing the compiled code should be created in a __pycache__ subdirectory of the directory containing the .py file. The .pyc file will have a filename that starts with the same name as the .py file, and ends with .pyc , with a middle component that depends on the particular python binary that created it. (See PEP 3147 for details.)

One reason that a .pyc file may not be created is a permissions problem with the directory containing the source file, meaning that the __pycache__ subdirectory cannot be created. This can happen, for example, if you develop as one user but run as another, such as if you are testing with a web server.

Unless the PYTHONDONTWRITEBYTECODE environment variable is set, creation of a .pyc file is automatic if you’re importing a module and Python has the ability (permissions, free space, etc…) to create a __pycache__ subdirectory and write the compiled module to that subdirectory.

Running Python on a top level script is not considered an import and no .pyc will be created. For example, if you have a top-level module foo.py that imports another module xyz.py , when you run foo (by typing python foo.py as a shell command), a .pyc will be created for xyz because xyz is imported, but no .pyc file will be created for foo since foo.py isn’t being imported.

If you need to create a .pyc file for foo – that is, to create a .pyc file for a module that is not imported – you can, using the py_compile and compileall modules.

The py_compile module can manually compile any module. One way is to use the compile() function in that module interactively:

This will write the .pyc to a __pycache__ subdirectory in the same location as foo.py (or you can override that with the optional parameter cfile ).

You can also automatically compile all files in a directory or directories using the compileall module. You can do it from the shell prompt by running compileall.py and providing the path of a directory containing Python files to compile:

How do I find the current module name? ¶

A module can find out its own module name by looking at the predefined global variable __name__ . If this has the value '__main__' , the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking __name__ :

How can I have modules that mutually import each other? ¶

Suppose you have the following modules:

The problem is that the interpreter will perform the following steps:

main imports foo

Empty globals for foo are created

foo is compiled and starts executing

foo imports bar

Empty globals for bar are created

bar is compiled and starts executing

bar imports foo (which is a no-op since there already is a module named foo )

The import mechanism tries to read foo_var from foo globals, to set bar.foo_var = foo.foo_var

The last step fails, because Python isn’t done with interpreting foo yet and the global symbol dictionary for foo is still empty.

The same thing happens when you use import foo , and then try to access foo.foo_var in global code.

There are (at least) three possible workarounds for this problem.

Guido van Rossum recommends avoiding all uses of from <module> import ... , and placing all code inside functions. Initializations of global variables and class variables should use constants or built-in functions only. This means everything from an imported module is referenced as <module>.<name> .

Jim Roskind suggests performing steps in the following order in each module:

exports (globals, functions, and classes that don’t need imported base classes)

import statements

active code (including globals that are initialized from imported values).

Van Rossum doesn’t like this approach much because the imports appear in a strange place, but it does work.

Matthias Urlichs recommends restructuring your code so that the recursive import is not necessary in the first place.

These solutions are not mutually exclusive.

__import__(‘x.y.z’) returns <module ‘x’>; how do I get z? ¶

Consider using the convenience function import_module() from importlib instead:

When I edit an imported module and reimport it, the changes don’t show up. Why does this happen? ¶

For reasons of efficiency as well as consistency, Python only reads the module file on the first time a module is imported. If it didn’t, in a program consisting of many modules where each one imports the same basic module, the basic module would be parsed and re-parsed many times. To force re-reading of a changed module, do this:

Warning: this technique is not 100% fool-proof. In particular, modules containing statements like

will continue to work with the old version of the imported objects. If the module contains class definitions, existing class instances will not be updated to use the new class definition. This can result in the following paradoxical behaviour:

The nature of the problem is made clear if you print out the “identity” of the class objects:

Table of Contents

  • General Questions
  • Core Language
  • Numbers and strings
  • Performance
  • Sequences (Tuples/Lists)

Previous topic

General Python FAQ

Design and History FAQ

  • Report a Bug
  • Show Source

IMAGES

  1. Worksheets for Python Global Variable In Function Referenced Before

    python3 global variable referenced before assignment

  2. [Python 3.X] "local variable referenced before assignment"

    python3 global variable referenced before assignment

  3. How to fix : Local variable referenced before assignment In Python

    python3 global variable referenced before assignment

  4. python

    python3 global variable referenced before assignment

  5. Variable in Python

    python3 global variable referenced before assignment

  6. PYTHON : Local (?) variable referenced before assignment

    python3 global variable referenced before assignment

VIDEO

  1. 📦Variables in Python

  2. Python global variable

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

  4. Python Global Keywords #python3 #technologies #datascience #softskills #ai

  5. Local and Global Variables in Python (Python Tutorial

  6. Python Global Variables ❓#python3 #programming #ml #dataanalytics #datascience

COMMENTS

  1. 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 See this example:

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

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

  4. Local variable referenced before assignment in Python

    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.

  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. How to Fix Local Variable Referenced Before Assignment Error in Python

    value = value + 1 We are defining a local variable called value and then trying to use it before it has been assigned a value, instead of using the variable that we defined in the first line.. If we want to refer the variable that was defined in the first line, we can make use of the global keyword.. The global keyword is used to refer to a variable that is defined outside of a function.

  8. UnboundLocalError Local variable Referenced Before Assignment in Python

    Below, code calculates a new value (local_var) based on the global variable and then prints both the local and global variables separately. It demonstrates that the global variable is accessed directly without being reassigned within the function.

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

  10. Local Variable Referenced Before Assignment in Python

    This tutorial explains the reason and solution of the python error local variable referenced before assignment

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

  12. 4 Ways to Fix Local Variable Referenced Before Assignment Error in

    These strategies include initializing variables before referencing, using the global keyword, adding input parameters to functions, and initializing variables before loops or conditionals. These techniques help to ensure clean code that is free from errors.

  13. Local variable referenced before assignment?

    in the function definition. The global statement does not have to be at the beginning of the function definition, but that is where it is usually placed. Wherever it is placed, the global declaration makes feed a global variable everywhere in the function. Without the global statement, since feed is taken to be a local variable, when Python ...

  14. [SOLVED] Local Variable Referenced Before Assignment

    Global Variables; A local variable is declared primarily within a Python function. Global variables are in the global scope, outside a function. A local variable is created when the function is called and destroyed when the execution is finished. A Global Variable is created upon execution and exists in memory till the program stops.

  15. 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()

  16. local variable referenced before assignment in python when i set it global

    6. You need to declare a global variable. def shift_arrange(worker): global counter. for day in days.values(): counter+=1. ... Since you modify counter in that scope, python treats it as a local variable, unless you declare it as global. If you only need to read it, that isn't necessary.

  17. Programming FAQ

    UnboundLocalError: local variable 'x' referenced before assignment. ... Initializations of global variables and class variables should use constants or built-in functions only. This means everything from an imported module is referenced as <module>.<name>.

  18. Global variable referenced before assignment?

    Global variable values in PyCharm (Python 3.6) console. 2. pycharm can't reference global variable inside a function. 0. Global Variable appearing as local variable. 1. Warning - variable referenced before assignment. 1. ... local variable referenced before assignment, Python. Hot Network Questions

  19. Why do I get a 'referenced before assignment' error, for a variable

    Because you can read the values of global variables without doing anything special, but not write them unless you use the global keyword.. In this line my_num = my_num + 1 you are trying to read and write a global variable. Since you didn't specify that my_num is a global variable with global my_num in your function, the interpreter sees the left hand side of the assignment as a new local ...

  20. global variable referenced before assignment

    global variable referenced before assignment. Ask Question Asked 5 years, 8 months ago. Modified 5 years, 8 months ago. ... if patientName!="123" --> throws global variable patientName referenced before assignment.... Thanks! python; python-2.7; Share. Improve this question. Follow edited May 31, 2018 at 22:25. Logan. 936 1 1 gold badge 10 10 ...

  21. local variable referenced before assignment but variable is global

    1. Python treats your variable answer as a local variable as in your answerCheck () function, under the else clause, there is an assignment done to the variable answer. Since there is an assignment involved within the local scope, python treats the variable to be in the local scope and this gives your issue. As long as you don't use assignment ...