Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a81088a

Browse files
committed
(Merge 3.4) Issue #11453: asyncore: emit a ResourceWarning when an unclosed
file_wrapper object is destroyed. The destructor now closes the file if needed. The close() method can now be called twice: the second call does nothing.
2 parents c3bc856 + 4d4c69d commit a81088a

3 files changed

Lines changed: 28 additions & 0 deletions

File tree

Lib/asyncore.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,11 @@ class file_wrapper:
600600
def __init__(self, fd):
601601
self.fd = os.dup(fd)
602602

603+
def __del__(self):
604+
if self.fd >= 0:
605+
warnings.warn("unclosed file %r" % self, ResourceWarning)
606+
self.close()
607+
603608
def recv(self, *args):
604609
return os.read(self.fd, *args)
605610

@@ -618,7 +623,10 @@ def getsockopt(self, level, optname, buflen=None):
618623
write = send
619624

620625
def close(self):
626+
if self.fd < 0:
627+
return
621628
os.close(self.fd)
629+
self.fd = -1
622630

623631
def fileno(self):
624632
return self.fd

Lib/test/test_asyncore.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,22 @@ def handle_read(self):
413413
asyncore.loop(timeout=0.01, use_poll=True, count=2)
414414
self.assertEqual(b"".join(data), self.d)
415415

416+
def test_resource_warning(self):
417+
# Issue #11453
418+
fd = os.open(support.TESTFN, os.O_RDONLY)
419+
f = asyncore.file_wrapper(fd)
420+
with support.check_warnings(('', ResourceWarning)):
421+
f = None
422+
support.gc_collect()
423+
424+
def test_close_twice(self):
425+
fd = os.open(support.TESTFN, os.O_RDONLY)
426+
f = asyncore.file_wrapper(fd)
427+
f.close()
428+
self.assertEqual(f.fd, -1)
429+
# calling close twice should not fail
430+
f.close()
431+
416432

417433
class BaseTestHandler(asyncore.dispatcher):
418434

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,10 @@ Core and Builtins
103103
Library
104104
-------
105105

106+
- Issue #11453: asyncore: emit a ResourceWarning when an unclosed file_wrapper
107+
object is destroyed. The destructor now closes the file if needed. The
108+
close() method can now be called twice: the second call does nothing.
109+
106110
- Issue #21858: Better handling of Python exceptions in the sqlite3 module.
107111

108112
- Issue #21476: Make sure the email.parser.BytesParser TextIOWrapper is

0 commit comments

Comments
 (0)