From ad61bc8d9bb3839341ee99b2befc6760c44179d4 Mon Sep 17 00:00:00 2001 From: Georg Brandl Date: Sat, 23 Feb 2008 15:11:18 +0000 Subject: [PATCH] #2067: file.__exit__() now calls subclasses' close() method. --- Lib/test/test_file.py | 18 +++++++++++++++++- Misc/NEWS | 4 +++- Objects/fileobject.c | 4 ++-- 3 files changed, 22 insertions(+), 4 deletions(-) diff --git a/Lib/test/test_file.py b/Lib/test/test_file.py index 73cb5b2412..3ae460c976 100644 --- a/Lib/test/test_file.py +++ b/Lib/test/test_file.py @@ -322,12 +322,28 @@ class OtherFileTests(unittest.TestCase): finally: os.unlink(TESTFN) +class FileSubclassTests(unittest.TestCase): + + def testExit(self): + # test that exiting with context calls subclass' close + class C(file): + def __init__(self, *args): + self.subclass_closed = False + file.__init__(self, *args) + def close(self): + self.subclass_closed = True + file.close(self) + + with C(TESTFN, 'w') as f: + pass + self.failUnless(f.subclass_closed) + def test_main(): # Historically, these tests have been sloppy about removing TESTFN. # So get rid of it no matter what. try: - run_unittest(AutoFileTests, OtherFileTests) + run_unittest(AutoFileTests, OtherFileTests, FileSubclassTests) finally: if os.path.exists(TESTFN): os.unlink(TESTFN) diff --git a/Misc/NEWS b/Misc/NEWS index c1172de5c6..e1fc418afb 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -12,7 +12,9 @@ What's New in Python 2.6 alpha 1? Core and builtins ----------------- -- Patch #1759: Backport of PEP 3129 class decorators +- Issue #2067: file.__exit__() now calls subclasses' close() method. + +- Patch #1759: Backport of PEP 3129 class decorators. - Issue #1881: An internal parser limit has been increased. Also see issue 215555 for a discussion. diff --git a/Objects/fileobject.c b/Objects/fileobject.c index eb05cdad51..932b7dc74d 100644 --- a/Objects/fileobject.c +++ b/Objects/fileobject.c @@ -1660,9 +1660,9 @@ file_self(PyFileObject *f) } static PyObject * -file_exit(PyFileObject *f, PyObject *args) +file_exit(PyObject *f, PyObject *args) { - PyObject *ret = file_close(f); + PyObject *ret = PyObject_CallMethod(f, "close", NULL); if (!ret) /* If error occurred, pass through */ return NULL; -- 2.40.0