MCPcopy Index your code
hub / github.com/python/cpython / _TemporaryFileWrapper

Class _TemporaryFileWrapper

Lib/tempfile.py:487–556  ·  view source on GitHub ↗

Temporary file wrapper This class provides a wrapper around files opened for temporary use. In particular, it seeks to automatically remove the file when it is no longer needed.

Source from the content-addressed store, hash-verified

485
486
487class _TemporaryFileWrapper:
488 """Temporary file wrapper
489
490 This class provides a wrapper around files opened for
491 temporary use. In particular, it seeks to automatically
492 remove the file when it is no longer needed.
493 """
494
495 def __init__(self, file, name, delete=True, delete_on_close=True):
496 self.file = file
497 self.name = name
498 self._closer = _TemporaryFileCloser(
499 file,
500 name,
501 delete,
502 delete_on_close,
503 warn_message=f"Implicitly cleaning up {self!r}",
504 )
505
506 def __repr__(self):
507 file = self.__dict__['file']
508 return f"<{type(self).__name__} {file=}>"
509
510 def __getattr__(self, name):
511 # Attribute lookups are delegated to the underlying file
512 # and cached for non-numeric results
513 # (i.e. methods are cached, closed and friends are not)
514 file = self.__dict__['file']
515 a = getattr(file, name)
516 if hasattr(a, '__call__'):
517 func = a
518 @_functools.wraps(func)
519 def func_wrapper(*args, **kwargs):
520 return func(*args, **kwargs)
521 # Avoid closing the file as long as the wrapper is alive,
522 # see issue #18879.
523 func_wrapper._closer = self._closer
524 a = func_wrapper
525 if not isinstance(a, int):
526 setattr(self, name, a)
527 return a
528
529 # The underlying __enter__ method returns the wrong object
530 # (self.file) so override it to return the wrapper
531 def __enter__(self):
532 self.file.__enter__()
533 return self
534
535 # Need to trap __exit__ as well to ensure the file gets
536 # deleted when used in a with statement
537 def __exit__(self, exc, value, tb):
538 result = self.file.__exit__(exc, value, tb)
539 self._closer.cleanup()
540 return result
541
542 def close(self):
543 """
544 Close the temporary file, possibly deleting it.

Callers 1

NamedTemporaryFileFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…