Python Nested Functions Variable Scoping

Python nested functions variable scoping

When I run your code I get this error:

UnboundLocalError: local variable '_total' referenced before assignment

This problem is caused by this line:

_total += PRICE_RANGES[key][0]

The documentation about Scopes and Namespaces says this:

A special quirk of Python is that – if no global statement is in effect – assignments to names always go into the innermost scope. Assignments do not copy data — they just bind names to objects.

So since the line is effectively saying:

_total = _total + PRICE_RANGES[key][0]

it creates _total in the namespace of recurse(). Since _total is then new and unassigned you can't use it in the addition.

Variable scope in Python nested function

It seems this is a commonly asked question as stated in this link. The reason is that variable a inside swim becomes a local variable as soon as there is an assignment to a. It shadows the external a, and local a is not defined before assignment in function swim, so the error rises.

Thanks for all your guys' answers!

Understanding variable scope in nested functions in Python

In your first case

def good_func():
sheet_num = 2
row_num = 2
a = test_file('new file')
return a

sheet_num and row_num are local to the function good_func and hence cannot be accessed in another function output_report

But when you do

sheet_num = 2
row_num = 2
def good_func():
a = test_file('new file')
return a

sheet_num and row_num become global variables accessible to all other functions, hence they are accessible in output_report as well

Also nested function are functions whose definition lies within another function like so, where a is accessible in inner

def outer():
a = 1
def inner():
print(a)
inner()

outer()

Calling another function inside a function like you do in good_func doesn't make them output_function nested.

python nested function variable scope

You have two variables named 'x', in two different scopes. I would not recommend doing this; it can lead to a lot of confusion, leading to bugs in the program.

I would not suggest fixing this with keywords. Rename one of the variables. If you do, the error becomes clear.

def test( root):
x_test=2
def f2(r):
print("***")
print("----",x_f2)
x_f2=r
f2(root)
return x_test
test(4)

Clearly, x_f2 is being referenced before assignment. When you write the code like this, the error is clear.

This is exactly what your code is doing; it is just not clear because you have two variables with the same name, in different scopes.

The 'x' inside f2 is a local variable in the function, and you can not use it before assigning it. The fact that in the outer scope there is a different variable named 'x' which has been assigned, does not change that.

Can a Python nested function variable be used in other nested functions?

You just need to return them in func1 and pass the results to func2

def func1():
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
return a, b

Then,

def func2(a, b):
print(f"{a}, {b}")

And then when you call the functions you assign variables a and b to the result of func1 and pass them as parameters to func2,

a,b = func1()
func2(a, b)

You could initialize the variables in the scope of func but it is better to handle them as the return of the function, it easier to keep track of the algorithm that way.

Using Global Variables inside a Nested Function in Python

In add, x is not a global variable; it's local to add. You either need to make it global as well, so that add and change are referring to the same variable

def add(): 
global x
x = 15

def change():
global x
x = 20
print("Before making changes: ", x)
print("Making change")
change()
print("After making change: ", x)

add()
print("value of x",x)

or you need to declare x in change as nonlocal, rather than global.

def add(): 
x = 15

def change():
nonlocal x
x = 20
print("Before making changes: ", x)
print("Making change")
change()
print("After making change: ", x)

add()
print("value of x",x)


Related Topics



Leave a reply



Submit