0

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

Vitim.us
  • 18,445
  • 15
  • 88
  • 102
  • 2
    You can fix it with `def wrappedFileGen(): nonlocal i; for line in file:...` – wwii Nov 26 '20 at 19:02
  • @wwii `nonlocal i` works. why does it work for `file` variable tho? – Vitim.us Nov 26 '20 at 19:06
  • When parsing the function the parser *sees* the assignment `i = ...` and makes it a variable local to the function. The function doesn't have an assignment for `file` so there is no problem. Add `file = file` as the first line. - what happens? – wwii Nov 26 '20 at 19:32

0 Answers0