Một số mã:Tôi có phải thực hiện StringIO.close() không?
import cStringIO
def f():
buffer = cStringIO.StringIO()
buffer.write('something')
return buffer.getvalue()
Các documentation nói:
StringIO.close()
: Miễn phí bộ nhớ đệm. Cố gắng thực hiện thêm các hoạt động với đối tượng StringIO đã đóng sẽ tăng giá trị ValueError.
Tôi có phải làm buffer.close()
hoặc tự động xảy ra khi bộ đệm nằm ngoài phạm vi và rác có được thu thập không?
UPDATE:
Tôi đã làm một thử nghiệm:
import StringIO, weakref
def handler(ref):
print 'Buffer died!'
def f():
buffer = StringIO.StringIO()
ref = weakref.ref(buffer, handler)
buffer.write('something')
return buffer.getvalue()
print 'before f()'
f()
print 'after f()'
Kết quả:
[email protected]:~/projects$ python test.py
before f()
Buffer died!
after f()
[email protected]:~/projects$
tại sao không in f() thay vì chỉ là một f (thường)? – mpag