diff -r 6cb93e45a3be Lib/tempfile.py --- a/Lib/tempfile.py Sun Dec 15 19:50:13 2013 +0100 +++ b/Lib/tempfile.py Sun Dec 15 23:08:51 2013 +0200 @@ -27,6 +27,7 @@ # Imports. +import functools as _functools import warnings as _warnings import sys as _sys import io as _io @@ -349,6 +350,15 @@ # (i.e. methods are cached, closed and friends are not) file = self.__dict__['file'] a = getattr(file, name) + if hasattr(a, '__call__'): + func = a + @_functools.wraps(func) + def func_wrapper(*args, **kwargs): + # This is to prevent self getting out of scope too early, + # see bug 18879 + local_self_copy = self + return func(*args, **kwargs) + a = func_wrapper if not isinstance(a, int): setattr(self, name, a) return a diff -r 6cb93e45a3be Lib/test/test_tempfile.py --- a/Lib/test/test_tempfile.py Sun Dec 15 19:50:13 2013 +0100 +++ b/Lib/test/test_tempfile.py Sun Dec 15 23:08:51 2013 +0200 @@ -689,6 +689,15 @@ self.do_create(pre="a", suf="b") self.do_create(pre="aa", suf=".txt") + def test_issue18879(self): + f = self.do_create() + write = f.write + write2 = f.write + del f + write(b'foo') + del write + write2(b'bar') + def test_creates_named(self): # NamedTemporaryFile creates files with names f = tempfile.NamedTemporaryFile()