Vinayak Vinayak - 3 months ago 26
Python Question

Are local variables not accessible within generator functions?

I'm learning Python and ran this piece of code in the python console earlier today:

num = 0

def generator():
while True:
yield num
num += 1

for i in generator():
if i > 5: break
print(i)


It threw a
UnboundLocalError: local variable 'num' referenced before assignment


I re-wrote the code and this version worked:

def generator():
num = 0
while True:
yield num
num += 1

for i in generator():
if i > 5: break
print(i)


My question is this: Can you not use local variables inside generator functions like you can with regular functions?

Answer

In the first code, you attempt to use num as a global variable: It is defined outside the function.

When the program reaches num += 1, you then attempt to assign to a local variable which happens to have the same name as the global that you referenced earlier. But since a local variable called num hasn't be assigned a value yet, the increment fails.

If you want to assign or increment a global variable inside a function, it must be declared with global num (usually right at the start of the function). This has nothing to do with generators, it would fail for regular functions too.