Function to create and return a unique temporary file with the given extension, if provided. Parameters ---------- extension : str The extension of the temporary file to be created dir : str If ``dir`` is not None, the file will be created in that directory; oth
(extension="", dir=None)
| 332 | |
| 333 | @contextmanager |
| 334 | def tmpfile(extension="", dir=None): |
| 335 | """ |
| 336 | Function to create and return a unique temporary file with the given extension, if provided. |
| 337 | |
| 338 | Parameters |
| 339 | ---------- |
| 340 | extension : str |
| 341 | The extension of the temporary file to be created |
| 342 | dir : str |
| 343 | If ``dir`` is not None, the file will be created in that directory; otherwise, |
| 344 | Python's default temporary directory is used. |
| 345 | |
| 346 | Returns |
| 347 | ------- |
| 348 | out : str |
| 349 | Path to the temporary file |
| 350 | |
| 351 | See Also |
| 352 | -------- |
| 353 | NamedTemporaryFile : Built-in alternative for creating temporary files |
| 354 | tmp_path : pytest fixture for creating a temporary directory unique to the test invocation |
| 355 | |
| 356 | Notes |
| 357 | ----- |
| 358 | This context manager is particularly useful on Windows for opening temporary files multiple times. |
| 359 | """ |
| 360 | extension = extension.lstrip(".") |
| 361 | if extension: |
| 362 | extension = f".{extension}" |
| 363 | handle, filename = tempfile.mkstemp(extension, dir=dir) |
| 364 | os.close(handle) |
| 365 | os.remove(filename) |
| 366 | |
| 367 | try: |
| 368 | yield filename |
| 369 | finally: |
| 370 | if os.path.exists(filename): |
| 371 | with suppress(OSError): # sometimes we can't remove a generated temp file |
| 372 | if os.path.isdir(filename): |
| 373 | shutil.rmtree(filename) |
| 374 | else: |
| 375 | os.remove(filename) |
| 376 | |
| 377 | |
| 378 | @contextmanager |
searching dependent graphs…