| 242 | file.close() |
| 243 | |
| 244 | def __del__(self) -> None: |
| 245 | # If we're the only CachingFileManger referencing an unclosed file, |
| 246 | # remove it from the cache upon garbage collection. |
| 247 | # |
| 248 | # We keep track of our own reference count because we don't want to |
| 249 | # close files if another identical file manager needs it. This can |
| 250 | # happen if a CachingFileManager is pickled and unpickled without |
| 251 | # closing the original file. |
| 252 | ref_count = self._ref_counter.decrement(self._key) |
| 253 | |
| 254 | if not ref_count and self._key in self._cache: |
| 255 | if acquire(self._lock, blocking=False): |
| 256 | # Only close files if we can do so immediately. |
| 257 | try: |
| 258 | self.close(needs_lock=False) |
| 259 | finally: |
| 260 | self._lock.release() |
| 261 | |
| 262 | if OPTIONS["warn_for_unclosed_files"]: |
| 263 | warnings.warn( |
| 264 | f"deallocating {self}, but file is not already closed. " |
| 265 | "This may indicate a bug.", |
| 266 | RuntimeWarning, |
| 267 | stacklevel=2, |
| 268 | ) |
| 269 | |
| 270 | def __getstate__(self): |
| 271 | """State for pickling.""" |