Skip to content

Instantly share code, notes, and snippets.

@cornchz
Created April 25, 2012 07:29
Show Gist options
  • Save cornchz/2487760 to your computer and use it in GitHub Desktop.
Save cornchz/2487760 to your computer and use it in GitHub Desktop.
return generator inside a with statement

generator에 대한 뭔가를 쓰다가 발견했다.

만들고 싶었던 함수는 이거.

def readlines(filename):
    with open(filename, 'r') as f:
        for line in f:
            yield line

print ''.join(readlines('test.txt'))

그런데, for line in f: yield line은 보통 generator expression을 이용해서 return (line for line in f)처럼 쓸 수 있잖아?
게다가 그쪽이 더 직관적이니까 고치려고 했는데... 생각해 보니 그렇게 하면 return하는 순간 with statement가 close돼 버려서 나중에 yield 되는 순간엔 f에 접근하지 못할 거 같다는 생각이.
근데 또 한편으로는 '파이썬이 어련히 잘 해놓지 않았을까...' 하는 생각도. 그래서 해봤다.

def readlines(filename):
    with open(filename, 'r') as f:
        return (line for line in f)

결과는?

Traceback (most recent call last):
  File "generator.py", line 8, in <module>
    print '\n'.join(read_lines())
  File "generator.py", line 6, in <genexpr>
    return (line for line in f)
ValueError: I/O operation on closed file

역시 안 되는구나ㅋㅋ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment