Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] What is the best way to create temp files and directories? #1931

Open
zaygraveyard opened this issue Mar 17, 2021 · 2 comments
Open

Comments

@zaygraveyard
Copy link

Normally I would use tempfile module.
But I was wondering if there's an async (trio compatible) alternative.

Thanks in advance

@Sxderp
Copy link

Sxderp commented Mar 17, 2021

I'd do it like this. The file is still opened / created synchronously but writes are done async.

import tempfile
import trio

async def temp_file():
    my_file = tempfile.TemporaryFile()
    async with trio.wrap_file(my_file):
        await my_file.write('Yo')

@altendky
Copy link
Member

altendky commented Mar 17, 2021

I guess I'll take a stab. Hopefully someone has already implemented this and worked out all the kinks that must certainly exist (and will chime in...). For example, I don't know what context manager bits of this would pass through sensibly or not.

https://github.com/python-trio/trio/blob/v0.18.0/trio/_file_io.py#L76-L79

import functools
import tempfile

import trio


async def temporary_file(*args, **kwargs):
    sync_fn = partial(tempfile.TemporaryFile, *args, **kwargs)
    sync_file = await trio.to_thread.run_sync(sync_fn)
    return trio.wrap_file(sync_file)

Could decorate it as a wrapper but it appears that, in addition to being private, trio._util.async_wrap() is exclusively for methods.

https://github.com/python-trio/trio/blob/v0.18.0/trio/_util.py#L200-L215

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants