I'm quite new to Python, but I'm trying to implement my "Line file reader" and I came across an error that I don't understand why it wouldn't work.
UnboundLocalError: local variable 'i' referenced before assignment
The generator can see the file variable in the closure just fine, why can't it see i?
import contextlib
@contextlib.contextmanager
def myOpen(name):
file = open(name)
i = 0
try:
def wrappedFileGen():
for line in file:
i = i + 1 #<-- UnboundLocalError: local variable 'i' referenced before assignment
print('Line:', i)
yield line
yield wrappedFileGen()
finally:
print('Total lines read:', i)
file.close()
with myOpen('test.txt') as file:
for line in file:
print('Content:', line)
# raise "Oops"
If I declare i inside the generator it works
def wrappedFileGen():
i = 0 #<---- HERE
for line in file:
i = i + 1
print('Line:', i)
yield line
I need i in the outer scope, because I want to finalize it