Defer tempfile import to sites of use#328
Defer tempfile import to sites of use#328Sachaa-Thanasius wants to merge 2 commits intopython:mainfrom
tempfile import to sites of use#328Conversation
tempfile import to sites of use
| with tempfile.TemporaryDirectory() as temp_dir: | ||
| yield _write_contents(pathlib.Path(temp_dir), path) |
There was a problem hiding this comment.
I don't care for this refactor. The reason _temp_path exists is to decouple the pathlib.Path construction from the invocation of the write function. Yes, it's logically the same, but without the presence of _temp_path the defect that tempfile doesn't provide pathlib objects is hidden. Let's keep _temp_path, especially as its presence isn't implicated in the purpose of this change.
| # Deferred for performance. | ||
| import tempfile |
There was a problem hiding this comment.
I'm not a fan of repeating ourselves. Now we have 6 lines of code where previous 1 was sufficient... and moreover, these lines of code are entangled (their comments both refer to the same motivation and should be kept in sync. Better would be to do:
| # Deferred for performance. | |
| import tempfile | |
| tempfile = _import_tempfile() |
And then in _import_tempfile, document the motivation, which should not only include the basic motivation ("deferred for performance"), but also details on what performance is saved. For example, it should link to the PR ("#328") and that PR should have examples of how much performance is saved.
Use |
|
When I run the tests on my Macbook Pro M3 and Python 3.14, I see a negligible benefit. Actually, that looks like a detriment. |
Part of #326.
tempfileis a relatively heavy import that's only used in a few routines, and they aren't always called when usingimportlib_resources, especially in the common case ofas_file()being passed apathlib.Pathobject. Thus, I think it's worthwhile to defer importing it until it's actually used.This PR effectively inlines the one function using
tempfileat module-level scope to avoid an import-time dependency ontempfile. It then "inlines" the necessary import in the two functions that use it.Based on local testing, doing so improves the upfront import time of
importlib_resourcesby about ~30% on supported CPython versions and ~50% on PyPy3.10.